问:
$.Ajax POST, accessing return data
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.

On my .cs file I have the following Webmethod

```<code>[WebMethod]
   public static string IsJobEditable(int jobid)
   {
       try
       {
           string isEditable = "false";

           JobsBLL jbl = new JobsBLL();

           int jobStatusId = jbl.GetJobStatusId(jobid);

           if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
           {
               isEditable = "true";
           }

           return isEditable;

       }
       catch (Exception ex)
       {

           throw ex;
       }
   }
</code>```

This function in this case will ALWAYS return TRUE as a string.

On Aspx page I have the following

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

           $.ajax({

               type: "POST",
               url: "Coordination.aspx/IsJobEditable",
               data: "{jobid:" + jobid + "}",
               contentType: "application/json; charset=utf-8",
               dataType: "text",
               success: function (result) {

                   alert(result);

                   // This is written out in the alert {"d":"true"}
                   // I want this in a variable as a string
                   // so I can do a check on it before I do some other actions
                   // The format is not a String so i cannot split on it to
                   // retrieve the "true" part.

               },
               error: function (err, result) { alert(err); }

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

As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.

So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).

答:
This solved it:

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

       $.ajax({

           type: "POST",
           url: "Coordination.aspx/IsJobEditable",
           data: "{jobid:" + jobid + "}",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (result) {

               alert(result.d);

               //I finally got the data string i wanted
               var resultAsString = result.d;

           },
           error: function (err, result) { alert(err); }

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

So 2 things were done to solve this. I had to change the dataType to "json" and I used the result.d to retrieve my data.

What threw me off was the lack of intellisens on the result object. But the .d (data) property however solved it.

Thanks you to all who contributed to this answer.

Title: $.Ajax POST, accessing return data

Body:
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.

On my .cs file I have the following Webmethod

[WebMethod]
   public static string IsJobEditable(int jobid)
   {
       try
       {
           string isEditable = "false";

           JobsBLL jbl = new JobsBLL();

           int jobStatusId = jbl.GetJobStatusId(jobid);

           if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
           {
               isEditable = "true";
           }

           return isEditable;

       }
       catch (Exception ex)
       {

           throw ex;
       }
   }

This function in this case will ALWAYS return TRUE as a string.

On Aspx page I have the following

$(function () {

           $.ajax({

               type: "POST",
               url: "Coordination.aspx/IsJobEditable",
               data: "{jobid:" + jobid + "}",
               contentType: "application/json; charset=utf-8",
               dataType: "text",
               success: function (result) {

                   alert(result);

                   // This is written out in the alert {"d":"true"}
                   // I want this in a variable as a string
                   // so I can do a check on it before I do some other actions
                   // The format is not a String so i cannot split on it to
                   // retrieve the "true" part.

               },
               error: function (err, result) { alert(err); }

           });
       });

As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.

So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).

Body:
This solved it:

$(function () {

       $.ajax({

           type: "POST",
           url: "Coordination.aspx/IsJobEditable",
           data: "{jobid:" + jobid + "}",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (result) {

               alert(result.d);

               //I finally got the data string i wanted
               var resultAsString = result.d;

           },
           error: function (err, result) { alert(err); }

       });
   });

So 2 things were done to solve this. I had to change the dataType to "json" and I used the result.d to retrieve my data.

What threw me off was the lack of intellisens on the result object. But the .d (data) property however solved it.

Thanks you to all who contributed to this answer.


来源: stackexchange

问:
Could someone explain this for me - for (i = 0; i=10; i++)
I know this below statement works

```<code>for ($i= 0; $i=<10; $i++)
</code>```

will output till 0 to 10
but when I write this code

```<code>for ($i=0; $i=10; $i++)
</code>```

it print 10 for unlimited times... why  why it not print 0 to 10...
what error I have done to get the result 0 to 10 for it....

答: if $i< or =10 Will perform,if $i> 10 will break,each time $i will +1 you can set the $i begin to value or set the maximum to achieve the result that you want.</p>

ContentLicense: CC BY-SA 3.0

Body:
I know this below statement works

for ($i= 0; $i=<10; $i++)

will output till 0 to 10
but when I write this code

for ($i=0; $i=10; $i++)

it print 10 for unlimited times... why  why it not print 0 to 10...
what error I have done to get the result 0 to 10 for it....


问:
How to update Symfony Entities from an existing database?
I found in Symfony docs that  you can Generate Entities from an Existing Database so are there any ways to update entities from existing database I added using MySQL?

For example, I added new column to my FOSUSERBUNDLE database called "batman"

using this command on MySQL:

```<code>ALTER TABLE cs_symfony_members
ADD batman int(11) NOT NULL;
</code>```

how to update my entities i generated using the docs guide above ?

答:
If you need to update database schema to Entity, you can use two command:

(1) Create entity mapping from database:

```<code>bin/console doctrine:mapping:import BundleName --filter=EntityName
</code>```

(2) Update your entity to match this mapping:

```<code>bin/console doctrine:generate:entities BundleName:EntityName
</code>```

Example, I have a User table in database, a had changed structure of this table. And now, I want to update these changes to my User entity in AppBundle. I need to run following command:

```<code>bin/console doctrine:mapping:import AppBundle --filter=User
bin/console doctrine:generate:entities AppBundle:User
</code>```

I hope this can help you!

ContentLicense: CC BY-SA 4.0

Body:
I found in Symfony docs that  you can Generate Entities from an Existing Database so are there any ways to update entities from existing database I added using MySQL?

For example, I added new column to my FOSUSERBUNDLE database called "batman"

using this command on MySQL:

ALTER TABLE cs_symfony_members
ADD batman int(11) NOT NULL;

how to update my entities i generated using the docs guide above ?

Body:
If you need to update database schema to Entity, you can use two command:

(1) Create entity mapping from database:

bin/console doctrine:mapping:import BundleName --filter=EntityName

(2) Update your entity to match this mapping:

bin/console doctrine:generate:entities BundleName:EntityName

Example, I have a User table in database, a had changed structure of this table. And now, I want to update these changes to my User entity in AppBundle. I need to run following command:

bin/console doctrine:mapping:import AppBundle --filter=User
bin/console doctrine:generate:entities AppBundle:User

I hope this can help you!


问:
random (read only) access to elements of Eigen::SparseVector
Consider the following silly code piece

```<code>typedef Eigen::SparseVector<std::complex<double>, Eigen::ColMajor,long long> Vector;

Vector V = CreateData();

for(i=0;i<V.size(),++i)
{
  DoSomething( Vector.coeffRef(i));
}
</code>```

I'm kind of interesting (for some purpose) to access (say) every elements of sparse vector V and expect, of course, zero to be returned when accessing non initialized entries.

What I'm surprisingly found is that at the access to a non existing\initialized entry, this entry is being created on reading, with the correct value of zero of course, but why???

I'm definitely not interesting in such behavior. All I want to get is zero returned whenever a non initialized entry being accessed for reading, otherwise a cast to full matrix is faster.
Is there an alternative to .coeffRef that won't allocate new entries.

答: Use the coeff() method instead of the coeffRef() one. It does exactly what you want. On the other hand, coeffRef() returns a reference for read-write access, so the element must exist.

Body:
Consider the following silly code piece

typedef Eigen::SparseVector<std::complex<double>, Eigen::ColMajor,long long> Vector;

Vector V = CreateData();

for(i=0;i<V.size(),++i)
{
  DoSomething( Vector.coeffRef(i));
}

I'm kind of interesting (for some purpose) to access (say) every elements of sparse vector V and expect, of course, zero to be returned when accessing non initialized entries.

What I'm surprisingly found is that at the access to a non existing\initialized entry, this entry is being created on reading, with the correct value of zero of course, but why???

I'm definitely not interesting in such behavior. All I want to get is zero returned whenever a non initialized entry being accessed for reading, otherwise a cast to full matrix is faster.
Is there an alternative to .coeffRef that won't allocate new entries.


问:
ExpressJS does not seem to work with ajax calls
I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.

My ajax call:

```<code>$.ajax({
        method: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "localhost:8000/login",
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function () {
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });
</code>```

In my express:

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', function (req, res) {
  var user = req.body.user;
  var password = req.body.pass;
  if(user == 'john' && password == '123') {
    res.status(200);
  } else {
    res.status(401);
  }
});

app.listen(8000, function () {
  console.log('Example app listening on port 8000!');
});
</code>```

Any help is greatly appreciated.

答:
This work for me:</p>

```<code>   $.ajax({
        type: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "/login",
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function (err) {
            console.log(err);
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });
    app.post('/login', function (req, res, next) {
    var user = req.body.user;
    var password = req.body.pass;
    if(user == 'john' && password == '123') {
    res.status(200).json({s: 1});
    } else {
    res.status(401).json({e: 2});
    }
   });
</code>```

Body:
I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.

My ajax call:

$.ajax({
        method: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "localhost:8000/login",
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function () {
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });

In my express:

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

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', function (req, res) {
  var user = req.body.user;
  var password = req.body.pass;
  if(user == 'john' && password == '123') {
    res.status(200);
  } else {
    res.status(401);
  }
});

app.listen(8000, function () {
  console.log('Example app listening on port 8000!');
});

Any help is greatly appreciated.

Body:
This work for me:

   $.ajax({
        type: "POST",
        contentType: 'application/json',
        dataType: 'json',
        url: "/login",
        data: JSON.stringify({user:"john", pass:"123"}),
        error: function (err) {
            console.log(err);
            alert('error');
        },
        success: function (data) {
            alert('success');
        }
    });
    app.post('/login', function (req, res, next) {
    var user = req.body.user;
    var password = req.body.pass;
    if(user == 'john' && password == '123') {
    res.status(200).json({s: 1});
    } else {
    res.status(401).json({e: 2});
    }
   });


问:
Biggest GWT Pitfalls?
I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective?

A couple things that we've seen/heard already include:

Google not being able to index content

CSS and styling in general seems to be a bit flaky

Looking for any additional feedback on these items as well. Thanks!

答:
We have been working with gwt for almost 2 years. We have learned a lot of lessons. Here is what we think:

Dont use third party widget libraries especially gwt-ext. It will kill your debugging, development and runtime performance. If you have questions about how this happens, contact me directly.

Use gwt to only fill in the dynamic parts of your apps. So if you have some complex user interactions with lots of fields. However, don't use the panels that come with it. Take your existing stock designer supplied pages. Carve out the areas that will contain the controls for your app. Attach these controls to the page within onModuleLoad(). This way you can use the standard pages from your designer and also do all the styling outside the gwt.

Don't build the entire app as one standard page that then dynamically builds all the pieces. If you do what I suggest in item 2, this won't happen anyway. If you build everything dynamically you will kill performance and consume huge amounts of memory for medium to large apps. Also, if you do what I am suggesting, the back button will work great, so will search engine indexing etc.

The other commenters also had some good suggestions. The rule of thumb i use is to create pages like you were doing a standard web page. Then carve out the pieces that need to be dynamic. Replace them with elements that have id's and then use RootPanel.get( id ).add( widget ) to fill those areas in.

OwnerDisplayName: agartzke

ContentLicense: CC BY-SA 2.5

Title: Biggest GWT Pitfalls?

LastEditorDisplayName: Michael Neale

OwnerDisplayName: kash


问:
How to draw multiple circle shape in SFML
i really want to know how to create a multiple circle shapes in SFML.

I know we can create the circle shape with sf::CircleShape
I want to create a circle shape with the same radius everytime i click on my screen and i have no idea how to do that, please help me.

答:
You need to use an event loop to capture mouse events and any other event for that matter. See https://www.sfml-dev.org/tutorials/2.0/window-events.php for details.
Read the documentation or search via Google for more.</p>


问:
Using regex for path value of routes in angular2
I want to configure route for my angular2 application. My URL needs to be like this:

http://domain_name/constant_value/variable_value/constant_value

The url can be like following examples:

http://localhost/myhouse/floor1/mirror

http://localhost/myhouse/floor1/room1/mirror

http://localhost/myhouse/floor1/room1/bathroom/mirror

Here the routes /myhouse and /mirror are constant. But the middle part can be anything like /floor1 or /floor2/something/something/....

How can i define a route for that in routing module.

```<code>const routes: Routes = [
    {
        path: 'myhouse',
        children: [
            {
                path: ..., //here how do i configure it
                children: [
                    {
                        path: '/mirror',
                        component: MirrorComponent
                    }
                ]
            }
        ]
    }
];
</code>```

Here the mirror component must be loaded if the url has /mirror at the end of the url if not login component should be loaded.
Mirror will be loaded for the urls shown above. Each mirror component will have different propertise value inside according to the variable part of the url.

For login component url will be like:

http://localhost/myhouse

or

http://localhost/myhouse/floor1

or

http://localhost/myhouse/floor1/bathroom1

I tried wanted to use regex but it seems the regex is not supported for newer version of angular2. If I am wrong on not being able to use regex please kindly point me to that direction with an example. If not please point me to right direction.

答:
You could use a UrlMatcher by providing matcher key for a Route. Unfortunately it's undocumented for now, so you may need to check the source of router/src/config.ts:

/**
 * @whatItDoes Represents the results of the URL matching.
 *
 * * `consumed` is an array of the consumed URL segments.
 * * `posParams` is a map of positional parameters.
 *
 * @experimental
 */
export type UrlMatchResult = {
  consumed: UrlSegment[]; posParams?: {[name: string]: UrlSegment};
};

/**
 * @whatItDoes A function matching URLs
 *
 * @description
 *
 * A custom URL matcher can be provided when a combination of `path` and `pathMatch` isn't
 * expressive enough.
 *
 * For instance, the following matcher matches html files.
 *
 * ```
 * function htmlFiles(url: UrlSegment[]) {
 *  return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null;
 * }
 *
 * const routes = [{ matcher: htmlFiles, component: HtmlCmp }];
 * ```
 *
 * @experimental
 */
export type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) =>
UrlMatchResult;
```

This basically allows you to write a function that can do any kind of matching, including regular expressions.

It's still experimental, so there aren't many examples around, but github/matanshukry has kindly provided a gist example of ComplexUrlMatcher. It should give you an idea how to implement one that suits your needs (sadly there's no license, so you can't use it as-is).

Body:
I want to configure route for my angular2 application. My URL needs to be like this:

http://domain_name/constant_value/variable_value/constant_value

The url can be like following examples:

http://localhost/myhouse/floor1/mirror

http://localhost/myhouse/floor1/room1/mirror

http://localhost/myhouse/floor1/room1/bathroom/mirror

Here the routes /myhouse and /mirror are constant. But the middle part can be anything like /floor1 or /floor2/something/something/....

How can i define a route for that in routing module.

const routes: Routes = [
    {
        path: 'myhouse',
        children: [
            {
                path: ..., //here how do i configure it
                children: [
                    {
                        path: '/mirror',
                        component: MirrorComponent
                    }
                ]
            }
        ]
    }
];

Here the mirror component must be loaded if the url has /mirror at the end of the url if not login component should be loaded.
Mirror will be loaded for the urls shown above. Each mirror component will have different propertise value inside according to the variable part of the url.

For login component url will be like:

http://localhost/myhouse

or

http://localhost/myhouse/floor1

or

http://localhost/myhouse/floor1/bathroom1

I tried wanted to use regex but it seems the regex is not supported for newer version of angular2. If I am wrong on not being able to use regex please kindly point me to that direction with an example. If not please point me to right direction.

Body:
You could use a UrlMatcher by providing matcher key for a Route. Unfortunately it's undocumented for now, so you may need to check the source of router/src/config.ts:

/**
 * @whatItDoes Represents the results of the URL matching.
 *
 * * `consumed` is an array of the consumed URL segments.
 * * `posParams` is a map of positional parameters.
 *
 * @experimental
 */
export type UrlMatchResult = {
  consumed: UrlSegment[]; posParams?: {[name: string]: UrlSegment};
};

/**
 * @whatItDoes A function matching URLs
 *
 * @description
 *
 * A custom URL matcher can be provided when a combination of `path` and `pathMatch` isn't
 * expressive enough.
 *
 * For instance, the following matcher matches html files.
 *
 * ```
 * function htmlFiles(url: UrlSegment[]) {
 *  return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null;
 * }
 *
 * const routes = [{ matcher: htmlFiles, component: HtmlCmp }];
 * ```
 *
 * @experimental
 */
export type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) =>
UrlMatchResult;

This basically allows you to write a function that can do any kind of matching, including regular expressions.

It's still experimental, so there aren't many examples around, but github/matanshukry has kindly provided a gist example of ComplexUrlMatcher. It should give you an idea how to implement one that suits your needs (sadly there's no license, so you can't use it as-is).


问:
Issue of undefined index while using ajax and php
I have four different files

index.php

select.php

insert.php

edit.php

delete.php

In my backend I have created a database named 'ecc'

Database 'ecc' has atable named 'task'

The table task has following fields

id, name, category, cost

Datatype for  id set to int and index as primary also id field is on auto increment

My issue :( ! ) Notice: Undefined index: id in C:\wamp\www\select.php on line 38

and same for lines 39, 40, 41,

each of the error is displayed twice on the page.

index.php

```<code><html>
      <head>
           <title>Live Table Data Edit</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      </head>
      <body>
           <div class="container">
                <br />
                <br />
                <br />
                <div class="table-responsive">
                     <h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />
                     <div id="live_data"></div>
                </div>
           </div>
      </body>
 </html>
 <script>
 $(document).ready(function(){
      function fetch_data()
      {
           $.ajax({
                url:"select.php",
                method:"POST",
                success:function(data){
                     $('#live_data').html(data);
                }
           });
      }
      fetch_data();
      $(document).on('click', '#btn_add', function(){
           var name = $('#name').text();
           var category = $('#category').text();
           if(name == '')
           {
                alert("Enter service Name");
                return false;
           }
           if(category == '')
           {
                alert("Enter category");
                return false;
           }
           $.ajax({
                url:"insert.php",
                method:"POST",
                data:{name:name, category:category},
                dataType:"text",
                success:function(data)
                {
                     alert(data);
                     fetch_data();
                }
           })
      });
      function edit_data(id, text, column_name)
      {
           $.ajax({
                url:"edit.php",
                method:"POST",
                data:{id:id, text:text, column_name:column_name},
                dataType:"text",
                success:function(data){
                     alert(data);
                }
           });
      }
      $(document).on('blur', '.name', function(){
           var id = $(this).data("id1");
           var name = $(this).text();
           edit_data(id, name, "name");
      });
      $(document).on('blur', '.category', function(){
           var id = $(this).data("id2");
           var category = $(this).text();
           edit_data(id,category, "category");
      });
      $(document).on('click', '.btn_delete', function(){
           var id=$(this).data("id3");
           if(confirm("Are you sure you want to delete this?"))
           {
                $.ajax({
                     url:"delete.php",
                     method:"POST",
                     data:{id:id},
                     dataType:"text",
                     success:function(data){
                          alert(data);
                          fetch_data();
                     }
                });
           }
      });
 });
 </script>
</code>```

select.php

```<code><?php

 $connect = mysqli_connect('localhost', 'root', '','ecc');
    mysqli_select_db($connect,'ecc');

                if(!$connect){
                    echo "yes";
                }else{
                    echo "no";
                }

 $output = '';

 $sql = "SELECT name, category FROM addservices ORDER BY id DESC";

 $result = mysqli_query($connect, $sql);

 $output .= '
      <div class="table-responsive">
           <table class="table table-bordered">
                <tr>
                     <th width="10%">Id</th>
                     <th width="40%">Service Name</th>
                     <th width="40%">Category</th>
                     <th width="10%">Delete</th>
                </tr>';

 if(mysqli_num_rows($result) > 0)
 {
      while($row = mysqli_fetch_array($result))
      {
           $output .= '
                <tr>
                     <td>'.$row["id"].'</td>
                     <td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
                     <td class="category" data-id2="'.$row["id"].'" contenteditable>'.$row["category"].'</td>
                     <td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
                </tr>
           ';
      }
      $output .= '
           <tr>
                <td></td>
                <td id="name" contenteditable></td>
                <td id="category" contenteditable></td>
                <td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
           </tr>
      ';
 }
 else
 {
      $output .= '<tr>
                          <td colspan="4">Data not Found</td>
                     </tr>';
 }
 $output .= '</table>
      </div>';
 echo $output;
 ?>
</code>```

答:
Chek your query.It need to change as:</p>

```<code>$sql = "SELECT * FROM task ORDER BY id DESC";
</code>```

Body:
I have four different files

index.php

select.php

insert.php

edit.php

delete.php

In my backend I have created a database named 'ecc'

Database 'ecc' has atable named 'task'

The table task has following fields

id, name, category, cost

Datatype for  id set to int and index as primary also id field is on auto increment

My issue :( ! ) Notice: Undefined index: id in C:\wamp\www\select.php on line 38

and same for lines 39, 40, 41,

each of the error is displayed twice on the page.

index.php

           <title>Live Table Data Edit</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

Live Table Add Edit Delete using Ajax Jquery in PHP Mysql

select.php

<?php

 $connect = mysqli_connect('localhost', 'root', '','ecc');
    mysqli_select_db($connect,'ecc');

                if(!$connect){
                    echo "yes";
                }else{
                    echo "no";
                }

 $output = '';

 $sql = "SELECT name, category FROM addservices ORDER BY id DESC";

 $result = mysqli_query($connect, $sql);

 $output .= '

                     Id
                     Service Name
                     Category
                     Delete

';

 if(mysqli_num_rows($result) > 0)
 {
      while($row = mysqli_fetch_array($result))
      {
           $output .= '

                     '.$row["id"].'
                     '.$row["name"].'
                     '.$row["category"].'
                     <button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button>

           ';
      }
      $output .= '

                <button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button>

      ';
 }
 else
 {
      $output .= '

                          Data not Found

';
 }
 $output .= '

';
 echo $output;
 ?>

Body:
Chek your query.It need to change as:

$sql = "SELECT * FROM task ORDER BY id DESC";


答:
" = " sign is an assignment operator and can't be used as conditional where as >= , == , <= such operators are conditional, so while checking for a condition you should not use " = "

please write like this below

```<code>for($i=0; $i <= 10; $i++)
{
echo $i;
}
</code>```

Title: Could someone explain this for me - for (i = 0; i=10; i++)

Body:
" = " sign is an assignment operator and can't be used as conditional where as >= , == , <= such operators are conditional, so while checking for a condition you should not use " = "

please write like this below

for($i=0; $i <= 10; $i++)
{
echo $i;
}


问:
database and asp.net
My goal is to connect to my database either manually or using an sqladapater, and get information from two of my databases on sql server 2005.
Then I want to take this information and on run-time begin to add/subtract/divide/multiply certain columns and place the information into other columns. I can do this in queries, however, I want to do it on run-time what is the best way to achieve this.
I had some of this working, but I just want to start fresh and see how you would go about doing this.

```<code>Partial Class _Default
    Inherits System.Web.UI.Page
    Public cmd As New SqlCommand()
    Public da As New SqlDataAdapter(cmd)
  conn string here.....
    Dim ds As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        cmd.Connection = conn
        conn.Open()

        ' Dim ds As New DataSet
        Dim x As New DataTable

        cmd.CommandText = "SELECT B603SalesAsOFMASTER.DIVISION, B603SalesAsOFMASTER.SDESCR, B603SalesAsOFMASTER.DYYYY, B603SalesAsOFMASTER.AsOFSales, B603SalesAsOFMASTER.ASOFPAX, B603SalesAsOFMASTER.YESales, B603SalesAsOFMASTER.YEPAX, B603SalesAsOFMASTER.PCTofSales, B603SalesAsOFMASTER.PCTofPAX, B601SalesAsOF.Sales AS [Current Sales], B601SalesAsOF.PAX AS [Current PAX], B601SalesAsOF.Sales / B601SalesAsOF.PAX AS [AVG PAX], B601SalesAsOF.Sales / B603SalesAsOFMASTER.PCTofSales AS [Projected Year End] FROM B603SalesAsOFMASTER INNER JOIN B601SalesAsOF ON B603SalesAsOFMASTER.SDESCR = B601SalesAsOF.SDESCR WHERE (B603SalesAsOFMASTER.DYYYY = '2008') AND (B601SalesAsOF.DYYYY = '2010')"
        'da.Fill(ds)
        da.Fill(x)

        GridView1.DataSource = x

        GridView1.DataBind()

        da.FillSchema(ds, SchemaType.Mapped)

        conn.Close()
    End Sub

End Class
</code>```

That is what i am playing around with right now, some of my calculations are done directly in the sql command, but i want to change this.

答:
It sounds like you're asking how to move a calculated field out of a SQL query and into code between the query and the datagrid binding.  (If I'm incorrect in that interpretation, let me know.)  If that's the case, this short tutorial should have exactly what you're looking for.

On a side note, those public data access members on your class make me uneasy.  Those might be better as private.  Or, better still, encapsulated within the single method that uses them.  Throw in some try/catch/finally for good measure and resource cleanup of course :)

Title: database and asp.net

Body:
My goal is to connect to my database either manually or using an sqladapater, and get information from two of my databases on sql server 2005.
Then I want to take this information and on run-time begin to add/subtract/divide/multiply certain columns and place the information into other columns. I can do this in queries, however, I want to do it on run-time what is the best way to achieve this.
I had some of this working, but I just want to start fresh and see how you would go about doing this.

Partial Class _Default
    Inherits System.Web.UI.Page
    Public cmd As New SqlCommand()
    Public da As New SqlDataAdapter(cmd)
  conn string here.....
    Dim ds As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        cmd.Connection = conn
        conn.Open()

        ' Dim ds As New DataSet
        Dim x As New DataTable

        cmd.CommandText = "SELECT B603SalesAsOFMASTER.DIVISION, B603SalesAsOFMASTER.SDESCR, B603SalesAsOFMASTER.DYYYY, B603SalesAsOFMASTER.AsOFSales, B603SalesAsOFMASTER.ASOFPAX, B603SalesAsOFMASTER.YESales, B603SalesAsOFMASTER.YEPAX, B603SalesAsOFMASTER.PCTofSales, B603SalesAsOFMASTER.PCTofPAX, B601SalesAsOF.Sales AS [Current Sales], B601SalesAsOF.PAX AS [Current PAX], B601SalesAsOF.Sales / B601SalesAsOF.PAX AS [AVG PAX], B601SalesAsOF.Sales / B603SalesAsOFMASTER.PCTofSales AS [Projected Year End] FROM B603SalesAsOFMASTER INNER JOIN B601SalesAsOF ON B603SalesAsOFMASTER.SDESCR = B601SalesAsOF.SDESCR WHERE (B603SalesAsOFMASTER.DYYYY = '2008') AND (B601SalesAsOF.DYYYY = '2010')"
        'da.Fill(ds)
        da.Fill(x)

        GridView1.DataSource = x

        GridView1.DataBind()

        da.FillSchema(ds, SchemaType.Mapped)

        conn.Close()
    End Sub

End Class

That is what i am playing around with right now, some of my calculations are done directly in the sql command, but i want to change this.


问:
C3P0 apparent deadlock when the threads are all empty?
I'm using C3P0 as a connection pool in Tomcat, and I'm seeing very worrying errors:

```<code>2010-09-16 13:25:00,160 [Timer-0] WARN  com.mchange.v2.async.ThreadPoolAsynchronousRunner  - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@43502400 -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!
2010-09-16 13:25:01,407 [Timer-0] WARN  com.mchange.v2.async.ThreadPoolAsynchronousRunner  - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@43502400 -- APPARENT DEADLOCK!!! Complete Status:
  Managed Threads: 10
  Active Threads: 0
  Active Tasks:
  Pending Tasks:
    com.mchange.v2.resourcepool.BasicResourcePool$1RefurbishCheckinResourceTask@6e4151a7
  Pool thread stack traces:
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#6,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#5,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#4,5,main]
    java.lang.Object.wait(Native Method)

... many more, exact same stack trace
</code>```

Line 534 is:

```<code> while (true) {
   Runnable myTask;
   synchronized ( ThreadPoolAsynchronousRunner.this ) {
     while ( !should_stop && pendingTasks.size() == 0 )
       ThreadPoolAsynchronousRunner.this.wait( POLL_FOR_STOP_INTERVAL ); // <- here
     if (should_stop) ...
</code>```

It looks very much like all the threads are idle.  They're waiting for work.  0 active threads, and only 1 task to complete.  Any clues on what's going wrong?

Here's the configuration:

```<code>ds.setUser(userName);
ds.setPassword(password);
ds.setMaxPoolSize(16);
ds.setMaxConnectionAge(1800);
ds.setAcquireRetryAttempts(4);
ds.setMaxIdleTime(900);
ds.setNumHelperThreads(10);
ds.setCheckoutTimeout(1000);
</code>```

答: Similar problem was encountered on glassfish4 server while deploying the application. Turned out it was a database configuration issue. Just make sure your database connectivity configurations are proper, verify that the hostname provided in the configuration allows the connection to database. Try connecting to the database manually with the configured username and the hostname/domain. If required, allow the db user to connect from the required domain. Rebuild the application with correct db configurations and then deploy it. </p>

Body:
I'm using C3P0 as a connection pool in Tomcat, and I'm seeing very worrying errors:

2010-09-16 13:25:00,160 [Timer-0] WARN  com.mchange.v2.async.ThreadPoolAsynchronousRunner  - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@43502400 -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!
2010-09-16 13:25:01,407 [Timer-0] WARN  com.mchange.v2.async.ThreadPoolAsynchronousRunner  - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@43502400 -- APPARENT DEADLOCK!!! Complete Status:
  Managed Threads: 10
  Active Threads: 0
  Active Tasks:
  Pending Tasks:
    com.mchange.v2.resourcepool.BasicResourcePool$1RefurbishCheckinResourceTask@6e4151a7
  Pool thread stack traces:
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#6,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#5,5,main]
    java.lang.Object.wait(Native Method)
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:534)
  Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#4,5,main]
    java.lang.Object.wait(Native Method)

... many more, exact same stack trace

Line 534 is:

 while (true) {
   Runnable myTask;
   synchronized ( ThreadPoolAsynchronousRunner.this ) {
     while ( !should_stop && pendingTasks.size() == 0 )
       ThreadPoolAsynchronousRunner.this.wait( POLL_FOR_STOP_INTERVAL ); // <- here
     if (should_stop) ...

It looks very much like all the threads are idle.  They're waiting for work.  0 active threads, and only 1 task to complete.  Any clues on what's going wrong?

Here's the configuration:

ds.setUser(userName);
ds.setPassword(password);
ds.setMaxPoolSize(16);
ds.setMaxConnectionAge(1800);
ds.setAcquireRetryAttempts(4);
ds.setMaxIdleTime(900);
ds.setNumHelperThreads(10);
ds.setCheckoutTimeout(1000);


问:
How to config Spring bean for prototype?
I wrote it as a singleton before, there were no errors.
But I think I should make it instance per request.
And I have the code

```<code><!--Dao configuration-->
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean" scope="request">
    <property name="mapperInterface" value="Dao.UserDao"></property>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>

package Test;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import Common.InitDataBases;
import Common.Controller.OutputStringController;
import Dao.UserDao;
import Model.User;
import java.util.List;

import org.apache.log4j.Logger;

@Controller
@Scope("request")
public class Hello extends OutputStringController{
    private UserDao uDao;
    @RequestMapping(value = "/getUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String dbTest(String username) {
        System.out.println(uDao.findByUsername(username).getUsername());
        return success("");
    }
    @Required
    public void setuDao(UserDao uDao) {
        this.uDao = uDao;
    }

}
</code>```

and it threw an exception.

```<code>org.springframework.beans.factory.BeanInitializationException: Property 'uDao' is required for bean 'hello'
    at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:155)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1225)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:345)
    at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:44)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:340)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.web.method.HandlerMethod.createWithResolvedBean(HandlerMethod.java:255)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:323)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:61)
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:352)
    at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1131)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:936)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

and I can't find a solution for it now.
I would like to make it like : Each http request will create a controller , a service,and a dao.
Help!

答: you dont need @Scope("request")  this,the default is prototype in springmvc</p>

Body:
I wrote it as a singleton before, there were no errors.
But I think I should make it instance per request.
And I have the code

<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean" scope="request">
    <property name="mapperInterface" value="Dao.UserDao"></property>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>

package Test;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import Common.InitDataBases;
import Common.Controller.OutputStringController;
import Dao.UserDao;
import Model.User;
import java.util.List;

import org.apache.log4j.Logger;

@Controller
@Scope("request")
public class Hello extends OutputStringController{
    private UserDao uDao;
    @RequestMapping(value = "/getUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String dbTest(String username) {
        System.out.println(uDao.findByUsername(username).getUsername());
        return success("");
    }
    @Required
    public void setuDao(UserDao uDao) {
        this.uDao = uDao;
    }

}

and it threw an exception.

org.springframework.beans.factory.BeanInitializationException: Property 'uDao' is required for bean 'hello'
    at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:155)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1225)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:345)
    at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:44)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:340)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.web.method.HandlerMethod.createWithResolvedBean(HandlerMethod.java:255)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:323)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:61)
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:352)
    at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1131)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:936)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

and I can't find a solution for it now.
I would like to make it like : Each http request will create a controller , a service,and a dao.
Help!


答:
You are getting this error because you have not selected "id" field in the $sql statement.
You have writen -

$sql = "SELECT name, category FROM addservices ORDER BY id DESC";

It should be

$sql = "SELECT id, name, category FROM addservices ORDER BY id DESC";

Title: Issue of undefined index while using ajax and php


问:
Issue With Telerik Input Controls
I have a shared user control.  This UC is in one page and everything works fine.  In the second page, the RadTextBox client-API get_value() method reports "", when it has a legitimate value.  There is very little javascript on that page, and it's not targeting textboxes; it's in a page with 6 tabs.  The controls work fine; I have RadCombo's and the drop downs work as you would expect.  But no text, no selected value, nothing is being reported (I have a script to check if the page is an empty form).  How do I even debug this to figure out what is going on, and why the value isn't being reported?

Thanks.

答: My advice is to start with debugging your js code and see whether the telerik inputs' client objects are valid in your context. If so, rhe methods from their client API should return the values set from the end user.</p>

Title: Issue With Telerik Input Controls


问:
Can't return array from php function to ajax request
I have a javascript file in which I am doing an ajax request to foo.php
in order to get an array of mysql results.
Here is my javascript file.

```<code>//foo.js
$(document).ready(function(){
    $.ajax({
        url:"foo.php",
        type:"POST",
        data:{
            action:"test",
            remail:"foo"
        },
        success:function(data){
            var messages = data;
            console.log("Ext req");
            try{
                console.log(JSON.parse(data));
            }catch(e){
                console.log(data);
            }
        },
        failure:function(){

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

In order to receive my array of results from php I do the following:

```<code>//foo.php
<?php
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $query = "select * from message where seen";
                $ar = [];
                $res = mysqli_query($con,$query);
                while($row = mysqli_fetch_array($res)){
                    $ar[] = $row;

                }
               echo json_encode($ar);
            break;
        }
    }
?>
</code>```

This returns an array of objects to my ajax request which then I can handle according to my needs.
However if I try to move the php code inside the switch statement into a function and return the encoded result of the function I only get an empty array as response.
Here is how I am trying to do it:

```<code><?php
    function test(){
        $query = "select * from message where seen";
        $ar = [];
        $res = mysqli_query($con,$query);
        while($row = mysqli_fetch_array($res)){
            $ar[] = $row;
        }
        return $ar;
    }
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $result = test();
               echo json_encode($result);
            break;
        }
    }
?>
</code>```

Any ideas why this happening?

UPDATE

$con is a variable that comes from another file which I include

答:
When you moved your query logic into a function, $con, MySQL's  connection object is not available. Use GLOBAL $con; inside your function.

Read this to understand Variable Scope

Method 1
Using GLOBAL keyword

```<code>function test(){
    GLOBAL $con;

    $query = "select * from message where seen";
    $ar = [];
    $res = mysqli_query($con,$query);
    while($row = mysqli_fetch_array($res)){
        $ar[] = $row;
    }
    return $ar;
}
</code>```

Method 2
Pass an argument to a function

```<code>function test($con){
    $query = "select * from message where seen";
    $ar = [];
    $res = mysqli_query($con,$query);
    while($row = mysqli_fetch_array($res)){
        $ar[] = $row;
    }
    return $ar;
}

Call it like this:

test($con);
</code>```

Body:
I have a javascript file in which I am doing an ajax request to foo.php
in order to get an array of mysql results.
Here is my javascript file.

//foo.js
$(document).ready(function(){
    $.ajax({
        url:"foo.php",
        type:"POST",
        data:{
            action:"test",
            remail:"foo"
        },
        success:function(data){
            var messages = data;
            console.log("Ext req");
            try{
                console.log(JSON.parse(data));
            }catch(e){
                console.log(data);
            }
        },
        failure:function(){

        }
    })
});

In order to receive my array of results from php I do the following:

//foo.php
<?php
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $query = "select * from message where seen";
                $ar = [];
                $res = mysqli_query($con,$query);
                while($row = mysqli_fetch_array($res)){
                    $ar[] = $row;

                }
               echo json_encode($ar);
            break;
        }
    }
?>

This returns an array of objects to my ajax request which then I can handle according to my needs.
However if I try to move the php code inside the switch statement into a function and return the encoded result of the function I only get an empty array as response.
Here is how I am trying to do it:

<?php
    function test(){
        $query = "select * from message where seen";
        $ar = [];
        $res = mysqli_query($con,$query);
        while($row = mysqli_fetch_array($res)){
            $ar[] = $row;
        }
        return $ar;
    }
    if(isset($_POST)){
        $action = $_POST['action'];
        if(empty($action)){
            return;
        }
        switch($action){
            case "test":
                $result = test();
               echo json_encode($result);
            break;
        }
    }
?>

Any ideas why this happening?

UPDATE

$con is a variable that comes from another file which I include

Body:
When you moved your query logic into a function, $con, MySQL's  connection object is not available. Use GLOBAL $con; inside your function.

Read this to understand Variable Scope

Method 1
Using GLOBAL keyword

function test(){
    GLOBAL $con;

    $query = "select * from message where seen";
    $ar = [];
    $res = mysqli_query($con,$query);
    while($row = mysqli_fetch_array($res)){
        $ar[] = $row;
    }
    return $ar;
}

Method 2
Pass an argument to a function

function test($con){
    $query = "select * from message where seen";
    $ar = [];
    $res = mysqli_query($con,$query);
    while($row = mysqli_fetch_array($res)){
        $ar[] = $row;
    }
    return $ar;
}

Call it like this:

test($con);


问:
creating a registration and login page with php and mysql on apache server (raspbian jessie)
Hello and thanks in advance for the help. I am running a LAMP server on my raspberry pi and I need help creating a registration and login page using mysql database. All my php files have to be in the /var/www/html. I've been googling this for about a week and I have some questions.

Where do I save css files

Can I make a subdirectory in the html that will create a website (I have tried to do this already but when i navigate to the site it tells me the page isnt working)

How do I make it secure (this is for a personal project so it doesnt have to be extremely secure I just want to know some common security issues)

I tried to follow http://www.allphptricks.com/simple-user-registration-login-script-in-php-and-mysqli/ steps and it showed nothing but a blank page.

I am not asking someone to just write all the code for me, I want to learn and understand what I am doing wrong so if you could direct me to a better tutorial or explain it that would be great.

Thanks

答:
First off make sure all of your CSS files paths are set correctly in the HTML files that you are trying to style. As long as the CSS files are included correctly then it should style your page. The final destination of the CSS files should not matter as long as you have the correct path set to the CSS file in the HTML file.

Linking a CSS file to an HTML file W3Schools
All I did was search "mysql php security best practices" I'm sure you can find more but here is what I found (the first link in my case) OWASP


问:
How to put a div over another div or element, but have it be 50% of that div (trying to do click event)
Basically, I've been trying all sorts of positioning and what not, but here's the issue:

given one div that is shaped like a rectangle, I am trying to overlay another div on it that will be 50% of the width.  However, if I do this then the div below also changes its shape/positioning.

How can I prevent htis from happening?

I know how to make containers, but the inside content is bound by the outer content.

In this case, I want to put a smaller div on top of a larger dive without messing up the div below.

```<code><div class="overlay">
  <div class="image">
  </div>
</div>
</code>```

答:
Please checkout this fiddle, if I understand you correctly

you can either use

```<code>float:left
</code>```

https://jsfiddle.net/wuvxuddk/

to take the div out of the normal flow or use

```<code>position: absolute
</code>```

https://jsfiddle.net/tygpoxuk/

Body:
Please checkout this fiddle, if I understand you correctly

you can either use

float:left

https://jsfiddle.net/wuvxuddk/

to take the div out of the normal flow or use

position: absolute

https://jsfiddle.net/tygpoxuk/


答:
What if you contain them in another div?
Something like this:

```<code><!DOCTYPE html>
<html>
<head>
<style>
div.container {
    height: 300px;
    width: 250px;
    position: relative;
}
div.overlay {
    position: absolute;
    border: 3px solid #73AD21;
    left: 0px;
    top: 0px;
    width: 50%;
    bottom: 0px;
    display:block;
}

div.image {
    position: absolute;
    top: 0px;
    width: 200%;
    height: 100%;
    border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: absolute;</h2>

<p>An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed):</p>

<div class="container">
  <div class="overlay">This div element has position: relative;
    <div class="image">This div element has position: absolute;</div>
  </div>
</div>
</body>
</html>
</code>```

https://www.w3schools.com/code/tryit.asp?filename=FE87FF3WRXHF

Title: How to put a div over another div or element, but have it be 50% of that div (trying to do click event)

Body:
Basically, I've been trying all sorts of positioning and what not, but here's the issue:

given one div that is shaped like a rectangle, I am trying to overlay another div on it that will be 50% of the width.  However, if I do this then the div below also changes its shape/positioning.

How can I prevent htis from happening?

I know how to make containers, but the inside content is bound by the outer content.

In this case, I want to put a smaller div on top of a larger dive without messing up the div below.

Body:
What if you contain them in another div?
Something like this:

<!DOCTYPE html>
<html>
<head>
<style>
div.container {
    height: 300px;
    width: 250px;
    position: relative;
}
div.overlay {
    position: absolute;
    border: 3px solid #73AD21;
    left: 0px;
    top: 0px;
    width: 50%;
    bottom: 0px;
    display:block;
}

div.image {
    position: absolute;
    top: 0px;
    width: 200%;
    height: 100%;
    border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: absolute;</h2>

<p>An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed):</p>

<div class="container">
  <div class="overlay">This div element has position: relative;
    <div class="image">This div element has position: absolute;</div>
  </div>
</div>
</body>
</html>

https://www.w3schools.com/code/tryit.asp?filename=FE87FF3WRXHF


问:
Excel VBA: Query a MySQL Database
I am looking for an example of how to query a MySQL database using Excel VBA.

I am able to use Data \ From Other Sources \ From Microsoft Query to import data from the db, but what I am actually looking for is a way not to import it to a spreadsheet directly, but rather to a data structure in VBA for further manipulation before I output the result to the spreadsheet. How can I do this?

答:
to connect:

```<code>conMySQL.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver};" & "SERVER=" & server & ";" & " DATABASE=" & database & ";" & "UID=" & login_user & ";PWD=" & password & "; OPTION=3; PORT=" & port & ";Connect Timeout=20;"

    'open the connection
    conMySQL.Open
</code>```

then to query:

```<code>strSQL = "SELECT x FROM some_table"
MySQL.Query (strSQL)

With rsTemporary
      Do Until .EOF
          recordCount = recordCount + 1
          some_variable = ![supcode]
          rsTemporary.MoveNext
      Loop
End With
        MySQL.closeCon
</code>```

Title: Excel VBA: Query a MySQL Database

Body:
to connect:

conMySQL.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver};" & "SERVER=" & server & ";" & " DATABASE=" & database & ";" & "UID=" & login_user & ";PWD=" & password & "; OPTION=3; PORT=" & port & ";Connect Timeout=20;"

    'open the connection
    conMySQL.Open

then to query:

strSQL = "SELECT x FROM some_table"
MySQL.Query (strSQL)

With rsTemporary
      Do Until .EOF
          recordCount = recordCount + 1
          some_variable = ![supcode]
          rsTemporary.MoveNext
      Loop
End With
        MySQL.closeCon


问:
Why is the ViewModel data null on POST ASP MVC
I'm doing forms on ASP .NET MVC 5. I thought it was simple enough to just post with a matching model in the action but I keep getting null values on my action. For example,

```<code>@model Tuple<ManageLoginsViewModel, IndexViewModel, LocalPasswordModel, SetPasswordViewModel>

<p>
    You do not have a local password for this site. Add a local
    password so you can log in without an external login.
</p>

@using (Html.BeginForm("SetPassword", "Manage", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Set Password</legend>
        <div>
            <div class="LabelPassword">
                <label>New password</label>
                <input data-val="true" data-val-length="The New password must be at least 6 characters long."
                    data-val-length-max="30" data-val-length-min="6"
                    data-val-required="The New password field is required."
                    id="NewPassword" type="password">
            </div>
            <div class="LabelPassword">
                <label>Confirm Password</label>
                <input data-val="true" data-val-length="The New password must be at least 6 characters long."
                    data-val-length-max="30" data-val-length-min="6"
                    data-val-required="The New password field is required."
                    id="ConfirmPassword" type="password">
            </div>
        </div>
        <input type="submit" value="Set password" />
    </fieldset>
}
</code>```

While numerous post suggest on renaming the action parameter to something that doesn't match the properties on my view model, I have not found a solution to this.

weirdly enough, there is no post data that Chrome shows. Is this an error in my html or my handling of the post?

and finally, here's the action method:

```<code>[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> SetPassword(SetPasswordViewModel setPassword)
        {
            if (ModelState.IsValid)
            {
                var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), setPassword.NewPassword);
                if (result.Succeeded)
                {
                    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
                    if (user != null)
                    {
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    }
                    return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(setPassword);
        }
</code>```

I'm sure its something simple, but I've got no indication where things are going wrong now, other then the blanks on POST that is shown in Chrome (well, the anti-forgery token is displayed at least). Is this the problem?

答:
Make sure your model name object not match with any its property. Example Passing the model object in controller action.

```<code>public class QuestionModel
{
  [Required]
  public string Question { get; set; }
)

public ActionResult Index(QuestionModel Question)
{

}
</code>```

look into above example where Question property matching with its model object name in action controller.

Body:
I'm doing forms on ASP .NET MVC 5. I thought it was simple enough to just post with a matching model in the action but I keep getting null values on my action. For example,

@model Tuple<ManageLoginsViewModel, IndexViewModel, LocalPasswordModel, SetPasswordViewModel>

    You do not have a local password for this site. Add a local
    password so you can log in without an external login.

@using (Html.BeginForm("SetPassword", "Manage", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Set Password</legend>

                New password
                <input data-val="true" data-val-length="The New password must be at least 6 characters long."
                    data-val-length-max="30" data-val-length-min="6"
                    data-val-required="The New password field is required."
                    id="NewPassword" type="password">

                Confirm Password
                <input data-val="true" data-val-length="The New password must be at least 6 characters long."
                    data-val-length-max="30" data-val-length-min="6"
                    data-val-required="The New password field is required."
                    id="ConfirmPassword" type="password">

        <input type="submit" value="Set password" />
    </fieldset>
}

While numerous post suggest on renaming the action parameter to something that doesn't match the properties on my view model, I have not found a solution to this.

weirdly enough, there is no post data that Chrome shows. Is this an error in my html or my handling of the post?

and finally, here's the action method:

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> SetPassword(SetPasswordViewModel setPassword)
        {
            if (ModelState.IsValid)
            {
                var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), setPassword.NewPassword);
                if (result.Succeeded)
                {
                    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
                    if (user != null)
                    {
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    }
                    return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(setPassword);
        }

I'm sure its something simple, but I've got no indication where things are going wrong now, other then the blanks on POST that is shown in Chrome (well, the anti-forgery token is displayed at least). Is this the problem?

Body:
Make sure your model name object not match with any its property. Example Passing the model object in controller action.

public class QuestionModel
{
  [Required]
  public string Question { get; set; }
)

public ActionResult Index(QuestionModel Question)
{

}

look into above example where Question property matching with its model object name in action controller.


问:
Is there any way to let Lua garbage collector know about memory requirements of userdata?
I have a C++ application which embeds Lua and periodically (~10 times per second) runs scripts that can create new userdata objects that allocate non-trivial amounts of memory (~1MiB each) on C++ side. The memory is correctly freed when these objects are garbage-collected, but the problem is that they don't seem to be collected until it's too late and the process starts consuming inordinate amounts of memory (many GiBs). I guess this happens because Lua GC thinks that these objects are just not worth collecting because they appear small on Lua side, and it has no idea how much memory do they actually consume. If this is correct, is there any way to tell it about the real cost of keeping these objects around?

For people familiar with C#, I'm basically looking for the equivalent of GC.AddMemoryPressure() for Lua.

答:
The closest thing you're going to get at present is LUA_GCSTEP.  The manual says:

lua_gc

int lua_gc (lua_State *L, int what, int data);

Controls the garbage collector. […]  For more details about these options, see collectgarbage.

collectgarbage ([opt [, arg]])

This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt:

[…]

"step": performs a garbage-collection step. The step "size" is controlled by arg. With a zero value, the collector will perform one basic (indivisible) step. For non-zero values, the collector will perform as if that amount of memory (in KBytes) had been allocated by Lua. Returns true if the step finished a collection cycle.

(emphasis mine)

This will advance the GC once (as if that much was allocated), but that information isn't kept, meaning that parameters influencing the behavior for future collections (GC pause length, total memory in use, etc.) aren't affected.  (So check if that's works well enough for you and if it doesn't maybe try playing with the GC pause and step multiplier.)


问:
twain driver with xerox workcentre
this is my first time to post here, i need to create a twain driver to control the scanner in a mpf Workcentre Xerox 3635. i need help about this why the xerox twain drivers don't work properly and are very very restricted. The language is or c/c++ or c#.
Thank a lot for the replies.</p>

答:
Do you really (really?) want to (re-)create a TWAIN driver? Really?
Are you really sure? If so, like John suggested, I hope you like pizza - and you're into C (see this topic why you shouldn't use C# for building drivers: C# driver development?)

If, on the other hand, just want to read and use the device.. my first suggestion would be to forget the whole "TWAIN driver idea" and build some application to use the device.

If you're stuck to TWAIN anyway, you might want to check out one of these components.

Title: twain driver with xerox workcentre


答:
Global variables if not used carefully can make problems harder to find as other solution suggested. Pass $con as argument to your function:

```<code>function test($con){
        $query = "select * from message where seen";
        $ar = [];
        $res = mysqli_query($con,$query);
        while($row = mysqli_fetch_array($res)){
            $ar[] = $row;
        }
        return $ar;
    }
</code>```

Title: Can't return array from php function to ajax request

Body:
Global variables if not used carefully can make problems harder to find as other solution suggested. Pass $con as argument to your function:

function test($con){
        $query = "select * from message where seen";
        $ar = [];
        $res = mysqli_query($con,$query);
        while($row = mysqli_fetch_array($res)){
            $ar[] = $row;
        }
        return $ar;
    }


问:
How to get read external storage permissions?
I'm developing an mp3 player application for android and I'm getting an error related to user permissions(READ_EXTERNAL_STORAGE)

This is my code where I ask for permissions:

```<code>int permissionCheck = ContextCompat.checkSelfPermission(PlayListActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE);

        if (ContextCompat.checkSelfPermission(PlayListActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // OPCIONAL(explicaciones de poque pedimos los permisos)
            if (ActivityCompat.shouldShowRequestPermissionRationale(PlayListActivity.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

            } else {
                //pedir permisos
                ActivityCompat.requestPermissions(PlayListActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        permissionCheck);
</code>```

and this is the rest of the code:

```<code>ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

    SongsManager plm = new SongsManager(PlayListActivity.this);
    // get all songs from sdcard
    this.songsList = plm.getPlayList();

    // looping through playlist
    for (int i = 0; i < songsList.size(); i++) {
        // creating new HashMap
        HashMap<String, String> song = songsList.get(i);

        // adding HashList to ArrayList
        songsListData.add(song);
    }

    // se añaden las canciones a la ListView mediante un adapter utilizando el layout playlist_item
    ListAdapter adapter = new SimpleAdapter(this, songsListData,
            R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
            R.id.songTitle });

    setListAdapter(adapter);
</code>```

this is the error:

```<code>03-31 22:09:16.159 2258-2258/com.androidchatapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidchatapp, PID: 2258
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidchatapp/com.androidchatapp.PlayListActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2258, uid=10184 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:153)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5451)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2258, uid=10184 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
    at android.os.Parcel.readException(Parcel.java:1620)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
    at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
    at android.content.ContentResolver.query(ContentResolver.java:493)
    at android.content.ContentResolver.query(ContentResolver.java:435)
    at com.androidchatapp.SongsManager.getPlayList(SongsManager.java:48)
    at com.androidchatapp.PlayListActivity.onCreate(PlayListActivity.java:65)
    at android.app.Activity.performCreate(Activity.java:6323)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:153)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5451)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
Android introduce runtime permission from Marshmallow OS, so we need to implement runtime permission with Manifest permission.  if CompileSdkVersion = 23

You can ask permission when your screen open (in onCreate()) or click event of your button (Like -play Music )

use this method for check runtime  Permission is enable or not

```<code> private static final int READ_STORAGE_PERMISSION_REQUEST_CODE = 41;
 public boolean checkPermissionForReadExtertalStorage() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int result = context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }
    return false;
 }
</code>```

if it return false then call below method, it will show a dialog for permission

```<code> public void requestPermissionForReadExtertalStorage() throws Exception {
        try {
            ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                    READ_STORAGE_PERMISSION_REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
</code>```

Body:
I'm developing an mp3 player application for android and I'm getting an error related to user permissions(READ_EXTERNAL_STORAGE)

This is my code where I ask for permissions:

int permissionCheck = ContextCompat.checkSelfPermission(PlayListActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE);

        if (ContextCompat.checkSelfPermission(PlayListActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // OPCIONAL(explicaciones de poque pedimos los permisos)
            if (ActivityCompat.shouldShowRequestPermissionRationale(PlayListActivity.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

            } else {
                //pedir permisos
                ActivityCompat.requestPermissions(PlayListActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        permissionCheck);

and this is the rest of the code:

ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

    SongsManager plm = new SongsManager(PlayListActivity.this);
    // get all songs from sdcard
    this.songsList = plm.getPlayList();

    // looping through playlist
    for (int i = 0; i < songsList.size(); i++) {
        // creating new HashMap
        HashMap<String, String> song = songsList.get(i);

        // adding HashList to ArrayList
        songsListData.add(song);
    }

    // se añaden las canciones a la ListView mediante un adapter utilizando el layout playlist_item
    ListAdapter adapter = new SimpleAdapter(this, songsListData,
            R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
            R.id.songTitle });

    setListAdapter(adapter);

this is the error:

03-31 22:09:16.159 2258-2258/com.androidchatapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidchatapp, PID: 2258
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidchatapp/com.androidchatapp.PlayListActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2258, uid=10184 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:153)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5451)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2258, uid=10184 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
    at android.os.Parcel.readException(Parcel.java:1620)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
    at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
    at android.content.ContentResolver.query(ContentResolver.java:493)
    at android.content.ContentResolver.query(ContentResolver.java:435)
    at com.androidchatapp.SongsManager.getPlayList(SongsManager.java:48)
    at com.androidchatapp.PlayListActivity.onCreate(PlayListActivity.java:65)
    at android.app.Activity.performCreate(Activity.java:6323)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:153)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5451)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
Android introduce runtime permission from Marshmallow OS, so we need to implement runtime permission with Manifest permission.  if CompileSdkVersion = 23

You can ask permission when your screen open (in onCreate()) or click event of your button (Like -play Music )

use this method for check runtime  Permission is enable or not

 private static final int READ_STORAGE_PERMISSION_REQUEST_CODE = 41;
 public boolean checkPermissionForReadExtertalStorage() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int result = context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }
    return false;
 }

if it return false then call below method, it will show a dialog for permission

 public void requestPermissionForReadExtertalStorage() throws Exception {
        try {
            ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                    READ_STORAGE_PERMISSION_REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


问:
java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
i am new in database want to run first database progrom with oracle but getting error
java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver

i wrote following code

```<code>     // DDL(Data Definition Language)

   // Two commands
  // 1. create
 // 2. insert
</code>```

// To execute this command used method create

// create command

```<code> import java.sql.*;
  import java.io.*;
 class create
 {
  public static void main(String[] args)
    {
        try
      {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            System.out.println("Drivers loaded");
      Connection con=DriverManager.getConnection("jdbc:odbc:new","system","cse");
        System.out.println("Connection established");
        Statement st=con.createStatement();
        st.execute("Create table student(sno varchar(20),sname varchar(20),sadd varchar(20))");
        System.out.println("Table created");
        st.close();
        con.close();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
</code>```

}

答:
If you are trying to connect to a Oracle database (e.g. Oracle 10g) then you should not be using the JDBC / ODBC bridge.  You should be using the appropriate Oracle drivers, and a JDBC URL of the appropriate type.  This Q&A covers this topic:

Oracle 10g connection with Java

There is more information on the Oracle website.

The JDBC / ODBC bridge are for connecting to a database that "speaks" ODBC; e.g. Microsoft Access or Excel.  If this is what you really require, then you need a 3rd-party JDBC / ODBC bridge driver.  Java 8 and later no longer include this driver, as described in this Q&A:

Manipulating an Access database from Java without ODBC

Body:
i am new in database want to run first database progrom with oracle but getting error
java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver

i wrote following code

     // DDL(Data Definition Language)

   // Two commands
  // 1. create
 // 2. insert

// To execute this command used method create

// create command

 import java.sql.*;
  import java.io.*;
 class create
 {
  public static void main(String[] args)
    {
        try
      {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            System.out.println("Drivers loaded");
      Connection con=DriverManager.getConnection("jdbc:odbc:new","system","cse");
        System.out.println("Connection established");
        Statement st=con.createStatement();
        st.execute("Create table student(sno varchar(20),sname varchar(20),sadd varchar(20))");
        System.out.println("Table created");
        st.close();
        con.close();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}

}


问:
How to do softmax when LSTM returns sequence in keras?
I am trying to make a sequence to sequence encoder decoder model and need to softmax the last layer to use categorical cross entropy. </p>

<p>I've tried setting activation of the last LSTM layer to 'softmax' but that doesn't seem to do the trick. Adding another dense layer and setting the activation to softmax doesn't help either. What is the correct way to do a softmax when your last LSTM outputs a sequence? </p>

```<code>inputs = Input(batch_shape=(batch_size, timesteps, input_dim), name='hella')
encoded = LSTM(latent_dim, return_sequences=True, stateful=False)(inputs)
encoded = LSTM(latent_dim, return_sequences=True, stateful=False)(encoded)
encoded = LSTM(latent_dim, return_sequences=True, stateful=False)(encoded)
encoded = LSTM(latent_dim, return_sequences=False)(encoded)
decoded = RepeatVector(timesteps)(encoded)
decoded = LSTM(input_dim, return_sequences=True)(decoded)
# do softmax here
sequence_autoencoder = Model(inputs, decoded)

sequence_autoencoder.compile(loss='categorical_crossentropy', optimizer='adam')
</code>```

答:
Figured it out:

As of Keras 2, you can simply add:

```<code>TimeDistributed(Dense(input_dim, activation='softmax'))
</code>```

TimeDistributed allows you to apply a Dense layer on each temporal time step. Documentation can be found here: https://keras.io/layers/wrappers/

Body:
I am trying to make a sequence to sequence encoder decoder model and need to softmax the last layer to use categorical cross entropy.

I've tried setting activation of the last LSTM layer to 'softmax' but that doesn't seem to do the trick. Adding another dense layer and setting the activation to softmax doesn't help either. What is the correct way to do a softmax when your last LSTM outputs a sequence?

inputs = Input(batch_shape=(batch_size, timesteps, input_dim), name='hella')
encoded = LSTM(latent_dim, return_sequences=True, stateful=False)(inputs)
encoded = LSTM(latent_dim, return_sequences=True, stateful=False)(encoded)
encoded = LSTM(latent_dim, return_sequences=True, stateful=False)(encoded)
encoded = LSTM(latent_dim, return_sequences=False)(encoded)
decoded = RepeatVector(timesteps)(encoded)
decoded = LSTM(input_dim, return_sequences=True)(decoded)
# do softmax here
sequence_autoencoder = Model(inputs, decoded)

sequence_autoencoder.compile(loss='categorical_crossentropy', optimizer='adam')

Body:
Figured it out:

As of Keras 2, you can simply add:

TimeDistributed(Dense(input_dim, activation='softmax'))

TimeDistributed allows you to apply a Dense layer on each temporal time step. Documentation can be found here: https://keras.io/layers/wrappers/