问:
creating dynamic variable for ruby objects in rails project
I am fairly new to rails and am just getting into using cool gems and APIs.  I have been made aware that this community values the contents of questions and answers, or it is expected that they are constructed in a specific way.  The short way to ask my question and the long way are provided.  Please let me know which is preferred here! It is a real question though!

SHORT VERSION

I have a users_controller and User object with a username attribute in a rails app.  How do I create global variables for these users that is dynamically based on their username?  Example: I want with my user (id = 1, first_name = "Rob", username = "rocky") to be callable as @rocky.  So what would go below in my Users_controller that is based on the first code line below working for me in terminal:

```<code>@rocky = User.find_by_username("rocky")

WHATGOESHERE = User.find_by_username(params[:username]}
</code>```

or should I be using this in some shape or form in place of params[:username]

```<code>@"#{user.username}"
</code>```

Below is the longer version of my question.  It is more detailed and follows more closely how I approached the issue.  The first one... that I wrote second, is more concise but that's not always what people want... please let me know which is preferred on this site.  Thanks!!

LONG VERSION

I need some clarity on a few things.  I am using a gem called "has_friendship" to create friendships between my users (link to gem-  https://github.com/sungwoncho/has_friendship ).

First, this is the documentations example of how to request a friendship, starting with the creation of the users.

```<code>@mac = User.create(name: "Mac")
@dee = User.create(name: "Dee")

# @mac sends a friend request to @dee
@mac.friend_request(@dee)
</code>```

This is where I first became confused.  My users don't have a "name" field.  But that's ok. I managed to figure out that I just need to assign my created users global variables as they do... since my users will be interacting with each other behind their "username" attribute.  So first question, How do I assign a dynamic variable name to each user?  In the documentation, they are hard-coding in the names "Mac" and "Dee." I need to have this global variable be created upon the creation of the object.. So my plan is to do this in the controller.  Here I am already defining @users  and @user in users#show

```<code>@users = User.all
@user = User.includes(:wallet).find_by_id(params[:id])
</code>```

So my thought process is that the left side of the equation should be the name of what you're naming and the right side is what that name is referring to.  So for the right side, I'd think to put

```<code>User.find_by_username(params[:username])
</code>```

as when in the terminal, if I replace the content in parenthesis with an actual username in quotes, it brings up that user's info.  So how do I write the left side.  I would think the left side is something like this:

```<code>@"#{params[:username]}"
</code>```

So in full I currently have the following in my users_controller to assign global variables to my users based on their username atttribute...

```<code>@"#{params[:username]}" = User.find_by_username(params[:username])
</code>```

This, especially the left side, does not look at all right to me.  So I've looked around on google a bunch and the only other thing I can find that looks like the right way to do this is by using "instance_variable_set" but everything I've looked at doesn't make total sense for my situation... (as usual.. ha)

答:
Ok what I get to know from your question is you want to use friend_request method to associate two users.

For this, you don't need to assign them to any variables. You can directly do this by something like this -
Suppose there are two user's

id=1 first_name='Rocky' username='rocky'

id=2 first_name='Nimish' username='nimish'

```<code>User.find_by(username: 'rocky').friend_request(User.find_by(username: 'nimish'))
</code>```

OR

```<code>User.find_by_username('rocky').friend_request(User.find_by_username( 'nimish'))
</code>```

Also, If you want to assign them to instance variable then it is not necessary to create an instance variable corresponding to the username value
You can simply assign them to @user and @requested_user and then

```<code>@user.friend_request(@requested_user)
</code>```

Body:
I am fairly new to rails and am just getting into using cool gems and APIs.  I have been made aware that this community values the contents of questions and answers, or it is expected that they are constructed in a specific way.  The short way to ask my question and the long way are provided.  Please let me know which is preferred here! It is a real question though!

SHORT VERSION

I have a users_controller and User object with a username attribute in a rails app.  How do I create global variables for these users that is dynamically based on their username?  Example: I want with my user (id = 1, first_name = "Rob", username = "rocky") to be callable as @rocky.  So what would go below in my Users_controller that is based on the first code line below working for me in terminal:

@rocky = User.find_by_username("rocky")

WHATGOESHERE = User.find_by_username(params[:username]}

or should I be using this in some shape or form in place of params[:username]

@"#{user.username}"

Below is the longer version of my question.  It is more detailed and follows more closely how I approached the issue.  The first one... that I wrote second, is more concise but that's not always what people want... please let me know which is preferred on this site.  Thanks!!

LONG VERSION

I need some clarity on a few things.  I am using a gem called "has_friendship" to create friendships between my users (link to gem-  https://github.com/sungwoncho/has_friendship ).

First, this is the documentations example of how to request a friendship, starting with the creation of the users.

@mac = User.create(name: "Mac")
@dee = User.create(name: "Dee")

# @mac sends a friend request to @dee
@mac.friend_request(@dee)

This is where I first became confused.  My users don't have a "name" field.  But that's ok. I managed to figure out that I just need to assign my created users global variables as they do... since my users will be interacting with each other behind their "username" attribute.  So first question, How do I assign a dynamic variable name to each user?  In the documentation, they are hard-coding in the names "Mac" and "Dee." I need to have this global variable be created upon the creation of the object.. So my plan is to do this in the controller.  Here I am already defining @users  and @user in users#show

@users = User.all
@user = User.includes(:wallet).find_by_id(params[:id])

So my thought process is that the left side of the equation should be the name of what you're naming and the right side is what that name is referring to.  So for the right side, I'd think to put

User.find_by_username(params[:username])

as when in the terminal, if I replace the content in parenthesis with an actual username in quotes, it brings up that user's info.  So how do I write the left side.  I would think the left side is something like this:

@"#{params[:username]}"

So in full I currently have the following in my users_controller to assign global variables to my users based on their username atttribute...

@"#{params[:username]}" = User.find_by_username(params[:username])

This, especially the left side, does not look at all right to me.  So I've looked around on google a bunch and the only other thing I can find that looks like the right way to do this is by using "instance_variable_set" but everything I've looked at doesn't make total sense for my situation... (as usual.. ha)

Body:
Ok what I get to know from your question is you want to use friend_request method to associate two users.

For this, you don't need to assign them to any variables. You can directly do this by something like this -
Suppose there are two user's

id=1 first_name='Rocky' username='rocky'

id=2 first_name='Nimish' username='nimish'

User.find_by(username: 'rocky').friend_request(User.find_by(username: 'nimish'))

OR

User.find_by_username('rocky').friend_request(User.find_by_username( 'nimish'))

Also, If you want to assign them to instance variable then it is not necessary to create an instance variable corresponding to the username value
You can simply assign them to @user and @requested_user and then

@user.friend_request(@requested_user)


来源: stackexchange

问:
Using Proguard for Android in Eclipse got Error
I have taken a fresh install of Eclipse and all the latest Android tools and want to use Proguard on existing project, but for now I have created a new blank one.
I have added a proguard.cfg file to my project
added proguard.config=proguard.cfg to my default.properties

Now when I try to export I get the following error

```<code>[2010-12-12 10:36:35 - ApplicationTest] Proguard returned with error code 1. See console
[2010-12-12 10:36:35 - ApplicationTest] 'C:\Program' is not recognized as an internal or external command,
[2010-12-12 10:36:35 - ApplicationTest] operable program or batch file.
[2010-12-12 10:36:35 - ApplicationTest] '-jar' is not recognized as an internal or external command,
[2010-12-12 10:36:35 - ApplicationTest] operable program or batch file.
</code>```

I know it means there is a filepath setup incorrectly, question is where the heck is as I have looked through the general properties and project properties and can't see any reference to proguard or obfuscation so am stuck on what to change

Any help appreciated.

答: Is there not a way to specify the direct paths ourselves to the Java and Android SDK in the proguard config file?</p>

ContentLicense: CC BY-SA 3.0

Body:
I have taken a fresh install of Eclipse and all the latest Android tools and want to use Proguard on existing project, but for now I have created a new blank one.
I have added a proguard.cfg file to my project
added proguard.config=proguard.cfg to my default.properties

Now when I try to export I get the following error

[2010-12-12 10:36:35 - ApplicationTest] Proguard returned with error code 1. See console
[2010-12-12 10:36:35 - ApplicationTest] 'C:\Program' is not recognized as an internal or external command,
[2010-12-12 10:36:35 - ApplicationTest] operable program or batch file.
[2010-12-12 10:36:35 - ApplicationTest] '-jar' is not recognized as an internal or external command,
[2010-12-12 10:36:35 - ApplicationTest] operable program or batch file.

I know it means there is a filepath setup incorrectly, question is where the heck is as I have looked through the general properties and project properties and can't see any reference to proguard or obfuscation so am stuck on what to change

Any help appreciated.

ContentLicense: CC BY-SA 2.5


问:
CUDA programming for ODE solver using thrust
I am trying to solve ODE with 6 variable in CUDA using thrust. My program is here.

```<code>#include <iostream>
#include <cmath>
#include <utility>
#include <cstdlib>

 #include <thrust/device_vector.h>
 #include <thrust/reduce.h>
 #include <thrust/functional.h>
  #include <boost/numeric/odeint.hpp>

  #include <boost/numeric/odeint/external/thrust/thrust_algebra.hpp>
  #include <boost/numeric/odeint/external/thrust/thrust_operations.hpp>
  #include <boost/numeric/odeint/external/thrust/thrust_resize.hpp>

   using namespace std;
   using namespace boost::numeric::odeint;

   typedef double value_type;

typedef thrust::device_vector< value_type > state_type;

const value_type n1 = 10.0;

 struct Goodwin_system
{
    struct Goodwin_functor
    {
        template< class T >
        __host__ __device__
        void operator()( T t ) const
        {

        value_type x1 = thrust::get< 0 >( t );
        value_type x2 = thrust::get< 1 >( t );
        value_type x3 = thrust::get< 2 >( t );
        value_type x4 = thrust::get< 3 >( t );
        value_type x5 = thrust::get< 4 >( t );
        value_type x6 = thrust::get< 5 >( t );

        value_type a  = thrust::get< 6 >( t );// For differnt values of a we will get different ODE

       thrust::get< 7 >( t ) = a * (77.3*(pow(0.001,n1)/(pow(0.001,n1) + pow(x3,n1))) - x1);
       thrust::get< 8 >( t ) = a * (x1-x2);
       thrust::get< 9 >( t ) = a * (x2-x3);
       thrust::get< 10 >( t ) = a * (x3-x4);
       thrust::get< 11 >( t ) = a * (x4-x5);
       thrust::get< 12 >( t ) = a * (x5-x6);
    }
};

Goodwin_system( size_t N , const state_type &aa ) // aa is for different values of the parameter a
: m_N( N ) , m_aa( aa ) { }

template< class State , class Deriv >
void operator()(  const State &x , Deriv &dxdt , value_type t ) const
{
    thrust::for_each(
            thrust::make_zip_iterator( thrust::make_tuple(
                    boost::begin( x ) ,
                    boost::begin( x ) + m_N ,
                    boost::begin( x ) + 2 * m_N ,
                    boost::begin( x ) + 3 * m_N ,
                    boost::begin( x ) + 4 * m_N ,
                    boost::begin( x ) + 5 * m_N ,
                    m_aa.begin() ,
                    boost::begin( dxdt ) ,
                    boost::begin( dxdt ) + m_N ,
                    boost::begin( dxdt ) + 2 * m_N,
                    boost::begin( dxdt ) + 3 * m_N,
                    boost::begin( dxdt ) + 4 * m_N,
                    boost::begin( dxdt ) + 5 * m_N ) ) ,
            thrust::make_zip_iterator( thrust::make_tuple(
                    boost::begin( x ) + m_N ,
                    boost::begin( x ) + 2 * m_N ,
                    boost::begin( x ) + 3 * m_N ,
                    boost::begin( x ) + 4 * m_N ,
                    boost::begin( x ) + 5 * m_N ,
                    boost::begin( x ) + 6 * m_N ,
                    m_aa.end() ,
                    boost::begin( dxdt ) + m_N ,
                    boost::begin( dxdt ) + 2 * m_N ,
                    boost::begin( dxdt ) + 3 * m_N,
                    boost::begin( dxdt ) + 4 * m_N,
                    boost::begin( dxdt ) + 5 * m_N,
                    boost::begin( dxdt ) + 6 * m_N)) ,
                    Goodwin_functor() );
}

size_t m_N;
const state_type &m_aa;
   };

size_t N;

 void write_ans( const state_type &x , const double t )// For writing the    results
{

 cout<<t<<"\t";

 for( size_t i=0 ; i<6*N ; ++i )
     {
    cout<<x[i]<<"\t";
     }
     cout<<endl;

 }

 const value_type dt = 0.1;
 const value_type t_max = 1000.0;

 int main( int argc , char* argv[] )
 {

      N = argc > 1 ? atoi(argv[1]) : 1000;// for 1000 oscillator

  vector< value_type > aa_host( N );

   const value_type aa_min = value_type(0.01);

   for( size_t i=0 ; i<N ; ++i )

      aa_host[i] =(i+1)*aa_min;// Generate differnt a values for each iteration

    state_type aa = aa_host;

     //[ thrust_Goodwin_parameters_integration

  state_type x( 6 * N );

// initialize x,y,z

thrust::fill( x.begin() , x.end() , value_type(0.2) );

typedef runge_kutta4< state_type , value_type , state_type , value_type ,
          thrust_algebra , thrust_operations > stepper_type;

Goodwin_system Goodwin(N , aa);

integrate_const( stepper_type() , Goodwin , x , value_type(0.1) , t_max , dt, write_ans);

return 0;
   }
</code>```

When I try to compile it, error showing

"error: no instance of overloaded function "thrust::make_tuple" matches the argument list"

I could solve ODE with 4 variable without any error. Is tuple only support up to 10

element? What is the way to solve this problem?

答: As is clearly defined in the documentation, thrust::tuple is statically templated up to a maximum of 10 entries. Short of re-implementing your own version with more entries, this is a non-negotiable limit of the class.

Body:
I am trying to solve ODE with 6 variable in CUDA using thrust. My program is here.

#include <iostream>
#include <cmath>
#include <utility>
#include <cstdlib>

 #include <thrust/device_vector.h>
 #include <thrust/reduce.h>
 #include <thrust/functional.h>
  #include <boost/numeric/odeint.hpp>

  #include <boost/numeric/odeint/external/thrust/thrust_algebra.hpp>
  #include <boost/numeric/odeint/external/thrust/thrust_operations.hpp>
  #include <boost/numeric/odeint/external/thrust/thrust_resize.hpp>

   using namespace std;
   using namespace boost::numeric::odeint;

   typedef double value_type;

typedef thrust::device_vector< value_type > state_type;

const value_type n1 = 10.0;

 struct Goodwin_system
{
    struct Goodwin_functor
    {
        template< class T >
        __host__ __device__
        void operator()( T t ) const
        {

        value_type x1 = thrust::get< 0 >( t );
        value_type x2 = thrust::get< 1 >( t );
        value_type x3 = thrust::get< 2 >( t );
        value_type x4 = thrust::get< 3 >( t );
        value_type x5 = thrust::get< 4 >( t );
        value_type x6 = thrust::get< 5 >( t );

        value_type a  = thrust::get< 6 >( t );// For differnt values of a we will get different ODE

       thrust::get< 7 >( t ) = a * (77.3*(pow(0.001,n1)/(pow(0.001,n1) + pow(x3,n1))) - x1);
       thrust::get< 8 >( t ) = a * (x1-x2);
       thrust::get< 9 >( t ) = a * (x2-x3);
       thrust::get< 10 >( t ) = a * (x3-x4);
       thrust::get< 11 >( t ) = a * (x4-x5);
       thrust::get< 12 >( t ) = a * (x5-x6);
    }
};

Goodwin_system( size_t N , const state_type &aa ) // aa is for different values of the parameter a
: m_N( N ) , m_aa( aa ) { }

template< class State , class Deriv >
void operator()(  const State &x , Deriv &dxdt , value_type t ) const
{
    thrust::for_each(
            thrust::make_zip_iterator( thrust::make_tuple(
                    boost::begin( x ) ,
                    boost::begin( x ) + m_N ,
                    boost::begin( x ) + 2 * m_N ,
                    boost::begin( x ) + 3 * m_N ,
                    boost::begin( x ) + 4 * m_N ,
                    boost::begin( x ) + 5 * m_N ,
                    m_aa.begin() ,
                    boost::begin( dxdt ) ,
                    boost::begin( dxdt ) + m_N ,
                    boost::begin( dxdt ) + 2 * m_N,
                    boost::begin( dxdt ) + 3 * m_N,
                    boost::begin( dxdt ) + 4 * m_N,
                    boost::begin( dxdt ) + 5 * m_N ) ) ,
            thrust::make_zip_iterator( thrust::make_tuple(
                    boost::begin( x ) + m_N ,
                    boost::begin( x ) + 2 * m_N ,
                    boost::begin( x ) + 3 * m_N ,
                    boost::begin( x ) + 4 * m_N ,
                    boost::begin( x ) + 5 * m_N ,
                    boost::begin( x ) + 6 * m_N ,
                    m_aa.end() ,
                    boost::begin( dxdt ) + m_N ,
                    boost::begin( dxdt ) + 2 * m_N ,
                    boost::begin( dxdt ) + 3 * m_N,
                    boost::begin( dxdt ) + 4 * m_N,
                    boost::begin( dxdt ) + 5 * m_N,
                    boost::begin( dxdt ) + 6 * m_N)) ,
                    Goodwin_functor() );
}

size_t m_N;
const state_type &m_aa;
   };

size_t N;

 void write_ans( const state_type &x , const double t )// For writing the    results
{

 cout<<t<<"\t";

 for( size_t i=0 ; i<6*N ; ++i )
     {
    cout<<x[i]<<"\t";
     }
     cout<<endl;

 }

 const value_type dt = 0.1;
 const value_type t_max = 1000.0;

 int main( int argc , char* argv[] )
 {

      N = argc > 1 ? atoi(argv[1]) : 1000;// for 1000 oscillator

  vector< value_type > aa_host( N );

   const value_type aa_min = value_type(0.01);

   for( size_t i=0 ; i<N ; ++i )

      aa_host[i] =(i+1)*aa_min;// Generate differnt a values for each iteration

    state_type aa = aa_host;

     //[ thrust_Goodwin_parameters_integration

  state_type x( 6 * N );

// initialize x,y,z

thrust::fill( x.begin() , x.end() , value_type(0.2) );

typedef runge_kutta4< state_type , value_type , state_type , value_type ,
          thrust_algebra , thrust_operations > stepper_type;

Goodwin_system Goodwin(N , aa);

integrate_const( stepper_type() , Goodwin , x , value_type(0.1) , t_max , dt, write_ans);

return 0;
   }

When I try to compile it, error showing

"error: no instance of overloaded function "thrust::make_tuple" matches the argument list"

I could solve ODE with 4 variable without any error. Is tuple only support up to 10

element? What is the way to solve this problem?


问:
Jquery Trigger is firing the wrong table column
I have a dynamically generated table with many checkboxes with same name and click event. I am using an ALL checkbox in every column which will check all the checkbox in that column .
The code is
***dynamically generated checkboxes

```<code>    if (discountProductGroupBuyer != null)
    {
    sb.Append("<td><input name=productGroupWiseCustomer id='" + "GetProduct" + customerGroup + "' type=checkbox checked=true value=mlb onclick=GetProduct('" + customerGroup + "') ></td>");
    }
</code>```

****onclick of generated checkboxes

```<code>   function GetProduct(ids) {
    debugger;
   var str = ids;
   var temp = [];
   temp.length = 0;
   temp = str.toString().split('-');

var addOrDelete = "";
var checkboxid = "#GetProduct" + ids;
if ($(checkboxid).is(":checked")) {
    addOrDelete = true;
    var flag = 0;
    $.grep(ProductGroupID, function (item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}
else {
    addOrDelete = false;
    flag = 0;
    $.grep(ProductGroupID, function(item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}
</code>```

}

*** Check all code

```<code>$(document).on("click", "#chkAll", function () {

    var cbody = $(this),
    theader = cbody.parent(),
    column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);

});
</code>```

Which seems to work and its checking all the checkbox in that specific column
like below image.

But the problem arise after adding a trigger event. Let me explain

I have also a trigger click event which will be fired by clicking that all checkbox for that specific column only. The problem is when I click the #chkAll checkbox its not triggering that specific column but triggering for the other column checkbox.

```<code>$(document).on("click", "#chkAll", function () {

     var cbody = $(this),
     theader = cbody.parent(),
     column = theader.index() + 1;
     $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);
     $("input:checkbox[name='productGroupWiseCustomer']").trigger('click');

});
</code>```

What I am trying to achieve that by clicking individual column's #chkAll  checkbox it will trigger only the checkboxes under that column only.Help Needed .Thanks for help

I also added a photo.

答:
It looks your click triggers next column.

Try this:

```<code>$(document).on("click", "#chkAll", function () {

   var cbody = $(this),
   theader = cbody.parent(),

   // index already makes the +1 for you
   column = theader.index();

   var td_set = $("#tbody td:nth-child(" + column + ") input");
   td_set.prop("checked", this.checked);

   td_set.trigger('click');
});
</code>```

The sentence $("input:checkbox[name='productGroupWiseCustomer']").trigger('click'); fires a new click in your table and check, still, the next column.

Update

Now the code triggers click for every checkbox that is set as checked.

Body:
I have a dynamically generated table with many checkboxes with same name and click event. I am using an ALL checkbox in every column which will check all the checkbox in that column .
The code is
***dynamically generated checkboxes

    if (discountProductGroupBuyer != null)
    {
    sb.Append("<input name=productGroupWiseCustomer id='" + "GetProduct" + customerGroup + "' type=checkbox checked=true value=mlb onclick=GetProduct('" + customerGroup + "') >	");
    }

****onclick of generated checkboxes

   function GetProduct(ids) {
    debugger;
   var str = ids;
   var temp = [];
   temp.length = 0;
   temp = str.toString().split('-');

var addOrDelete = "";
var checkboxid = "#GetProduct" + ids;
if ($(checkboxid).is(":checked")) {
    addOrDelete = true;
    var flag = 0;
    $.grep(ProductGroupID, function (item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}
else {
    addOrDelete = false;
    flag = 0;
    $.grep(ProductGroupID, function(item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}

}

*** Check all code

$(document).on("click", "#chkAll", function () {

    var cbody = $(this),
    theader = cbody.parent(),
    column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);

});

Which seems to work and its checking all the checkbox in that specific column
like below image.

But the problem arise after adding a trigger event. Let me explain

I have also a trigger click event which will be fired by clicking that all checkbox for that specific column only. The problem is when I click the #chkAll checkbox its not triggering that specific column but triggering for the other column checkbox.

$(document).on("click", "#chkAll", function () {

     var cbody = $(this),
     theader = cbody.parent(),
     column = theader.index() + 1;
     $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);
     $("input:checkbox[name='productGroupWiseCustomer']").trigger('click');

});

What I am trying to achieve that by clicking individual column's #chkAll  checkbox it will trigger only the checkboxes under that column only.Help Needed .Thanks for help

I also added a photo.

Body:
It looks your click triggers next column.

Try this:

$(document).on("click", "#chkAll", function () {

   var cbody = $(this),
   theader = cbody.parent(),

   // index already makes the +1 for you
   column = theader.index();

   var td_set = $("#tbody td:nth-child(" + column + ") input");
   td_set.prop("checked", this.checked);

   td_set.trigger('click');
});

The sentence $("input:checkbox[name='productGroupWiseCustomer']").trigger('click'); fires a new click in your table and check, still, the next column.

Update

Now the code triggers click for every checkbox that is set as checked.


问:
Run GPIO process in background python
I'm using Raspberry Pi 3 and DHT11 ( temp&humid sensor) to get surrounding values.

From time to time, while accessing sensor via its python module, a stall of 2-5 seconds until data is sent back back to RPI (and GUI for displaying results) occurs. This issue happens also when only printing data to terminal and not regarding GUI updating.

This delay causes a stall of entire GUI.

Regarding this stall in getting data measurement as a system limitation, I'm wondering if it is possible to run this process in parallel / background (updating a temp variable) - that it won't stall entire GUI ?

The following function access the sensor and retrieve data:

```<code>ht_data():
    h0,t0 = Adafruit_DHT.read_retry (11,4) # DHT module to obtain T&H
    temp_var.set("%d"%t)  ## update StringVar
    hum_var.set("%d%%"%h) ## update StringVar
root.after(500, ht_data)
</code>```

答:
There might be a simpler solution.

As you can see here, read_retry simply uses time.sleep() between retries which is indeed undesirable from a GUI standpoint.

So try using read() instead of read_retry(), and do not update the values if it returns (None, None).

```<code>ht_data():
    h0,t0 = Adafruit_DHT.read(11,4)
    if h0 and t0:
        temp_var.set("%d" % t0)  ## update StringVar
        hum_var.set("%d%%" % h0) ## update StringVar
    root.after(2000, ht_data)
</code>```

Since the documentation indicates that you can only read it once every two seconds, I increased the timeout to match that.

Only if using read() doesn't work should you use a separate process (or thread).

ContentLicense: CC BY-SA 4.0

Title: Run GPIO process in background python

Body:
I'm using Raspberry Pi 3 and DHT11 ( temp&humid sensor) to get surrounding values.

From time to time, while accessing sensor via its python module, a stall of 2-5 seconds until data is sent back back to RPI (and GUI for displaying results) occurs. This issue happens also when only printing data to terminal and not regarding GUI updating.

This delay causes a stall of entire GUI.

Regarding this stall in getting data measurement as a system limitation, I'm wondering if it is possible to run this process in parallel / background (updating a temp variable) - that it won't stall entire GUI ?

The following function access the sensor and retrieve data:

ht_data():
    h0,t0 = Adafruit_DHT.read_retry (11,4) # DHT module to obtain T&H
    temp_var.set("%d"%t)  ## update StringVar
    hum_var.set("%d%%"%h) ## update StringVar
root.after(500, ht_data)

Body:
There might be a simpler solution.

As you can see here, read_retry simply uses time.sleep() between retries which is indeed undesirable from a GUI standpoint.

So try using read() instead of read_retry(), and do not update the values if it returns (None, None).

ht_data():
    h0,t0 = Adafruit_DHT.read(11,4)
    if h0 and t0:
        temp_var.set("%d" % t0)  ## update StringVar
        hum_var.set("%d%%" % h0) ## update StringVar
    root.after(2000, ht_data)

Since the documentation indicates that you can only read it once every two seconds, I increased the timeout to match that.

Only if using read() doesn't work should you use a separate process (or thread).


问:
XAMPP: Couldn't start Apache (Windows 10)
I'm using XAMPP, and I can start Apache, but, MySQL (phpMyAdmin) start!

When I start, I get this error;

10:07:49 [Apache] Error: Apache shutdown unexpectedly.
10:07:49 [Apache] This may be due to a blocked port, missing dependencies,
10:07:49 [Apache] improper privileges, a crash, or a shutdown by another method.
10:07:49 [Apache] Press the Logs button to view error logs and check
10:07:49 [Apache] the Windows Event Viewer for more clues
10:07:49 [Apache] If you need more help, copy and post this
10:07:49 [Apache] entire log window on the forums
```
<p>I search on it, and, change the port of Apache in Config -> Service and Port setting. I have;</p>
<pre class="lang-none prettyprint-override"><code>Service name: Apache 2.4
Main port: 122
SSL port: 444
</code>```

I also uninstall Skype (Windows 8/10/Metro version). Nothing is working. In the httpd.conf file I have;

Listen 122
ServerName localhost:122
```
<p>I start it via <code>apache_start.bat</code> and get;</p>
<pre class="lang-none prettyprint-override"><code>(OS 10013)An attempt was made to access a socket in a way forbidden by its access permissions.  : AH00072: make_sock: could not bind to address [::]:445
(OS 10013)An attempt was made to access a socket in a way forbidden by its access permissions.  : AH00072: make_sock: could not bind to address 0.0.0.0:445
AH00451: no listening sockets available, shutting down
AH00015: Unable to open logs
</code>```

Please note that all the log files don’t exists!
Skype is uninstalled.

答:
If you have installed SQL Server, some of its services may block the port which XAMPP needs. I solved my problem by disabling SQL Server Reporting Services and now Apache starts without any problems.

Just open the services.msc, scroll down, and find SQL Server Reporting Services. Right click on it and click Stop.

Body:
I'm using XAMPP, and I can start Apache, but, MySQL (phpMyAdmin) start!

When I start, I get this error;

10:07:49 [Apache] Error: Apache shutdown unexpectedly.
10:07:49 [Apache] This may be due to a blocked port, missing dependencies,
10:07:49 [Apache] improper privileges, a crash, or a shutdown by another method.
10:07:49 [Apache] Press the Logs button to view error logs and check
10:07:49 [Apache] the Windows Event Viewer for more clues
10:07:49 [Apache] If you need more help, copy and post this
10:07:49 [Apache] entire log window on the forums

I search on it, and, change the port of Apache in Config -> Service and Port setting. I have;

Service name: Apache 2.4
Main port: 122
SSL port: 444

I also uninstall Skype (Windows 8/10/Metro version). Nothing is working. In the httpd.conf file I have;

Listen 122
ServerName localhost:122

I start it via apache_start.bat and get;

(OS 10013)An attempt was made to access a socket in a way forbidden by its access permissions.  : AH00072: make_sock: could not bind to address [::]:445
(OS 10013)An attempt was made to access a socket in a way forbidden by its access permissions.  : AH00072: make_sock: could not bind to address 0.0.0.0:445
AH00451: no listening sockets available, shutting down
AH00015: Unable to open logs

Please note that all the log files don’t exists!
Skype is uninstalled.


问:
How should I parallelize a mix of cpu- and network-intensive tasks (in Celery)
I have a job that scans a network file system (can be remote), pulls many files, runs a computation on them and pushes the results (per file) into a DB. I am in process of moving this to Celery so that it can be scaled up. The number of files can get really huge (1M+).

I am not sure what design approach to take, specifically:

Uniform "end2end" tasks

A task gets a batch (list of N files), pulls them, computes and uploads results.

(Using batches rather than individual files is for optimizing the connection to the remote file system and the DB, although it is a pure heuristics at this point)

Clearly, a task would spend a large part of it waiting for I/O, so we'll need to play with number of worker processes (much more than # of CPUs), so that I have enough tasks running (computing) concurrently.

pro: simple design, easier coding and control.

con: probably will need to tune the process pool size individually per installation, as it would depend on environment (network, machines etc.)

Split into dedicated smaller tasks

download, compute, upload (again, batches).

This option is appealing intuitively, but I don't actually see the advantage.

I'd be glad to get some references to tutorials on concurrency design, as well as design suggestions.

答:
Instead of celery, you can write a simple python script which runs on k*cpu_count threads just to connect to remote servers and fetch files without celery.

Personally, I found that k value in between 4 to 7 gives better results in terms of CPU utilization for IO bound tasks. Depending on the number of files produced or the rate at which you want to consume, you can use a suitable number of threads.

Alternatively, you can use celery + gevent or celery with threads if your tasks are IO bound.

For computation and updating DB you can use celery so that you can scale as per your requirements dynamically. If you are too many tasks at a time which need DB connection, you should use DB connection pooling for workers.


问:
How to delete shared preferences data from App in Android
How do I delete SharedPreferences data for my application?

I'm creating an application that uses a lot of web services to sync data. For testing purposes, I need to wipe out some SharedPreferences values when I restart the app.

答:
Just did this this morning.  From a command prompt:

```<code>adb shell
cd /data/data/YOUR_PACKAGE_NAME/shared_prefs
rm * // to remove all shared preference files
rm YOUR_PREFS_NAME.xml // to remove a specific shared preference file
</code>```

NOTE: This requires a rooted device such as the stock Android virtual devices, a Genymotion device, or an actual rooted handset/tablet, etc.

Body:
Just did this this morning.  From a command prompt:

adb shell
cd /data/data/YOUR_PACKAGE_NAME/shared_prefs
rm * // to remove all shared preference files
rm YOUR_PREFS_NAME.xml // to remove a specific shared preference file

NOTE: This requires a rooted device such as the stock Android virtual devices, a Genymotion device, or an actual rooted handset/tablet, etc.


问:
Get nullpointerexception while inflating in custom adapter of RecyclerView
This is onCreateViewHolder of my adapter :

```<code>    @Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    try
    {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
        return new ViewHolder(v);
    }
    catch (Exception e)
    {
        return  null ;
    }

}
</code>```

and this line throw NullPointException :

```<code>    LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
</code>```

I debugged function but nothing was null  , so I dont understand what causes problem ?

答:
According to your error line I guess it can be :

your item layout

your data

and if one of these ( most probably first one  ) causes problem you may get irrelevant errors in inflating . so I suggest check them first

Body:
This is onCreateViewHolder of my adapter :

    @Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    try
    {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
        return new ViewHolder(v);
    }
    catch (Exception e)
    {
        return  null ;
    }

}

and this line throw NullPointException :

    LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);

I debugged function but nothing was null  , so I dont understand what causes problem ?


问:
Wordpress blog page title font not appropriate
[Link for blog][1]

In the above Blog page how can i increase font for title of every post?

答:
Add following in style.css. Appearance->Editor->style.css</p>

```<code>.entry-title
{
font-size:30px;
}
</code>```

Body:
Add following in style.css. Appearance->Editor->style.css

.entry-title
{
font-size:30px;
}


问:
FindAndUpdate How to check if document was really updated
Imagine the following model:

```<code>var Office =
{
    id: 1,
    name: "My Office",
    branches:
    [
      {
        adddress: "Some street, that avenue",
        isPrincipal: true,
      },
      {
        adddress: "Another address",
        isPrincipal: false,
      },
    ]
}
</code>```

I'd like to remove a branch, but we can't let the user remove the principal branch from an office. So here's my function:

```<code>remove: function(body)
{
  return new Promise(function(resolve, reject)
  {
    return Office.findByIdAndUpdate(1, { $pull: {'branches': {_id: body.branch.id}}}, { new: true })
    .then(function(updatedOffice){
      resolve(updatedOffice)
    })
    .catch(function(error){
      reject(error);
    });

  })
}
</code>```

I have some doubts here:

As you can see I haven't included the another WHERE on the isPrincipal property, this is because I don't know how can I determine whether the office object got actually changed. Because the object will alway be retrieved but... How can I know this for sure?

Is FindByIdAndUpdate the best approach considering we can't let a user delete the principal branch, and if he's trying to do so, we have to show a warning.

答:
Finding and updating in two steps would better in this case, as you just said you'll have the option of warning the user.

A note on find. You have an array of objects branches. To match more than one field in find $elemMatch is needed. The query will look something like:

```<code>Office.findOne({_id: 1, "branches" : {$elemMatch: {"_id": body.branch.id, "isPrincipal": false}}})
</code>```

Which will either return the office document or not. If it does, you proceed with findByIdAndUpdate (which is better than modifying and saving the already found document). If it does not, return a forbidden message to the user.

Body:
Imagine the following model:

var Office =
{
    id: 1,
    name: "My Office",
    branches:
    [
      {
        adddress: "Some street, that avenue",
        isPrincipal: true,
      },
      {
        adddress: "Another address",
        isPrincipal: false,
      },
    ]
}

I'd like to remove a branch, but we can't let the user remove the principal branch from an office. So here's my function:

remove: function(body)
{
  return new Promise(function(resolve, reject)
  {
    return Office.findByIdAndUpdate(1, { $pull: {'branches': {_id: body.branch.id}}}, { new: true })
    .then(function(updatedOffice){
      resolve(updatedOffice)
    })
    .catch(function(error){
      reject(error);
    });

  })
}

I have some doubts here:

As you can see I haven't included the another WHERE on the isPrincipal property, this is because I don't know how can I determine whether the office object got actually changed. Because the object will alway be retrieved but... How can I know this for sure?

Is FindByIdAndUpdate the best approach considering we can't let a user delete the principal branch, and if he's trying to do so, we have to show a warning.

Body:
Finding and updating in two steps would better in this case, as you just said you'll have the option of warning the user.

A note on find. You have an array of objects branches. To match more than one field in find $elemMatch is needed. The query will look something like:

Office.findOne({_id: 1, "branches" : {$elemMatch: {"_id": body.branch.id, "isPrincipal": false}}})

Which will either return the office document or not. If it does, you proceed with findByIdAndUpdate (which is better than modifying and saving the already found document). If it does not, return a forbidden message to the user.


答: Find Class/ID of element you want to change with tool like Element Inspector of firefox/chrome then add appropriate styling to your element.</p>

Title: Wordpress blog page title font not appropriate

Body:
[Link for blog][1]

In the above Blog page how can i increase font for title of every post?


问:
Navigate in Angular 2 Without Having to Click On an HTML Element
It is possible to find many examples showing how to navigate between components using a button or a routerLink in angular 2. What I want to do is to navigate to a certain component when an error occurs, without user action. Like this:

```<code>class MyErrorHandler implements ErrorHandler {
    handleError(error) {
        this.router.navigate(['/pagenotfound']);
    }
}
</code>```

But it is not possible to initialize a Router object in MyErrorHandler constructor. Is there any way to work around this issue and create an auto navigate system?

答:
If you want to use the Router service inside your error handler class, you will have to inject it. You can do this by registering your service using the @Injectable decorator. See the example below.

```<code>@Injectable()
export class MyErrorHandler {
    constructor(private router: Router) {

    }

    handleError(error) {
        this.router.navigate(['/pagenotfound']);
    }
}
</code>```

After doing this you can inject your MyErrorHandler service into your component or any other place you would like to use it.

For more information on dependency injection (DI), see:
https://angular.io/guide/dependency-injection

Body:
It is possible to find many examples showing how to navigate between components using a button or a routerLink in angular 2. What I want to do is to navigate to a certain component when an error occurs, without user action. Like this:

class MyErrorHandler implements ErrorHandler {
    handleError(error) {
        this.router.navigate(['/pagenotfound']);
    }
}

But it is not possible to initialize a Router object in MyErrorHandler constructor. Is there any way to work around this issue and create an auto navigate system?

Body:
If you want to use the Router service inside your error handler class, you will have to inject it. You can do this by registering your service using the @Injectable decorator. See the example below.

@Injectable()
export class MyErrorHandler {
    constructor(private router: Router) {

    }

    handleError(error) {
        this.router.navigate(['/pagenotfound']);
    }
}

After doing this you can inject your MyErrorHandler service into your component or any other place you would like to use it.

For more information on dependency injection (DI), see:
https://angular.io/guide/dependency-injection


问:
palindrome or not what logical error in this
what is the logical error in this code.In this non palindrome are also showing palindrome like "java"is not palindrome but code shows it palindrome</p>

```<code>     package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());
        StringBuffer sbuffer1=new StringBuffer();
        sbuffer1=sbuffer.reverse();
        System.out.println(sbuffer1);
        if(sbuffer1.equals(sbuffer)){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");

        }
        input.close();
    }

}
</code>```

答:
Use this Code to check how many palindromes are present in the sentence.
This doesn't use any predefined method to reverse. </p>

```<code>import java.io.*;
class String_Pallindrome
{
   public static void main()throws IOException
   {
       DataInputStream br= new DataInputStream(System.in);
       String word="",str,word1="";
       char c,ch;
       int i,j,pc=0;
       System.out.println("Enter the Sentence");
       str=br.readLine();
       System.out.print("The Pallindrome words are :- ");
       for(i=0;i<str.length();i++)
       {

           c=str.charAt(i);
           if(c==' ')
           {
               for(j=0;j<word.length();j++)
               {
                   ch=word.charAt(j);
                   word1=ch+word1;
                }
               if(word1.equalsIgnoreCase(word)==true)
                      pc++;
               word1="";word="";
            }
           else
              word+=c;
            }
       System.out.println();
       System.out.println("Number of Pallindrome word= "+pc);
   }
}
</code>```

Body:
what is the logical error in this code.In this non palindrome are also showing palindrome like "java"is not palindrome but code shows it palindrome

     package stringbuffer;
import java.util.Scanner;
public class Task1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sbuffer = new StringBuffer();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string");
        sbuffer.append(input.nextLine());
        StringBuffer sbuffer1=new StringBuffer();
        sbuffer1=sbuffer.reverse();
        System.out.println(sbuffer1);
        if(sbuffer1.equals(sbuffer)){
            System.out.println("palindrome");
        }
        else{
            System.out.println("not palindrome");

        }
        input.close();
    }

}

Body:
Use this Code to check how many palindromes are present in the sentence.
This doesn't use any predefined method to reverse.

import java.io.*;
class String_Pallindrome
{
   public static void main()throws IOException
   {
       DataInputStream br= new DataInputStream(System.in);
       String word="",str,word1="";
       char c,ch;
       int i,j,pc=0;
       System.out.println("Enter the Sentence");
       str=br.readLine();
       System.out.print("The Pallindrome words are :- ");
       for(i=0;i<str.length();i++)
       {

           c=str.charAt(i);
           if(c==' ')
           {
               for(j=0;j<word.length();j++)
               {
                   ch=word.charAt(j);
                   word1=ch+word1;
                }
               if(word1.equalsIgnoreCase(word)==true)
                      pc++;
               word1="";word="";
            }
           else
              word+=c;
            }
       System.out.println();
       System.out.println("Number of Pallindrome word= "+pc);
   }
}


问:
How to get input values when opened by material dialog
I'm trying to get the values from input where it opened by Material Dialog box. I tried below but the values is not changed one.

Please see this plunker https://plnkr.co/edit/tiiMwvQTB4sbz5uTAByP?p=preview

```<code>import {Component} from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';

@Component({
  selector: 'dialog-result-example',
  templateUrl: 'dialog-result-example.html',
})
export class DialogResultExample {
  selectedOption: string;

  constructor(public dialog: MdDialog) {}

  openDialog() {
    let dialogRef = this.dialog.open(DialogResultExampleDialog);
    dialogRef.afterClosed().subscribe(result => {
      this.selectedOption = result;
      const dialogResultExampleDialog = new DialogResultExampleDialog()
      console.log(dialogResultExampleDialog.hero) <--- this value is not the changed value
    });
  }
}

export class Hero {
  id: number;
  name: String
}

@Component({
  selector: 'dialog-result-example-dialog',
  templateUrl: 'dialog-result-example-dialog.html',
})
export class DialogResultExampleDialog {
  hero: Hero = {
    id: 1,
    name: "Hello"
  }
  constructor(public dialogRef: MdDialogRef<DialogResultExampleDialog>) {}
}
</code>```

答:
If You want to return value from dialog instance You should call dialog instance close method in Your dialog component class.

To do that, I added close method to DialogResultExampleDialog class. This method simply calls this.dialogRef.close(this.hero);

plunker

Body:
I'm trying to get the values from input where it opened by Material Dialog box. I tried below but the values is not changed one.

Please see this plunker https://plnkr.co/edit/tiiMwvQTB4sbz5uTAByP?p=preview

import {Component} from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';

@Component({
  selector: 'dialog-result-example',
  templateUrl: 'dialog-result-example.html',
})
export class DialogResultExample {
  selectedOption: string;

  constructor(public dialog: MdDialog) {}

  openDialog() {
    let dialogRef = this.dialog.open(DialogResultExampleDialog);
    dialogRef.afterClosed().subscribe(result => {
      this.selectedOption = result;
      const dialogResultExampleDialog = new DialogResultExampleDialog()
      console.log(dialogResultExampleDialog.hero) <--- this value is not the changed value
    });
  }
}

export class Hero {
  id: number;
  name: String
}

@Component({
  selector: 'dialog-result-example-dialog',
  templateUrl: 'dialog-result-example-dialog.html',
})
export class DialogResultExampleDialog {
  hero: Hero = {
    id: 1,
    name: "Hello"
  }
  constructor(public dialogRef: MdDialogRef<DialogResultExampleDialog>) {}
}


问:
Cannot POST ajax request
can anyone explain to me why i cannot post the ajax request. When i run this code the console appear POST http://localhost:8080/api/users 404 (Not Found), and in the networth part the preview is 404 not found
In the index.js file </p>

```<code>        var path = require('path');
    var express = require('express');
    var webpack = require('webpack');
    var config = require('./webpack.config.dev.js');

    var app = express();
    var compiler = webpack(config);
    var bodyParser = require('body-parser');
    var users = require('./server/routes/users');

    app.use(bodyParser.json());

    app.use('/api/users', users);

    app.use(require('webpack-dev-middleware')(compiler, {
      noInfo: true,
      publicPath: config.output.publicPath
    }));

    app.use(require('webpack-hot-middleware')(compiler));

    app.get('*', function(req, res) {
      res.sendFile(path.join(__dirname, 'index.html'));
    });

    app.listen(8080, 'localhost', function(err) {
      if (err) {
        console.log(err);
        return;
      }

      console.log('Listening at http://localhost:8080');
    });
</code>```

<p>and the users file </p>

```<code>    var express = require('express')
    var router = express.Router()

    // middleware that is specific to this router
    function validateInput(data) {
      let errors = {};

      if (Validator.isNull(data.username)){
        errors.username = "This field is required";
      }
      if (Validator.isEmail(data.email)) {
        errors.email = "Email is invalid";
      }
      if (Validator.isNull(data.password)){
        errors.password = 'This field is required';
      }
      if (Validator.isNull(data.passwordConfirmation)){
        errors.passwordConfirmation = 'This field is required';
      }
      if (Validator.equals(data.password, data.passwordConfirmation)){
        errors.passwordConfirmation = 'Password must match';
      }
      return {
        errors,
        isValid: isEmpty(errors)
      }
    }

    router.post('/api/users', (req, res) => {

          console.log('runiing the router/post');
          console.log(req.body);
          const {errors, isValid} = validateInput(req.body);

          if (!isValid) {
            res.status(400).json(errors);
          }

    });

    module.exports = router
</code>```

答:
in users.js file the function should be

```<code>router.post('/', (req, res) => {

          console.log('runiing the router/post');
          console.log(req.body);
          const {errors, isValid} = validateInput(req.body);

          if (!isValid) {
            res.status(400).json(errors);
          }

    });
</code>```

Because index.js have already resolved /api/users part in the request url http://localhost:8080/api/users at this point. So you only have to map after the /api/users in your users js file.

For example, if you have following function in users.js file

```<code>router.post('/:id', (req, res) => {
      ...
    }
</code>```

It will resole to the path http://localhost:8080/api/users/1

Edit
In your existing version,

```<code>router.post('/api/users', (req, res) => {
  ...
}
</code>```

will resolve as http://localhost:8080/api/users/api/users

Title: Cannot POST ajax request

Body:
can anyone explain to me why i cannot post the ajax request. When i run this code the console appear POST http://localhost:8080/api/users 404 (Not Found), and in the networth part the preview is 404 not found
In the index.js file

        var path = require('path');
    var express = require('express');
    var webpack = require('webpack');
    var config = require('./webpack.config.dev.js');

    var app = express();
    var compiler = webpack(config);
    var bodyParser = require('body-parser');
    var users = require('./server/routes/users');

    app.use(bodyParser.json());

    app.use('/api/users', users);

    app.use(require('webpack-dev-middleware')(compiler, {
      noInfo: true,
      publicPath: config.output.publicPath
    }));

    app.use(require('webpack-hot-middleware')(compiler));

    app.get('*', function(req, res) {
      res.sendFile(path.join(__dirname, 'index.html'));
    });

    app.listen(8080, 'localhost', function(err) {
      if (err) {
        console.log(err);
        return;
      }

      console.log('Listening at http://localhost:8080');
    });

and the users file

    var express = require('express')
    var router = express.Router()

    // middleware that is specific to this router
    function validateInput(data) {
      let errors = {};

      if (Validator.isNull(data.username)){
        errors.username = "This field is required";
      }
      if (Validator.isEmail(data.email)) {
        errors.email = "Email is invalid";
      }
      if (Validator.isNull(data.password)){
        errors.password = 'This field is required';
      }
      if (Validator.isNull(data.passwordConfirmation)){
        errors.passwordConfirmation = 'This field is required';
      }
      if (Validator.equals(data.password, data.passwordConfirmation)){
        errors.passwordConfirmation = 'Password must match';
      }
      return {
        errors,
        isValid: isEmpty(errors)
      }
    }

    router.post('/api/users', (req, res) => {

          console.log('runiing the router/post');
          console.log(req.body);
          const {errors, isValid} = validateInput(req.body);

          if (!isValid) {
            res.status(400).json(errors);
          }

    });

    module.exports = router

Body:
in users.js file the function should be

router.post('/', (req, res) => {

          console.log('runiing the router/post');
          console.log(req.body);
          const {errors, isValid} = validateInput(req.body);

          if (!isValid) {
            res.status(400).json(errors);
          }

    });

Because index.js have already resolved /api/users part in the request url http://localhost:8080/api/users at this point. So you only have to map after the /api/users in your users js file.

For example, if you have following function in users.js file

router.post('/:id', (req, res) => {
      ...
    }

It will resole to the path http://localhost:8080/api/users/1

Edit
In your existing version,

router.post('/api/users', (req, res) => {
  ...
}

will resolve as http://localhost:8080/api/users/api/users


问:
Why are div, ldiv and lldiv not templates?
According to this, there are

```<code>std::div_t     div( int x, int y );
std::ldiv_t    div( long x, long y );
std::lldiv_t   div( long long x, long long y );
std::ldiv_t   ldiv( long x, long y );
std::lldiv_t lldiv( long long x, long long y );
</code>```

two div in <cinttypes>

I would prefer to have seen

```<code>template<typename t>
std::div_t<T> div(T x, T y);
template<>
std::div_t<int> div(int x, int x)
{
  // implementation here
}
</code>```

Thoughts?

答:
You mean you would like to use template specializations instead of overloading? That's not a good idea.

First of all, what if I use a type that has a conversion operator to long? Well, none of the specialization is going to get chosen, because they are only taken when there is an exact match, and that type is not part of them. So I have to use a static_cast. This is not the case with operator overloading, where such a conversion is allowed and will happen.

Second of all, what advantage do you gain by specializing like that? You still have to write the same implementation for each specialization. In addition, you can't easily write the implementation in a source file.

The only advantage I could see is that it is much easier to take the address of a specific version of the function, as with templates you would do &std::div<int> instead of static_casting to the right overload.

Here a generic solution would be much more appropriate, because there is some duplication between those functions. Maybe something like this:

```<code>template<typename T>
concept Integral = std::is_integral_v<T>;

template <Integral T>
struct cdiv_t {
    T quot{};
    T rem{};
};

constexpr auto cdiv(Integral auto x, Integral auto y) noexcept {
    return cdiv_t{x / y, x % y};
}
</code>```

Body:
According to this, there are

std::div_t     div( int x, int y );
std::ldiv_t    div( long x, long y );
std::lldiv_t   div( long long x, long long y );
std::ldiv_t   ldiv( long x, long y );
std::lldiv_t lldiv( long long x, long long y );

two div in <cinttypes>

I would prefer to have seen

template<typename t>
std::div_t<T> div(T x, T y);
template<>
std::div_t<int> div(int x, int x)
{
  // implementation here
}

Thoughts?

Body:
You mean you would like to use template specializations instead of overloading? That's not a good idea.

First of all, what if I use a type that has a conversion operator to long? Well, none of the specialization is going to get chosen, because they are only taken when there is an exact match, and that type is not part of them. So I have to use a static_cast. This is not the case with operator overloading, where such a conversion is allowed and will happen.

Second of all, what advantage do you gain by specializing like that? You still have to write the same implementation for each specialization. In addition, you can't easily write the implementation in a source file.

The only advantage I could see is that it is much easier to take the address of a specific version of the function, as with templates you would do &std::div<int> instead of static_casting to the right overload.

Here a generic solution would be much more appropriate, because there is some duplication between those functions. Maybe something like this:

template<typename T>
concept Integral = std::is_integral_v<T>;

template <Integral T>
struct cdiv_t {
    T quot{};
    T rem{};
};

constexpr auto cdiv(Integral auto x, Integral auto y) noexcept {
    return cdiv_t{x / y, x % y};
}


问:
File upload using a Perl CGI script not working
The following code doesn't have any syntax errors, but still doesn't working.Can I use server ip(like 100.100.100.100) for $Domain and what path should be given for $directory(i mean adding the serverip or domain name?Please help</p>

```<code>#!/usr/bin/perl
use CGI;
$CGI::POST_MAX= 100 * 1024;
$CGI::DISABLE_UPLOADS=0;
$Referer = $ENV{HTTP_REFERER};
$Domain = "xxx.com";
$cgi = new CGI;
$file=$cgi->upload('text');
print $cgi->header,
$cgi->start_html
(
        -title=>'CGI.pm File Upload'
);
print <<EOF;
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="text" size=60><br>
<input type="submit" value="Upload">
</form>
EOF
if($file)
{
        if($Referer =~ "$Domain")
        {
                $directory="var/www/cgi-bin/uploads";
                open UPLOAD, ">$directory$file";
                binmode UPLOAD;
                while(<$file>) {print UPLOAD;}
                close UPLOAD;
        }
}
$cgi->end_html;
exit;
</code>```

答:
Looks like you need to read the documentation on file upload basics again. The sample code they have is:

```<code>use autodie;

# undef may be returned if it's not a valid file handle
if ( my $io_handle = $q->upload('field_name') ) {
    open ( my $out_file,'>>','/usr/local/web/users/feedback' );
    while ( my $bytesread = $io_handle->read($buffer,1024) ) {
        print $out_file $buffer;
    }
}
</code>```

There are some stylistic differences to your code, but the important thing to note that is that when your code runs this line:

```<code>$file=$cgi->upload('text');
</code>```

Then $file contains an open filehandle. It does not contain the filename. This means that there are at least three errors in these lines of your code:

```<code>$directory="var/www/cgi-bin/uploads";
open UPLOAD, ">$directory$file";
</code>```

The value you store in $directory should almost certainly start with a / (so it's /var/www/cgi-bin/uploads).

You also need another / between $directory and $file (otherwise, it will contain something like /var/www/cgi-bin/uploadsmyfile.dat).

You need to call $cgi->param('text') to get the name of the file that is being uploaded.

This is what is stopping your program from working. The upload section of your code should look like this:

```<code>my $filename = $cgi->param('text');
my $fh       = $cgi->upload('text');

my $directory = '/var/www/cgi-bin/uploads';

open my $upload_fh, '>', "$directory/$filename"
  or die "Can't open '$directory/$filename': $!";

print $upload_fh $_ while <$fh>;
</code>```

Note that I've made some stylistic improvements here:

Used 3-argument version of open()

Used lexical filehandles

Checked the success of the open() call and killed the program with a useful error message if it fails

All in all, you seem to have learned CGI programming from a resource that is about twenty years out of date. Your code looks like it comes from the 1990s.

A few other tips:

Always use strict and use warnings.

Indirect object notation (new CGI) is potentially very confusing. Use CGI->new instead.

We've known that the HTML-generation functions in CGI.pm are a terrible idea since the end of the last millennium. Please don't use them. Many good templating solutions are available for Perl.

Writing a CGI program in 2017 is a terrible idea. Take a look at CGI::Alternatives for an introduction to Modern Perl Web Development tools.

Body:
The following code doesn't have any syntax errors, but still doesn't working.Can I use server ip(like 100.100.100.100) for $Domain and what path should be given for $directory(i mean adding the serverip or domain name?Please help

#!/usr/bin/perl
use CGI;
$CGI::POST_MAX= 100 * 1024;
$CGI::DISABLE_UPLOADS=0;
$Referer = $ENV{HTTP_REFERER};
$Domain = "xxx.com";
$cgi = new CGI;
$file=$cgi->upload('text');
print $cgi->header,
$cgi->start_html
(
        -title=>'CGI.pm File Upload'
);
print <<EOF;
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="text" size=60>

<input type="submit" value="Upload">
</form>
EOF
if($file)
{
        if($Referer =~ "$Domain")
        {
                $directory="var/www/cgi-bin/uploads";
                open UPLOAD, ">$directory$file";
                binmode UPLOAD;
                while(<$file>) {print UPLOAD;}
                close UPLOAD;
        }
}
$cgi->end_html;
exit;

Body:
Looks like you need to read the documentation on file upload basics again. The sample code they have is:

use autodie;

# undef may be returned if it's not a valid file handle
if ( my $io_handle = $q->upload('field_name') ) {
    open ( my $out_file,'>>','/usr/local/web/users/feedback' );
    while ( my $bytesread = $io_handle->read($buffer,1024) ) {
        print $out_file $buffer;
    }
}

There are some stylistic differences to your code, but the important thing to note that is that when your code runs this line:

$file=$cgi->upload('text');

Then $file contains an open filehandle. It does not contain the filename. This means that there are at least three errors in these lines of your code:

$directory="var/www/cgi-bin/uploads";
open UPLOAD, ">$directory$file";

The value you store in $directory should almost certainly start with a / (so it's /var/www/cgi-bin/uploads).

You also need another / between $directory and $file (otherwise, it will contain something like /var/www/cgi-bin/uploadsmyfile.dat).

You need to call $cgi->param('text') to get the name of the file that is being uploaded.

This is what is stopping your program from working. The upload section of your code should look like this:

my $filename = $cgi->param('text');
my $fh       = $cgi->upload('text');

my $directory = '/var/www/cgi-bin/uploads';

open my $upload_fh, '>', "$directory/$filename"
  or die "Can't open '$directory/$filename': $!";

print $upload_fh $_ while <$fh>;

Note that I've made some stylistic improvements here:

Used 3-argument version of open()

Used lexical filehandles

Checked the success of the open() call and killed the program with a useful error message if it fails

All in all, you seem to have learned CGI programming from a resource that is about twenty years out of date. Your code looks like it comes from the 1990s.

A few other tips:

Always use strict and use warnings.

Indirect object notation (new CGI) is potentially very confusing. Use CGI->new instead.

We've known that the HTML-generation functions in CGI.pm are a terrible idea since the end of the last millennium. Please don't use them. Many good templating solutions are available for Perl.

Writing a CGI program in 2017 is a terrible idea. Take a look at CGI::Alternatives for an introduction to Modern Perl Web Development tools.


问:
Diameter of Binary Tree - Better Design
I have written a code for finding diameter of Binary Tree.
Need suggestions for the following:

Can I do this without using static variable at class level?

Is the algorithm fine/any suggestions?

```<code>public class DiameterOfTree {
public static int diameter = 0;
public static int getDiameter(BinaryTreeNode root) {
    if (root != null) {
        int leftCount = getDiameter(root.getLeft());
        int rightCount = getDiameter(root.getRight());
        if (leftCount + rightCount > diameter) {
            diameter = leftCount + rightCount;
            System.out.println("---diameter------------->" + diameter);
        }
        if ( leftCount > rightCount) {
            return leftCount + 1;
        }
        return rightCount + 1;
    }
    return 0;
  }
}
</code>```

答:
Here is one recursive solution in C++ which gives you the height as well as diameter of binary tree.

```<code>struct tree
{
    int height = -1;
    int diameter = 0;
};

struct tree BSTDiameter(struct node *root)
{
    struct tree currentTree, leftTree, rightTree;
    if (root == NULL)
    {
        currentTree.height = -1;
        currentTree.diameter = 0;
        return currentTree;
    }
    leftTree = BSTDiameter(root->left);
    rightTree = BSTDiameter(root->right);
    currentTree.height = ((leftTree.height > rightTree.height) ? leftTree.height : rightTree.height) + 1;
    if (leftTree.height == -1 || rightTree.height == -1)
        currentTree.diameter = 0;
    else
        currentTree.diameter = (leftTree.height + rightTree.height + 3) > (rightTree.diameter > leftTree.diameter ? rightTree.diameter : leftTree.diameter) ? (leftTree.height + rightTree.height + 3) : (rightTree.diameter > leftTree.diameter ? rightTree.diameter : leftTree.diameter);
    return currentTree;
}
</code>```

The time complexity of this is O(h) where h is height of the tree.
   Hope that helped you.

Title: Diameter of Binary Tree - Better Design

Body:
I have written a code for finding diameter of Binary Tree.
Need suggestions for the following:

Can I do this without using static variable at class level?

Is the algorithm fine/any suggestions?

public class DiameterOfTree {
public static int diameter = 0;
public static int getDiameter(BinaryTreeNode root) {
    if (root != null) {
        int leftCount = getDiameter(root.getLeft());
        int rightCount = getDiameter(root.getRight());
        if (leftCount + rightCount > diameter) {
            diameter = leftCount + rightCount;
            System.out.println("---diameter------------->" + diameter);
        }
        if ( leftCount > rightCount) {
            return leftCount + 1;
        }
        return rightCount + 1;
    }
    return 0;
  }
}

Body:
Here is one recursive solution in C++ which gives you the height as well as diameter of binary tree.

struct tree
{
    int height = -1;
    int diameter = 0;
};

struct tree BSTDiameter(struct node *root)
{
    struct tree currentTree, leftTree, rightTree;
    if (root == NULL)
    {
        currentTree.height = -1;
        currentTree.diameter = 0;
        return currentTree;
    }
    leftTree = BSTDiameter(root->left);
    rightTree = BSTDiameter(root->right);
    currentTree.height = ((leftTree.height > rightTree.height) ? leftTree.height : rightTree.height) + 1;
    if (leftTree.height == -1 || rightTree.height == -1)
        currentTree.diameter = 0;
    else
        currentTree.diameter = (leftTree.height + rightTree.height + 3) > (rightTree.diameter > leftTree.diameter ? rightTree.diameter : leftTree.diameter) ? (leftTree.height + rightTree.height + 3) : (rightTree.diameter > leftTree.diameter ? rightTree.diameter : leftTree.diameter);
    return currentTree;
}

The time complexity of this is O(h) where h is height of the tree.
   Hope that helped you.


问:
Linear combination of variating number of vectors
I have a variating number of vectors which have a linear dependency. I'd like to find the linear combination of coefficients which brings their sum to 0.
For example:

```<code>a*[1;1;1]+b[2;2;2]=0
a=2, b=-1
</code>```

I could use iterators, but the number of vectors is changing and can be quite large.

Thanks

答:
Solution

You can use the following approach:

arrange the base vectors in columns

Use SVD to calculate a non trivial solution.

code

```<code>%defines input
v1 = [1;1;1];
v2 = [2;2;2];

%perform calculation
[U S V] = svd([v1,v2]);
x = V(:,end)
</code>```

result

```<code>v1*x(1)+v2*x(2)

ans =
 0
 0
 0

x =
0.8944
-0.4472
</code>```

Body:
I have a variating number of vectors which have a linear dependency. I'd like to find the linear combination of coefficients which brings their sum to 0.
For example:

a*[1;1;1]+b[2;2;2]=0
a=2, b=-1

I could use iterators, but the number of vectors is changing and can be quite large.

Thanks

Body:
Solution

You can use the following approach:

arrange the base vectors in columns

Use SVD to calculate a non trivial solution.

code

%defines input
v1 = [1;1;1];
v2 = [2;2;2];

%perform calculation
[U S V] = svd([v1,v2]);
x = V(:,end)

result

v1*x(1)+v2*x(2)

ans =
 0
 0
 0

x =
0.8944
-0.4472


问:
WireMock with multiple hosts and dnsmasq?
I'm working on mocking endpoints for an iOS app that hits over a dozen different HTTPS hosts. Based on my understanding from the WireMock docs and this answer from the maintainer, WireMock is designed to proxy / mock only one host. My current plan is to use dnsmasq to point one host at WireMock at a time.

```<code>                                      +----------+            +-------------------+
                                      |          |            |                   |
                                      | WireMock +-->Proxy+--->  123.example.com  |
                                      |          |            |                   |
                                      +----^-----+            +-------------------+
                                           |
                                           |                  +-------------------+
+-------+                                 +----+----+         |                   |
|       +---> https://123.example.com +--->         |   +----->  xyz.example.com  |
|       |                                 |         |   |     |                   |
|  App  +---> https://xyz.example.com +---> dnsmasq +---+     +-------------------+
|       |                                 |         |
|       +---> https://9.different.com +--->         +---+     +-------------------+
+-------+                                 +---------+   |     |                   |
                                                        +----->  9.different.com  |
                                                              |                   |
                                                              +-------------------+
</code>```

This seems pretty clunky, is there a better way to mock multiple hosts like this? One of the primary constraints is that these have to be tested over HTTPS and not unencrypted.

答:
You should be able to achieve this by creating stubs that have a host header condition in the request. That way e.g. a request to

GET /hello
Host: firsthost.example.com

And a request to
GET /hello
Host: secondhost.example.com

would match different stubs and there return different responses.

Body:
I'm working on mocking endpoints for an iOS app that hits over a dozen different HTTPS hosts. Based on my understanding from the WireMock docs and this answer from the maintainer, WireMock is designed to proxy / mock only one host. My current plan is to use dnsmasq to point one host at WireMock at a time.

                                      +----------+            +-------------------+
                                      |          |            |                   |
                                      | WireMock +-->Proxy+--->  123.example.com  |
                                      |          |            |                   |
                                      +----^-----+            +-------------------+
                                           |
                                           |                  +-------------------+
+-------+                                 +----+----+         |                   |
|       +---> https://123.example.com +--->         |   +----->  xyz.example.com  |
|       |                                 |         |   |     |                   |
|  App  +---> https://xyz.example.com +---> dnsmasq +---+     +-------------------+
|       |                                 |         |
|       +---> https://9.different.com +--->         +---+     +-------------------+
+-------+                                 +---------+   |     |                   |
                                                        +----->  9.different.com  |
                                                              |                   |
                                                              +-------------------+

This seems pretty clunky, is there a better way to mock multiple hosts like this? One of the primary constraints is that these have to be tested over HTTPS and not unencrypted.


问:
PHP Login with bCrypt Hashed Passwords

Why didn't the other posts help?

      Other posts didn't help because one was asking since none worked, despite there are a lot of similar questions.

More details

    The thing I want to do is to make a user log in using his password. But, the passwords are hashed using bCrypt in the database.

When I try to enter the real password, it doesn't work and says that the password is incorrect.

But, when I try to enter the hashed password. It says: "Successfully logged in".

How to make it log in using the real password not the hash?!

Code

Login.php

```<code><form method="post" action="loginsession.php">//login
    <p>Username <input type="text" name="uid" size="20"> </p>
    <p>Password <input type="password" name="pwd" size="20"> </p>
    <p><input type="submit" value="Login" name="login"></p>
</form>
</code>```

Loginsession.php

```<code>  <?php
   session_start();
   include ('dbhandler.php');
   $uid = $_POST['uid'];
   $pwd = $_POST['pwd'];

   $sql = "SELECT * FROM user WHERE uid='$uid' and pwd='$pwd' ";
   $result = mysqli_query($conn, $sql);
   $row = mysqli_fetch_assoc($result);
   $encrypted_pwd = password_hash($pwd, PASSWORD_DEFAULT);
   $hash = password_verify($pwd,$encrypted_pwd);
   $count = mysqli_num_rows($result);

   if ($count == 1) {
   echo("Logging in...");
   $_SESSION['id'] = $row['id'];
   $_SESSION['uid'] = $row['uid'];
   $_SESSION['pwd'] = $row['pwd'];
   echo("<h1 style='color:green;'>Successfully Logged In");

   }
    else {
           echo "Your Login Name or Password is invalid";
                die();
         }

    ?>
</code>```

答:
There was so much wrong that a rewrite was more appropriate: </p>

```<code><?php
   session_start();
   include 'dbhandler.php'; // shouldn't be include './dbhandler.php'; ?
   $uid = $_POST['uid'];
   $pwd = $_POST['pwd'];

   $sql = "SELECT * FROM user WHERE uid='".mysqli_real_escape_string($conn, $uid)."'";
   $result = mysqli_query($conn, $sql);
   if (mysqli_num_rows($result) === 1) {
     $row = mysqli_fetch_assoc($result);
     if (password_verify($pwd, $row['pwd'])) {
       $_SESSION['id'] = $row['id'];
       $_SESSION['uid'] = $row['uid'];
       $_SESSION['pwd'] = $row['pwd'];
       // redirect to "login success" page would be a better solution
       echo "<h1 style='color:green;'>Successfully Logged In";
     } else {
       echo "Invalid password";
     }
   } else {
     echo "Your login name is invalid";
   }
</code>```

Title: PHP Login with bCrypt Hashed Passwords

Body:
Why didn't the other posts help?

      Other posts didn't help because one was asking since none worked, despite there are a lot of similar questions.

More details

    The thing I want to do is to make a user log in using his password. But, the passwords are hashed using bCrypt in the database.

When I try to enter the real password, it doesn't work and says that the password is incorrect.

But, when I try to enter the hashed password. It says: "Successfully logged in".

How to make it log in using the real password not the hash?!

Code

Login.php

<form method="post" action="loginsession.php">//login

Username <input type="text" name="uid" size="20">

Password <input type="password" name="pwd" size="20">

<input type="submit" value="Login" name="login">

</form>

Loginsession.php

  <?php
   session_start();
   include ('dbhandler.php');
   $uid = $_POST['uid'];
   $pwd = $_POST['pwd'];

   $sql = "SELECT * FROM user WHERE uid='$uid' and pwd='$pwd' ";
   $result = mysqli_query($conn, $sql);
   $row = mysqli_fetch_assoc($result);
   $encrypted_pwd = password_hash($pwd, PASSWORD_DEFAULT);
   $hash = password_verify($pwd,$encrypted_pwd);
   $count = mysqli_num_rows($result);

   if ($count == 1) {
   echo("Logging in...");
   $_SESSION['id'] = $row['id'];
   $_SESSION['uid'] = $row['uid'];
   $_SESSION['pwd'] = $row['pwd'];
   echo("
Successfully Logged In");

   }
    else {
           echo "Your Login Name or Password is invalid";
                die();
         }

    ?>

Body:
There was so much wrong that a rewrite was more appropriate:

<?php
   session_start();
   include 'dbhandler.php'; // shouldn't be include './dbhandler.php'; ?
   $uid = $_POST['uid'];
   $pwd = $_POST['pwd'];

   $sql = "SELECT * FROM user WHERE uid='".mysqli_real_escape_string($conn, $uid)."'";
   $result = mysqli_query($conn, $sql);
   if (mysqli_num_rows($result) === 1) {
     $row = mysqli_fetch_assoc($result);
     if (password_verify($pwd, $row['pwd'])) {
       $_SESSION['id'] = $row['id'];
       $_SESSION['uid'] = $row['uid'];
       $_SESSION['pwd'] = $row['pwd'];
       // redirect to "login success" page would be a better solution
       echo "<h1 style='color:green;'>Successfully Logged In";
     } else {
       echo "Invalid password";
     }
   } else {
     echo "Your login name is invalid";
   }


问:
Calling dynamically created dictionaries
In my code i have created multiple dictionaries with the following code;

```<code>g = globals()
    lrange = len(requestcells * 2)
    for i in range(1, lrange):
        g['request_{0}'.format(i)] = {}
</code>```

I then have a for loop which iterates over excel coordinates from a list and extracts data from them. Each row in the excel file is a separate set of data (request). I want to store these requests in separate dictionary.

request_1 request_2 etc etc (Dynamic as it always changes)

However I am stuck on how I can input the data into a new dictionary when its a new row and over multiple iterations.

```<code>for items in requestcells:
        for row in ws.iter_rows(min_row=items, max_row=items):
            for cell in row:
                cell_location = (cell.column)
                header_text = header_dict[cell_location + "3"]

                # This should be request 1 on first iteration and 3rd on second iteration

                request_??[header_text] = cell.value

        for row in ws.iter_rows(min_row=items + 1, max_row=items + 1):
            for cell in row:
                cell_location = (cell.column)
                header_text = header_dict[cell_location + "3"]

                # This should be request 2 on first iteration and 4th on second iteration

                request_??[header_text] = cell.value
</code>```

答:
Don't use variable names as part of your data structure. Variable names are for the programmer to type in. If you're using code to produce them, you probably want that code to be indexing a list or a dictionary instead.

I'd change the code you've shown to put the dictionaries in a list instead of making them each global variables. It might also make sense to use two separate lists for the two different sets of data you're currently interleaving with your even and odd request numbers.

```<code>requests = [{} for _ in range(len(requestcells * 2)]

for i, items in enumerate(requestcells):
    for row in ws.iter_rows(min_row=items, max_row=items):
        for cell in row:
            cell_location = (cell.column)
            header_text = header_dict[cell_location + "3"]

            requests[2*i][header_text] = cell.value

    for row in ws.iter_rows(min_row=items + 1, max_row=items + 1):
        for cell in row:
            cell_location = (cell.column)
            header_text = header_dict[cell_location + "3"]

            requests[2*i+1][header_text] = cell.value
</code>```

Body:
In my code i have created multiple dictionaries with the following code;

g = globals()
    lrange = len(requestcells * 2)
    for i in range(1, lrange):
        g['request_{0}'.format(i)] = {}

I then have a for loop which iterates over excel coordinates from a list and extracts data from them. Each row in the excel file is a separate set of data (request). I want to store these requests in separate dictionary.

request_1 request_2 etc etc (Dynamic as it always changes)

However I am stuck on how I can input the data into a new dictionary when its a new row and over multiple iterations.

for items in requestcells:
        for row in ws.iter_rows(min_row=items, max_row=items):
            for cell in row:
                cell_location = (cell.column)
                header_text = header_dict[cell_location + "3"]

                # This should be request 1 on first iteration and 3rd on second iteration

                request_??[header_text] = cell.value

        for row in ws.iter_rows(min_row=items + 1, max_row=items + 1):
            for cell in row:
                cell_location = (cell.column)
                header_text = header_dict[cell_location + "3"]

                # This should be request 2 on first iteration and 4th on second iteration

                request_??[header_text] = cell.value

Body:
Don't use variable names as part of your data structure. Variable names are for the programmer to type in. If you're using code to produce them, you probably want that code to be indexing a list or a dictionary instead.

I'd change the code you've shown to put the dictionaries in a list instead of making them each global variables. It might also make sense to use two separate lists for the two different sets of data you're currently interleaving with your even and odd request numbers.

requests = [{} for _ in range(len(requestcells * 2)]

for i, items in enumerate(requestcells):
    for row in ws.iter_rows(min_row=items, max_row=items):
        for cell in row:
            cell_location = (cell.column)
            header_text = header_dict[cell_location + "3"]

            requests[2*i][header_text] = cell.value

    for row in ws.iter_rows(min_row=items + 1, max_row=items + 1):
        for cell in row:
            cell_location = (cell.column)
            header_text = header_dict[cell_location + "3"]

            requests[2*i+1][header_text] = cell.value


问:
Celery Tasks Lost after sending to rabbitmq broker
I am having a strange issue where some of my tasks are getting dropped after sent to broker. This happens for around 1 out of 10 tasks. I have checked that there is no old celery worker consuming the task.

I used database backed backend and flower to monitor the missing tasks, but the task_id returned after apply_async is not present in database or in flower. Its status always comes as pending.

Then I used celery signals to find out what's happening. I found that for the missing tasks, only before_task_publish and after_task_publish signals are fired. Post that there is no trace for this task.

These are my signals

```<code>@before_task_publish.connect
def before_task_publish_handler(sender=None, headers=None, body=None, **kwargs):
# information about task are located in headers for task messages
# using the task protocol version 2.
  logger.info("BEFORE TASK SENT  id:"+body['id'])

@after_task_publish.connect
def after_task_publish_handler(sender=None, headers=None, body=None, exchange=None, routing_key=None, **kwargs):
# information about task are located in headers for task messages
# using the task protocol version 2.
    logger.info("AFTER TASK SENT  id:"+body['id'])

@task_prerun.connect
def task_prerun_handler(sender=None, task_id=None, task=None, **kwargs):
  logger.info("TASK PRERUN with TASK_ID:"+str(task_id))
</code>```

This is what I found in logs

```<code>$ cat gunicorn-access.log | grep -i 103de274-00dc-4765-844f-d319e9e199c2
  BEFORE TASK SENT id: '103de274-00dc-4765-844f-d319e9e199c2'
  AFTER TASK SENT  id: '103de274-00dc-4765-844f-d319e9e199c2'
</code>```

I am not sure whether the task is ignored by rabbitmq or its silently dropped for some reason.

答:
Once in a while celery loses tasks before it gets executed. If you don't want to lose them, you should set enable task_acks_late(CELERY_ACKS_LATE in old versions).

In your celery settings, set

```<code>task_acks_late = True
</code>```

This makes sure that the task messages will be acknowledged after the task has been executed.

Body:
I am having a strange issue where some of my tasks are getting dropped after sent to broker. This happens for around 1 out of 10 tasks. I have checked that there is no old celery worker consuming the task.

I used database backed backend and flower to monitor the missing tasks, but the task_id returned after apply_async is not present in database or in flower. Its status always comes as pending.

Then I used celery signals to find out what's happening. I found that for the missing tasks, only before_task_publish and after_task_publish signals are fired. Post that there is no trace for this task.

These are my signals

@before_task_publish.connect
def before_task_publish_handler(sender=None, headers=None, body=None, **kwargs):
# information about task are located in headers for task messages
# using the task protocol version 2.
  logger.info("BEFORE TASK SENT  id:"+body['id'])

@after_task_publish.connect
def after_task_publish_handler(sender=None, headers=None, body=None, exchange=None, routing_key=None, **kwargs):
# information about task are located in headers for task messages
# using the task protocol version 2.
    logger.info("AFTER TASK SENT  id:"+body['id'])

@task_prerun.connect
def task_prerun_handler(sender=None, task_id=None, task=None, **kwargs):
  logger.info("TASK PRERUN with TASK_ID:"+str(task_id))

This is what I found in logs

$ cat gunicorn-access.log | grep -i 103de274-00dc-4765-844f-d319e9e199c2
  BEFORE TASK SENT id: '103de274-00dc-4765-844f-d319e9e199c2'
  AFTER TASK SENT  id: '103de274-00dc-4765-844f-d319e9e199c2'

I am not sure whether the task is ignored by rabbitmq or its silently dropped for some reason.

Body:
Once in a while celery loses tasks before it gets executed. If you don't want to lose them, you should set enable task_acks_late(CELERY_ACKS_LATE in old versions).

In your celery settings, set

task_acks_late = True

This makes sure that the task messages will be acknowledged after the task has been executed.


问:
Presto Nodes with too much load
I'm performing some queries over a tpch 100gb dataset on presto, I have 4 nodes, 1 master, 3 workers. When I try to run some queries, not all of them, I see on Presto web interface that the nodes die during the execution, resulting in query failure, the error is the following:

.facebook.presto.operator.PageTransportTimeoutException: Encountered too many errors talking to a worker node. The node may have crashed or been under too much load. This is probably a transient issue, so please retry your query in a few minutes.

I rebooted all nodes and presto service but the error remains, this problem doesn't exist if I run the same queries over a smaller dataset.Can someone provide some help on this problem?

Thanks

答: It might be an issue for configuration. For example, if the local maximum memory is not set appropriately and the query use too much heap memory, full GC might happen to cause such errors. I would suggest to ask in the Presto Google Group and describe someway to reproduce the issue :) </p>

Title: Presto Nodes with too much load


问:
Xamarin.Forms Android Local Notification Not Sending
I have followed the Xamarin walkthrough, and it's not working for me.
The code falls through this cleanly, but it never sends the notification.
It never shows up on my emulator or device.

I have no idea what is going on.

```<code>    public override void OnReceive(Context context, Intent intent)
    {

        string message = intent.GetStringExtra("message");
        string title = intent.GetStringExtra("title");
        int id = int.Parse(intent.GetStringExtra("id"));

        //Generate a notification with just short text and small icon
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                        .SetAutoCancel(true)                    // Dismiss from the notif. area when clicked
                        .SetContentTitle(title)      // Set its title
                        .SetContentText(message); // The message to display.

        NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
        notificationManager.Notify(id, builder.Build());
</code>```

Any help or links would be very helpful. I'm just completely lost; been working on this for about 14 hours now, and cannot find any help on the Google.

Answer to my inquiry: You must have an Icon set for notifications to be properly build and sent. Though, it won't send an error for not having one.

Short version: Needed to add

```<code> .SetSmallIcon(Resource.Drawable.icon);
</code>```

答:
Add an icon to notification. </p>

```<code>Notification.Builder builder = new Notification.Builder (this)
.SetContentTitle ("Title")
.SetContentText ("Message")
.SetSmallIcon (Resource.Drawable.ic_notification);

Notification notification = builder.Build();

NotificationManager notificationManager =
       GetSystemService (Context.NotificationService) as NotificationManager;

const int notificationId = 0;
notificationManager.Notify (notificationId, notification);
</code>```

Body:
I have followed the Xamarin walkthrough, and it's not working for me.
The code falls through this cleanly, but it never sends the notification.
It never shows up on my emulator or device.

I have no idea what is going on.

    public override void OnReceive(Context context, Intent intent)
    {

        string message = intent.GetStringExtra("message");
        string title = intent.GetStringExtra("title");
        int id = int.Parse(intent.GetStringExtra("id"));

        //Generate a notification with just short text and small icon
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                        .SetAutoCancel(true)                    // Dismiss from the notif. area when clicked
                        .SetContentTitle(title)      // Set its title
                        .SetContentText(message); // The message to display.

        NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
        notificationManager.Notify(id, builder.Build());

Any help or links would be very helpful. I'm just completely lost; been working on this for about 14 hours now, and cannot find any help on the Google.

Answer to my inquiry: You must have an Icon set for notifications to be properly build and sent. Though, it won't send an error for not having one.

Short version: Needed to add

 .SetSmallIcon(Resource.Drawable.icon);

Body:
Add an icon to notification.

Notification.Builder builder = new Notification.Builder (this)
.SetContentTitle ("Title")
.SetContentText ("Message")
.SetSmallIcon (Resource.Drawable.ic_notification);

Notification notification = builder.Build();

NotificationManager notificationManager =
       GetSystemService (Context.NotificationService) as NotificationManager;

const int notificationId = 0;
notificationManager.Notify (notificationId, notification);