问:
Symfony2 - Set label of ChoiceType
I have a select field (choiceType) in a form which is automatically filled (with all the line in another table).

I would like to set the label (only the label, not the content of the select)...

I managed to do that for a textType with changing :

```<code>$builder->add('note')
</code>```

to

```<code>$builder->add('note', 'text', array('label' => 'myNewLabel')
</code>```

but I can't do that with a choiceType because if I change

```<code>$buidler->add('column')
</code>```

to

```<code>$builder->add('column', 'choice', array('label' => 'myNewLabel')
</code>```

the select isn't filled...

答:
The solution is :</p>

```<code>$builder->add('column', null, array('label' => 'myNewLabel')
</code>```

Title: Symfony2 - Set label of ChoiceType

Body:
I have a select field (choiceType) in a form which is automatically filled (with all the line in another table).

I would like to set the label (only the label, not the content of the select)...

I managed to do that for a textType with changing :

$builder->add('note')

to

$builder->add('note', 'text', array('label' => 'myNewLabel')

but I can't do that with a choiceType because if I change

$buidler->add('column')

to

$builder->add('column', 'choice', array('label' => 'myNewLabel')

the select isn't filled...

Body:
The solution is :

$builder->add('column', null, array('label' => 'myNewLabel')


来源: stackexchange

问:
Failed to start LSB :Bring Up down Networking
I am new to CentOS 7 and I am configuring a static IP on CentOS 7, so I have edited the file /etc/sysconfig/network-scipts/ifcfg-eth0 as following:

```<code>TYPE=Ethernet
BOOTPROTO=none
Device=eth0
ONBBOOT=yes
IPADDR=192.168.4.196
NETMASK=255.255.255.0
GATEWAY=192.168.88.254
DNS1=8.8.8.8
USERCTL=no
</code>```

But when I issue the command

```<code>systemctl restart network
</code>```

I am getting the error

```<code>failed to start LSB :/Bring Up down Networking
</code>```

ip route show gives me no output.

I have applied the solution that stops NetworkManager with the same existing error.

I am able to configure a dynamic DHCP and get a dynamic IP address but not static one.

What can be possible solutions?

答:
You should change BOOTPROTO to static and move your DNS config to your /etc/resolv.conf file, for example: </p>

```<code>TYPE=Ethernet
BOOTPROTO=static
PHYSDEV=eth0
ONBBOOT=yes
IPADDR=192.168.4.196
NETMASK=255.255.255.0
GATEWAY=192.168.88.254
USERCTL=no
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to CentOS 7 and I am configuring a static IP on CentOS 7, so I have edited the file /etc/sysconfig/network-scipts/ifcfg-eth0 as following:

TYPE=Ethernet
BOOTPROTO=none
Device=eth0
ONBBOOT=yes
IPADDR=192.168.4.196
NETMASK=255.255.255.0
GATEWAY=192.168.88.254
DNS1=8.8.8.8
USERCTL=no

But when I issue the command

systemctl restart network

I am getting the error

failed to start LSB :/Bring Up down Networking

ip route show gives me no output.

I have applied the solution that stops NetworkManager with the same existing error.

I am able to configure a dynamic DHCP and get a dynamic IP address but not static one.

What can be possible solutions?

Body:
You should change BOOTPROTO to static and move your DNS config to your /etc/resolv.conf file, for example:

TYPE=Ethernet
BOOTPROTO=static
PHYSDEV=eth0
ONBBOOT=yes
IPADDR=192.168.4.196
NETMASK=255.255.255.0
GATEWAY=192.168.88.254
USERCTL=no

ContentLicense: CC BY-SA 3.0


问:
How to get date & month using date in mysql
I want to get date & month from date. example 2017-06-15 so I want date & month i.e. -06-15. Do u have any idea? Really appreciated.

From Below query I am getting month from date. but I want both date & month

```<code>SELECT MONTHNAME(`date`) AS month_name FROM table_name;
</code>```

答:
MySQL MONTH() returns the MONTH for the date within a range of 1 to 12
  ( January to December). It Returns 0 when MONTH part for the date is
  0.

```<code>SELECT MONTH('2009-05-18');
</code>```

MySQL DAY() returns the day of the month for a specified date. The day
  returned will be within the range of 1 to 31. If the given date is
  ‘0000-00-00’, the function will return 0. The DAYOFMONTH() is the
  synonym of DAY().

```<code>SELECT DAY('2008-05-15');
</code>```

Link : here

Body:
I want to get date & month from date. example 2017-06-15 so I want date & month i.e. -06-15. Do u have any idea? Really appreciated.

From Below query I am getting month from date. but I want both date & month

SELECT MONTHNAME(`date`) AS month_name FROM table_name;

Body:
MySQL MONTH() returns the MONTH for the date within a range of 1 to 12
  ( January to December). It Returns 0 when MONTH part for the date is
  0.

SELECT MONTH('2009-05-18');

MySQL DAY() returns the day of the month for a specified date. The day
  returned will be within the range of 1 to 31. If the given date is
  ‘0000-00-00’, the function will return 0. The DAYOFMONTH() is the
  synonym of DAY().

SELECT DAY('2008-05-15');

Link : here


问:
How to save result of sp_help TableName in User Tables
I want to save the result of SP_HELP [TableName] in UserTable. How can it be achieved. I know this information is available in information_schema.columns table.

The purpose of this tables is to use it if any changes are done to the table. It's achievable by using information_schema.columns but is it possible using sp_help.

答:
I don't think you can do this with just T-SQL, as INSERT...EXEC calls don't work with multiple result sets, and Microsoft don't plan on fixing it (https://connect.microsoft.com/SQLServer/feedback/details/470881/allow-more-than-one-resultset-to-be-stored-with-insert-into-exec-syntax)

So you will need to write some sort of script to run the SP and then write the result back into the database.  In which case, this answer will tell you what you need to know How do I return multiple result sets with SqlCommand?

Another option would be to reverse engineer sp_help and write a series of custom stored procedures that do each part of the process in turn. I.e. using information_schema.columns as you say!


问:
Automate data calculation in mysql tables
I have 2 tables Environment and room:

Environment
+-------+------------+--------------+----------------------+
| Envid | Agregate   | Availability | RoomNo               |
+-------+------------+--------------+----------------------+

Room
+--------+----------+-------------+------------------+
| RoomNo | Humidity | Temperature | Lighting         |
+--------+----------+-------------+------------------+
|  1     |    50    |  40         |  9               |
|  2     |    79    |  25         |  7               |
|  3     |    50    |  40         |  9               |
+--------+----------+-------------+------------------+```

Basically, Environment is an empty table.
What I need is to automate its calculation:

Take the values of Humidity, temperature and lighting from Room on EACH ROW,

sum them up together. This I have been able to do-

SELECT RoomNo,Humidity,Temperature,Lighting, Humidity+Temperature+Lighting AS Agregate FROM Room;

I just need to:

Store this new calculated "Agregate" in Environment table as "Agregate"

Populate it with the corresponding room number of the table Room (via foreign key).

EDIT:
5. Availability(boolean) of Room, should Update to 1 when Agregate > 100.

Can this be done directly in mysql? or in PHP ?

Note: RoomNo in Environment is a Foreign key
OF Primary key in Room

答:
Use the following triggers to populate the Environment table.

```<code>delimiter |
CREATE TRIGGER `after_update_Room`
  AFTER UPDATE ON `Room` FOR EACH ROW
    BEGIN
      UPDATE Environment
      SET Agregate = NEW.Humidity + NEW.Temperature + NEW.Lighting
      WHERE RoomNo = NEW.RoomNo;
    END;
|

delimiter |
CREATE TRIGGER `after_insert_Room`
    AFTER INSERT ON `Room` FOR EACH ROW
    BEGIN
       INSERT INTO Environment (`Agregate`, `RoomNo`)
       SELECT Humidity+Temperature+Lighting AS Agregate, RoomNo
       FROM Room
       WHERE RoomNo = NEW.RoomNo;
    END;
|
</code>```

Body:
I have 2 tables Environment and room:

Environment
+-------+------------+--------------+----------------------+
| Envid | Agregate   | Availability | RoomNo               |
+-------+------------+--------------+----------------------+

Room
+--------+----------+-------------+------------------+
| RoomNo | Humidity | Temperature | Lighting         |
+--------+----------+-------------+------------------+
|  1     |    50    |  40         |  9               |
|  2     |    79    |  25         |  7               |
|  3     |    50    |  40         |  9               |
+--------+----------+-------------+------------------+

Basically, Environment is an empty table.
What I need is to automate its calculation:

Take the values of Humidity, temperature and lighting from Room on EACH ROW,

sum them up together. This I have been able to do-

SELECT RoomNo,Humidity,Temperature,Lighting, Humidity+Temperature+Lighting AS Agregate FROM Room;

I just need to:

Store this new calculated "Agregate" in Environment table as "Agregate"

Populate it with the corresponding room number of the table Room (via foreign key).

EDIT:
5. Availability(boolean) of Room, should Update to 1 when Agregate > 100.

Can this be done directly in mysql? or in PHP ?

Note: RoomNo in Environment is a Foreign key
OF Primary key in Room

Body:
Use the following triggers to populate the Environment table.

delimiter |
CREATE TRIGGER `after_update_Room`
  AFTER UPDATE ON `Room` FOR EACH ROW
    BEGIN
      UPDATE Environment
      SET Agregate = NEW.Humidity + NEW.Temperature + NEW.Lighting
      WHERE RoomNo = NEW.RoomNo;
    END;
|

delimiter |
CREATE TRIGGER `after_insert_Room`
    AFTER INSERT ON `Room` FOR EACH ROW
    BEGIN
       INSERT INTO Environment (`Agregate`, `RoomNo`)
       SELECT Humidity+Temperature+Lighting AS Agregate, RoomNo
       FROM Room
       WHERE RoomNo = NEW.RoomNo;
    END;
|


问:
Delete or Select Only row with same id but have values for certain fields
I would like to select/delete data with different rows but with same id.

For Example.

```<code>ID  ColumnA
A    Honda
A    NULL
B    Yamaha
B    NULL
C    NULL
C    Merc
D    NULL
E    NULL
</code>```

Output:

```<code>ID  ColumnA
A    Honda
B    Yamaha
C    Merc
D    NULL
E    NULL
</code>```

First thing, I already google for the solutions, but no answers. Any help is greatly appreciated

答:
try this:

```<code>declare @tb table(ID varchar(50), ColumnA varchar(50))
insert into @tb
select 'A',   'Honda' union all
select 'A' ,   null union all
select 'B',    'Yamaha' union all
select 'B' ,   null union all
select 'C' ,   null union all
select 'C',    'Merc' union all
select 'D',    NULL union all
select  'E',    NULL

  select a.id,b.ColumnA from
(select count(1) cnt,ID from @tb  group by ID having count(1)>1 or count(1)=1) as a
 left join
 (select * from @tb) as b  on  a.ID = b.ID
 where b.columnA is not null and cnt>1 or cnt =1
</code>```

result:

```<code>A   Honda
B   Yamaha
C   Merc
D   NULL
E   NULL
</code>```

Body:
I would like to select/delete data with different rows but with same id.

For Example.

ID  ColumnA
A    Honda
A    NULL
B    Yamaha
B    NULL
C    NULL
C    Merc
D    NULL
E    NULL

Output:

ID  ColumnA
A    Honda
B    Yamaha
C    Merc
D    NULL
E    NULL

First thing, I already google for the solutions, but no answers. Any help is greatly appreciated

Body:
try this:

declare @tb table(ID varchar(50), ColumnA varchar(50))
insert into @tb
select 'A',   'Honda' union all
select 'A' ,   null union all
select 'B',    'Yamaha' union all
select 'B' ,   null union all
select 'C' ,   null union all
select 'C',    'Merc' union all
select 'D',    NULL union all
select  'E',    NULL

  select a.id,b.ColumnA from
(select count(1) cnt,ID from @tb  group by ID having count(1)>1 or count(1)=1) as a
 left join
 (select * from @tb) as b  on  a.ID = b.ID
 where b.columnA is not null and cnt>1 or cnt =1

result:

A   Honda
B   Yamaha
C   Merc
D   NULL
E   NULL


问:
How to use string array coming from webservice to INSPhotoViewable
I have an array of image url ["http://1.jpg", "http://2.jpg", "http://3.jpg", "http://4.jpg"] coming from webservice. Now I want to show that images with extention INSPhotoGallery INSPhotoGallery

This is workig fine:

```<code>    lazy var photos: [INSPhotoViewable] = {

    return [

        INSPhoto(imageURL: URL(string: "http://1.jpg"), thumbnailImage: UIImage(named: "thumbnailImage")!),

        INSPhoto(imageURL: URL(string: "http://2.jpg"), thumbnailImage: UIImage(named: "thumbnailImage")!),

        INSPhoto(imageURL: URL(string: "http://3.jpg"), thumbnailImageURL: URL(string: "thumbnailImage")),

        INSPhoto(imageURL: URL(string: "http://4.jpg"), thumbnailImageURL: URL(string: "thumbnailImage")),

        INSPhoto(imageURL: URL(string: "http://5.jpg"), thumbnailImageURL: URL(string: "thumbnailImage"))

    ]
}()
</code>```

But I am not able to return the images dynamically. What to do if I get 10 or 100 images from web service. How to display that, Please help me.

答:
You can use map like this</p>

```<code>let imgUrlArr = ["http://1.jpg", "http://2.jpg", "http://3.jpg", "http://4.jpg"]
var photos: [INSPhotoViewable] = imgUrlArr.map { INSPhoto(imageURL: URL(string: $0), thumbnailImage: UIImage(named: "thumbnailImage")!) }
</code>```

Body:
I have an array of image url ["http://1.jpg", "http://2.jpg", "http://3.jpg", "http://4.jpg"] coming from webservice. Now I want to show that images with extention INSPhotoGallery INSPhotoGallery

This is workig fine:

    lazy var photos: [INSPhotoViewable] = {

    return [

        INSPhoto(imageURL: URL(string: "http://1.jpg"), thumbnailImage: UIImage(named: "thumbnailImage")!),

        INSPhoto(imageURL: URL(string: "http://2.jpg"), thumbnailImage: UIImage(named: "thumbnailImage")!),

        INSPhoto(imageURL: URL(string: "http://3.jpg"), thumbnailImageURL: URL(string: "thumbnailImage")),

        INSPhoto(imageURL: URL(string: "http://4.jpg"), thumbnailImageURL: URL(string: "thumbnailImage")),

        INSPhoto(imageURL: URL(string: "http://5.jpg"), thumbnailImageURL: URL(string: "thumbnailImage"))

    ]
}()

But I am not able to return the images dynamically. What to do if I get 10 or 100 images from web service. How to display that, Please help me.

Body:
You can use map like this

let imgUrlArr = ["http://1.jpg", "http://2.jpg", "http://3.jpg", "http://4.jpg"]
var photos: [INSPhotoViewable] = imgUrlArr.map { INSPhoto(imageURL: URL(string: $0), thumbnailImage: UIImage(named: "thumbnailImage")!) }


问:
Git pull and specify directory?
i would like to run a git pull and specify the directory. some say using --git-dir and --work-tree should work but such as

```<code>git --git-dir=/var/www/.git --work-tree=/var/www pull
</code>```

put this returns a "cannot be used without a working tree". The only time i can get this to work is if i use ".", ".." or any directory above the current directory

this post suggests maybe a bug?
git pull while not in a git directory

in the end i need to run a sudo git pull in a single line. i welcome any work arounds. thanks

答:
On Windows in MINGW64:

```<code>git -C "C:\Trunk190117\crewcontrol-source" pull
</code>```

or

```<code>git -C /c/Trunk190117/crewcontrol-source pull
</code>```

Title: Git pull and specify directory?

Body:
i would like to run a git pull and specify the directory. some say using --git-dir and --work-tree should work but such as

git --git-dir=/var/www/.git --work-tree=/var/www pull

put this returns a "cannot be used without a working tree". The only time i can get this to work is if i use ".", ".." or any directory above the current directory

this post suggests maybe a bug?
git pull while not in a git directory

in the end i need to run a sudo git pull in a single line. i welcome any work arounds. thanks

Body:
On Windows in MINGW64:

git -C "C:\Trunk190117\crewcontrol-source" pull

or

git -C /c/Trunk190117/crewcontrol-source pull


问:
Broadcast Receiver suggestion
My current project method only works to connect sync with my remote db when mobile data is turned on. How do I implement the same this time by using wifi? What code will I add to make it work on Wifi and Mobile data.

Here is my broadcast receiver.

```<code>public class NetworkMonitor extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
        if (checkNetworkConnection(context))
        {
            final DbHelper dbHelper = new DbHelper(context);
            final SQLiteDatabase database = dbHelper.getWritableDatabase();

           Cursor cursor = dbHelper.readFromLocalDatabase(database);

            while (cursor.moveToNext())
            {
                int sync_status = cursor.getInt(cursor.getColumnIndex(DBContract.SYNC_STATUS));
                if (sync_status == DBContract.SYNC_STATUS_FAILED)
                {
                    final String Name = cursor.getString(cursor.getColumnIndex(DBContract.NAME));
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, DBContract.SERVER_URL,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String Response = jsonObject.getString("response");
                                        if (Response.equals("OK"))
                                        {
                                            dbHelper.updateLocalDatabase(Name,DBContract.SYNC_STATUS_OK,database);
                                            context.sendBroadcast(new Intent(DBContract.UI_UPDATE_BROADCAST));
                                        }

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    })
                    {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> params = new HashMap<>();
                            params.put("name",Name);
                            return params;
                        }
                    }
                            ;
                    MySingleton.getInstance(context).addToRequestQue(stringRequest);

                }
            }

        }
    }
`

    public boolean checkNetworkConnection(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo!= null && networkInfo.isConnected());
    }
</code>```

What I'm trying to do is when mobile data is turned off and a record is inserted it is saved to local sqlite. And when i turn on mobile data it automatically uploads that record to the remote mysql db. But when I do the same on WiFi. When i turn it off and turn it on it does not automatically send the record to the remote mysql db.

答: ConnectivityManager will basically give the network connection status regardless mobile data or wifi.So your code should work for both conditions. </p>

Title: Broadcast Receiver suggestion

Body:
My current project method only works to connect sync with my remote db when mobile data is turned on. How do I implement the same this time by using wifi? What code will I add to make it work on Wifi and Mobile data.

Here is my broadcast receiver.

public class NetworkMonitor extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
        if (checkNetworkConnection(context))
        {
            final DbHelper dbHelper = new DbHelper(context);
            final SQLiteDatabase database = dbHelper.getWritableDatabase();

           Cursor cursor = dbHelper.readFromLocalDatabase(database);

            while (cursor.moveToNext())
            {
                int sync_status = cursor.getInt(cursor.getColumnIndex(DBContract.SYNC_STATUS));
                if (sync_status == DBContract.SYNC_STATUS_FAILED)
                {
                    final String Name = cursor.getString(cursor.getColumnIndex(DBContract.NAME));
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, DBContract.SERVER_URL,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String Response = jsonObject.getString("response");
                                        if (Response.equals("OK"))
                                        {
                                            dbHelper.updateLocalDatabase(Name,DBContract.SYNC_STATUS_OK,database);
                                            context.sendBroadcast(new Intent(DBContract.UI_UPDATE_BROADCAST));
                                        }

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    })
                    {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> params = new HashMap<>();
                            params.put("name",Name);
                            return params;
                        }
                    }
                            ;
                    MySingleton.getInstance(context).addToRequestQue(stringRequest);

                }
            }

        }
    }
`

    public boolean checkNetworkConnection(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo!= null && networkInfo.isConnected());
    }

What I'm trying to do is when mobile data is turned off and a record is inserted it is saved to local sqlite. And when i turn on mobile data it automatically uploads that record to the remote mysql db. But when I do the same on WiFi. When i turn it off and turn it on it does not automatically send the record to the remote mysql db.


问:
Mockito: replace method that throws an exception
I've this interface:

```<code>public interface IEnd<T> {
    T get() throws FluentApiException;
}

public interface IFluentEntityCollectionRelation<ID, T> extends IEnd<Iterable<T>>
</code>```

I'm trying to mock this interface in order to return an concrete empty Iterable<T> object when it's called:

```<code>IFluentEntityCollectionRelation<String, Plan> plans = any();
when(plans.get()).thenReturn(new ArrayList<Plan>());
</code>```

Nevertheless, I'm getting a compilation error:

Unhandled exception type FluentApiException

since IEnd<>.get() throws an FluentApiException exception never catched.

Any ideas?

答:
Simple: you should only need to change your test code like

```<code>@Test
public void testWhatever() throws FluentApiException
</code>```

Of course, the testcase should never throw that exception. If it gets thrown, it will lead to a test case failure.

In other words: you simply don't care. Make the compiler happy by adding this checked exception to the test method(s) that invoke get().

Body:
I've this interface:

public interface IEnd<T> {
    T get() throws FluentApiException;
}

public interface IFluentEntityCollectionRelation<ID, T> extends IEnd<Iterable<T>>

I'm trying to mock this interface in order to return an concrete empty Iterable<T> object when it's called:

IFluentEntityCollectionRelation<String, Plan> plans = any();
when(plans.get()).thenReturn(new ArrayList<Plan>());

Nevertheless, I'm getting a compilation error:

Unhandled exception type FluentApiException

since IEnd<>.get() throws an FluentApiException exception never catched.

Any ideas?

Body:
Simple: you should only need to change your test code like

@Test
public void testWhatever() throws FluentApiException

Of course, the testcase should never throw that exception. If it gets thrown, it will lead to a test case failure.

In other words: you simply don't care. Make the compiler happy by adding this checked exception to the test method(s) that invoke get().


问:
Django not inserting data into database when I execute subprocess.Popen
I am using django and inserting data into database and downloading images. When I call the function it works fine but it blocks the main thread. To execute the process in the background  I'm using :

views.py:

class get_all_data(View):
    def post(self, request, *args, **kwargs):

```<code>subprocess.Popen(
            ['python get_images.py --data=data'],
            close_fds=True,
            shell = True
        )
</code>```

But when I call:

python get_images.py(data="data")

it works fine but it runs on the main thread.

How can I fix it ? BTW I'm using python 2.7.

Note: Please don't suggest Celery . I'm looking for something which runs the task async or any other alternative.

I'm using the following code to insert into my db:

get_images.py:

```<code>from models import Test

        def get_image_all():

            #get data from server
            insert_to_Test(data="data")

        if __name__ == "__main__":
            import argparse
            from  .models import Test
            import django
            django.setup()

            parser = argparse.ArgumentParser()
            parser.add_argument('--from_date')
            parser.add_argument('--data')
            parser.add_argument('--execute', type=bool, default=False)
            args = parser.parse_args()
            print "args", args
            get_image_all(**vars(args))
</code>```

When I call subprocess.Popen then it does not insert data into my db but If I execute it by call the function then it inserts the data to db. Why does that happen?

答:
Shouldn't it be</p>

```<code>subprocess.Popen(
            ['python get_images.py(data=data)'],
            close_fds=True,
            shell = True
        )
</code>```

Body:
I am using django and inserting data into database and downloading images. When I call the function it works fine but it blocks the main thread. To execute the process in the background  I'm using :

views.py:

class get_all_data(View):
    def post(self, request, *args, **kwargs):

subprocess.Popen(
            ['python get_images.py --data=data'],
            close_fds=True,
            shell = True
        )

But when I call:

python get_images.py(data="data")

it works fine but it runs on the main thread.

How can I fix it ? BTW I'm using python 2.7.

Note: Please don't suggest Celery . I'm looking for something which runs the task async or any other alternative.

I'm using the following code to insert into my db:

get_images.py:

from models import Test

        def get_image_all():

            #get data from server
            insert_to_Test(data="data")

        if __name__ == "__main__":
            import argparse
            from  .models import Test
            import django
            django.setup()

            parser = argparse.ArgumentParser()
            parser.add_argument('--from_date')
            parser.add_argument('--data')
            parser.add_argument('--execute', type=bool, default=False)
            args = parser.parse_args()
            print "args", args
            get_image_all(**vars(args))

When I call subprocess.Popen then it does not insert data into my db but If I execute it by call the function then it inserts the data to db. Why does that happen?

Body:
Shouldn't it be

subprocess.Popen(
            ['python get_images.py(data=data)'],
            close_fds=True,
            shell = True
        )


Title: How to get date & month using date in mysql

Body: select month('2017-06-15'),DAY('2017-06-15')


问:
How to show the constant for the property instead of value
Hello
I am working in VB.Net 2010 framework 2.0.
Suppose I declare a property :

```<code>Dim NewColor As Color = Color.FromArgb(150, 145, 145)

Private _myColor As Color = NewColor
Public Property MyColor() As Color
    Get
        Return _myColor
    End Get
    Set(ByVal value As Color)
        _myColor = value
    End Set
End Property
</code>```

In the form designer, the property "MyColor" will be seen the value as 150, 145, 145. I want to see this value as "NewColor" in form designer.
This is the same like ControlDark, ActiveBorder etc. system colors. I want that instead of the color value, designer should show the variable name.
The .Net framework also use the above implementation for System Colors and same i want to do.

Thanks for any reply in advance.

答:
This is possible, but not easy.

You should define your own type, probably hide the current property in the browser, with a <Browsable(False)> attribute, and create a shadow property that is of your own type. This type should know when it is "pointing to" a variable, or has a color itself.

On the new type you should override ToString, to return what you want to display. And create your own Editor. Look at EditorAttribute for more information.

You can create a dropdown, like Color has, with an extra tab that lists your variables.

If you do not want to create the extra properties (it is bad OO), you can also define a TypeConverter on the class, and specify each property and how to behave yourself.

BTW: The Color structure stores a KnownColor value (Color.Red or SystemColor.WindowText) or the RGB values. This way it knows that it points to a known color. Your structure should also know if it points to a variable (and what variable) or is a System.Color.

ContentLicense: CC BY-SA 2.5

Body:
Hello
I am working in VB.Net 2010 framework 2.0.
Suppose I declare a property :

Dim NewColor As Color = Color.FromArgb(150, 145, 145)

Private _myColor As Color = NewColor
Public Property MyColor() As Color
    Get
        Return _myColor
    End Get
    Set(ByVal value As Color)
        _myColor = value
    End Set
End Property

In the form designer, the property "MyColor" will be seen the value as 150, 145, 145. I want to see this value as "NewColor" in form designer.
This is the same like ControlDark, ActiveBorder etc. system colors. I want that instead of the color value, designer should show the variable name.
The .Net framework also use the above implementation for System Colors and same i want to do.

Thanks for any reply in advance.


答:
```<code>drop table if exists dbo.Motorcycle;

create table dbo.Motorcycle (
     ID char(1)
     , ColumnA varchar(100)
);

insert into dbo.Motorcycle (ID, ColumnA)
values ('A', 'Honda'), ('A', null)
, ('B', 'Yamaha'), ('B', null)
, ('C', null), ('C', 'Merc')
, ('D', null)
, ('E', null);

select
t.ID, t.ColumnA
from (
select
*
, ROW_NUMBER() over (partition by m.ID order by m.ColumnA desc) as RBr
from dbo.Motorcycle m
) t
where t.RBr = 1
</code>```

Title: Delete or Select Only row with same id but have values for certain fields


问:
Cannot be root from a tmux session on a remote machine
I can become root when I am logged into a gateway node, but not when I have my tmux session running. I can ssh into other machines and become root but the not the one running the tmux. This issue seems to be isolated to our gateway node in production.

In tmux

```<code>user@gateway:~$ sudo su
[sudo] password for user:
user is not in the sudoers file.  This incident will be reported.
</code>```

No tmux

```<code>user@gateway:~$ sudo su
[sudo] password for user:
root@gateway:/home/user#
</code>```

答: I had unattached tmux sessions that needed to be closed.</p>

Body:
I can become root when I am logged into a gateway node, but not when I have my tmux session running. I can ssh into other machines and become root but the not the one running the tmux. This issue seems to be isolated to our gateway node in production.

In tmux

user@gateway:~$ sudo su
[sudo] password for user:
user is not in the sudoers file.  This incident will be reported.

No tmux

user@gateway:~$ sudo su
[sudo] password for user:
root@gateway:/home/user#


问:
matching two points with minimum distance
I'm working on this problem:

There is a 3d binary matrix which i cluster with the kmeans algorithm in matlab;

After that i get a value C which contains the coordinates of the centroids of these clusters in an array, for example:

```<code> C=   30.0000   15.0000   48.5000

      100.2676   57.7382   80.7489

      57.5000   85.0000   35.0000

      27.5000   50.0000   69.5000
</code>```

(4 centroids: first one with coordinates (30,15,48,5))
where the rows represent the x,y and z coordinate of each centroid.

When I cluster another matrix I get a second value which also contains the coordinates of the second centroids.
now i have to match the centroids from first and second clustering which have minimum distance and create an output where i can see which centroids belong together.

I have tried it with pdist(X) and i get the distances pairwise of the coordinates but i can not match them together..

How to solve this, any idea?

答:
You should use pdist2 instead of pdist.

pdist2 calculates the pairwise distance between two sets of observations, whereas pdist calculates the pairwise distance between all observations in a single matrix.

The documentation of pdist2 specifies the correct syntax and meaning of the output distance matrix:

D = pdist2(X,Y) returns a matrix D containing the Euclidean distances
  between each pair of observations in the mx-by-n data matrix X and
  my-by-n data matrix Y. Rows of X and Y correspond to observations,
  columns correspond to variables. D is an mx-by-my matrix, with the
  (i,j) entry equal to distance between observation i in X and
  observation j in Y.

So, you should use this as follows:

```<code>D = pdist2(C1, C2);
</code>```

Note 1: If you have find a function which almost does what you want (i.e. pdist) it is often useful to look into the See Also section of the manual and check if one of these may be helpful.

Body:
I'm working on this problem:

There is a 3d binary matrix which i cluster with the kmeans algorithm in matlab;

After that i get a value C which contains the coordinates of the centroids of these clusters in an array, for example:

 C=   30.0000   15.0000   48.5000

      100.2676   57.7382   80.7489

      57.5000   85.0000   35.0000

      27.5000   50.0000   69.5000

(4 centroids: first one with coordinates (30,15,48,5))
where the rows represent the x,y and z coordinate of each centroid.

When I cluster another matrix I get a second value which also contains the coordinates of the second centroids.
now i have to match the centroids from first and second clustering which have minimum distance and create an output where i can see which centroids belong together.

I have tried it with pdist(X) and i get the distances pairwise of the coordinates but i can not match them together..

How to solve this, any idea?

Body:
You should use pdist2 instead of pdist.

pdist2 calculates the pairwise distance between two sets of observations, whereas pdist calculates the pairwise distance between all observations in a single matrix.

The documentation of pdist2 specifies the correct syntax and meaning of the output distance matrix:

D = pdist2(X,Y) returns a matrix D containing the Euclidean distances
  between each pair of observations in the mx-by-n data matrix X and
  my-by-n data matrix Y. Rows of X and Y correspond to observations,
  columns correspond to variables. D is an mx-by-my matrix, with the
  (i,j) entry equal to distance between observation i in X and
  observation j in Y.

So, you should use this as follows:

D = pdist2(C1, C2);

Note 1: If you have find a function which almost does what you want (i.e. pdist) it is often useful to look into the See Also section of the manual and check if one of these may be helpful.


问:
Creating a Linked List of Odd Numbers (C)
I'm fairly new to coding and am taking a course at school that teaches the C programming language. We are learning about data structures in C and have been given an assignment which requires us to create a linked list with the odd integers from 1 to 10, and also print that list. However, the code that I have written seems to be having some problems. Here it is:

```<code>#include <stdio.h>
#include <stdlib.h>

struct listNode {
    int value;
    struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

void createList(ListNodePtr *sPtr);
void printList(ListNodePtr currentPtr);

int main(void) {
    ListNodePtr list1Ptr;

    list1Ptr = NULL;

    list1Ptr->value = 1;
    createList(&list1Ptr);
    printf("List 1 is: ");
    printList(list1Ptr);

    printf("End of run.\n");

    return 0;
}

void createList(ListNodePtr *sPtr) {
    ListNodePtr previousPtr;
    ListNodePtr newPtr;

    newPtr = malloc(sizeof(ListNodePtr));

    if (newPtr != NULL) {
        newPtr = *sPtr;

        previousPtr = NULL;

        while (((*sPtr)->value) <= 10) {
            previousPtr = *sPtr;
            *sPtr = (*sPtr)->nextPtr;
            (*sPtr)->value = previousPtr->value + 2;
        }
    }
    else {
        printf("No memory available.\n");
    }
}

int isEmpty(ListNodePtr sPtr) {
    return sPtr == NULL;
}

void printList(ListNodePtr currentPtr) {
    if (currentPtr == NULL) {
        printf("List is empty.\n\n");
    }
    else {
        while (currentPtr != NULL) {
            printf("%d ", currentPtr->value);
            currentPtr = currentPtr->nextPtr;
        }
        printf("*\n");
    }
}
</code>```

The desired output it: [List 1 is: 1 3 5 7 9 *]
The environment I use keeps telling me that there are either "unhandled exceptions" (I'm not so sure what that means) or just ceases running midway. Any ideas of how I might be able to reach the desired outcome?

Any other tips and words of advice are greatly appreciated. Thank you!

答:
There are few errors in logic as well as use of pointers. May be following code be useful. Comment if any clarification is required:

```<code> #include <stdio.h>
 #include <stdlib.h>
 #define START_COUNT 1
 #define INCREMENT_COUNT 2
 #define END_COUNT 10

 struct listNode {
     int value;
     struct listNode *nextPtr;
 };

 typedef struct listNode ListNode;
 typedef ListNode* ListNodePtr;

 ListNodePtr createList(ListNodePtr sPtr, int val);
 void printList(ListNodePtr currentPtr);

 int main(void) {
     ListNodePtr list1Ptr;
     int counter = END_COUNT;

     list1Ptr = NULL;
     do
     {
         list1Ptr = createList(list1Ptr, START_COUNT);
         counter -= INCREMENT_COUNT;
     }while(counter>0);
     printf("List 1 is: ");
     printList(list1Ptr);

     printf("End of run.\n");

     return 0;
 }

 ListNodePtr createList(ListNodePtr sPtr, int val) {
     ListNodePtr previousPtr;
     ListNodePtr newPtr;
     newPtr = malloc(sizeof(ListNode));

     if (newPtr != NULL) {

         //Make 'newPtr' very first node
         newPtr->nextPtr =sPtr;
         newPtr->value = val;

         sPtr = newPtr;
         //(sPtr != NULL) is to check for [1] and (sPtr->nextPtr != NULL) for [2]
         while ((sPtr != NULL) && (sPtr->nextPtr != NULL) && (sPtr->value <= END_COUNT)) {
             previousPtr = sPtr; //[1]
             sPtr = sPtr->nextPtr; //[2]
             sPtr->value = previousPtr->value + INCREMENT_COUNT; //[1] and [2]
         }
     }
     else {
         printf("No memory available.\n");
     }

     //Set to the very first Node
     return newPtr;
 }

 int isEmpty(ListNodePtr sPtr) {
     return sPtr == NULL;
 }

 void printList(ListNodePtr currentPtr) {
     if (currentPtr == NULL) {
         printf("List is empty.\n\n");
     }
     else {
         while (currentPtr != NULL) {
             printf("%d ", currentPtr->value);
             currentPtr = currentPtr->nextPtr;
         }
         printf("*\n");
     }
 }
</code>```

Body:
I'm fairly new to coding and am taking a course at school that teaches the C programming language. We are learning about data structures in C and have been given an assignment which requires us to create a linked list with the odd integers from 1 to 10, and also print that list. However, the code that I have written seems to be having some problems. Here it is:

#include <stdio.h>
#include <stdlib.h>

struct listNode {
    int value;
    struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

void createList(ListNodePtr *sPtr);
void printList(ListNodePtr currentPtr);

int main(void) {
    ListNodePtr list1Ptr;

    list1Ptr = NULL;

    list1Ptr->value = 1;
    createList(&list1Ptr);
    printf("List 1 is: ");
    printList(list1Ptr);

    printf("End of run.\n");

    return 0;
}

void createList(ListNodePtr *sPtr) {
    ListNodePtr previousPtr;
    ListNodePtr newPtr;

    newPtr = malloc(sizeof(ListNodePtr));

    if (newPtr != NULL) {
        newPtr = *sPtr;

        previousPtr = NULL;

        while (((*sPtr)->value) <= 10) {
            previousPtr = *sPtr;
            *sPtr = (*sPtr)->nextPtr;
            (*sPtr)->value = previousPtr->value + 2;
        }
    }
    else {
        printf("No memory available.\n");
    }
}

int isEmpty(ListNodePtr sPtr) {
    return sPtr == NULL;
}

void printList(ListNodePtr currentPtr) {
    if (currentPtr == NULL) {
        printf("List is empty.\n\n");
    }
    else {
        while (currentPtr != NULL) {
            printf("%d ", currentPtr->value);
            currentPtr = currentPtr->nextPtr;
        }
        printf("*\n");
    }
}

The desired output it: [List 1 is: 1 3 5 7 9 *]
The environment I use keeps telling me that there are either "unhandled exceptions" (I'm not so sure what that means) or just ceases running midway. Any ideas of how I might be able to reach the desired outcome?

Any other tips and words of advice are greatly appreciated. Thank you!

Body:
There are few errors in logic as well as use of pointers. May be following code be useful. Comment if any clarification is required:

 #include <stdio.h>
 #include <stdlib.h>
 #define START_COUNT 1
 #define INCREMENT_COUNT 2
 #define END_COUNT 10

 struct listNode {
     int value;
     struct listNode *nextPtr;
 };

 typedef struct listNode ListNode;
 typedef ListNode* ListNodePtr;

 ListNodePtr createList(ListNodePtr sPtr, int val);
 void printList(ListNodePtr currentPtr);

 int main(void) {
     ListNodePtr list1Ptr;
     int counter = END_COUNT;

     list1Ptr = NULL;
     do
     {
         list1Ptr = createList(list1Ptr, START_COUNT);
         counter -= INCREMENT_COUNT;
     }while(counter>0);
     printf("List 1 is: ");
     printList(list1Ptr);

     printf("End of run.\n");

     return 0;
 }

 ListNodePtr createList(ListNodePtr sPtr, int val) {
     ListNodePtr previousPtr;
     ListNodePtr newPtr;
     newPtr = malloc(sizeof(ListNode));

     if (newPtr != NULL) {

         //Make 'newPtr' very first node
         newPtr->nextPtr =sPtr;
         newPtr->value = val;

         sPtr = newPtr;
         //(sPtr != NULL) is to check for [1] and (sPtr->nextPtr != NULL) for [2]
         while ((sPtr != NULL) && (sPtr->nextPtr != NULL) && (sPtr->value <= END_COUNT)) {
             previousPtr = sPtr; //[1]
             sPtr = sPtr->nextPtr; //[2]
             sPtr->value = previousPtr->value + INCREMENT_COUNT; //[1] and [2]
         }
     }
     else {
         printf("No memory available.\n");
     }

     //Set to the very first Node
     return newPtr;
 }

 int isEmpty(ListNodePtr sPtr) {
     return sPtr == NULL;
 }

 void printList(ListNodePtr currentPtr) {
     if (currentPtr == NULL) {
         printf("List is empty.\n\n");
     }
     else {
         while (currentPtr != NULL) {
             printf("%d ", currentPtr->value);
             currentPtr = currentPtr->nextPtr;
         }
         printf("*\n");
     }
 }


问:
Destroying Sprites in and around the Collided Sprite
I need help in destroying the sprites which are in and around the collided sprites ie in a radius of 2.5 cms all sprites should be destroyed. Idea here is i will be shooting a projectile from bottom to the objects falling from the top. Once collision happens all the sprites around that radius also should be destroyed. Like a Bomb Effect. I have used box2d for collision ie contact listener. How to go about doing that?

Please Suggest:-)

Regards,

Karthik

答:
Hold an array of your sprites, or if you are using a batchNode you can do that.

When the collision happens, go through your sprites. Check the distance with their position and the explosion center and kill them if they are in range.

e.g.

```<code>CCSprite *sprite;
for (sprite in [batchNode descendants]) {

   if ([sprite isInRangeOf:[explosionSprite position]]) {
       [sprite yourRemovalMethod];
   }

}
</code>```

the method 'isInRangeOf:' would be within your sprite subclass

Something like..

```<code>-(BOOL) isInRangeOf:(CGPoint)explosionCenter {

 //Use pythagoras theorem to work out the distance between [sprite position] and [explosionCenter]

    CGFloat dx = explosionCenter.x - [self position].x;
    CGFloat dy = explosionCenter.y - [self position].y;
    float distance = sqrt(dx*dx + dy*dy );

 // If your distance is less than or equal to your 'death radius' return YES, else No.
    if (distance <= 25) {
    return TRUE;
    } else {
    return FALSE;
    }

}
</code>```

Hope that helps.

Body:
Hold an array of your sprites, or if you are using a batchNode you can do that.

When the collision happens, go through your sprites. Check the distance with their position and the explosion center and kill them if they are in range.

e.g.

CCSprite *sprite;
for (sprite in [batchNode descendants]) {

   if ([sprite isInRangeOf:[explosionSprite position]]) {
       [sprite yourRemovalMethod];
   }

}

the method 'isInRangeOf:' would be within your sprite subclass

Something like..

-(BOOL) isInRangeOf:(CGPoint)explosionCenter {

 //Use pythagoras theorem to work out the distance between [sprite position] and [explosionCenter]

    CGFloat dx = explosionCenter.x - [self position].x;
    CGFloat dy = explosionCenter.y - [self position].y;
    float distance = sqrt(dx*dx + dy*dy );

 // If your distance is less than or equal to your 'death radius' return YES, else No.
    if (distance <= 25) {
    return TRUE;
    } else {
    return FALSE;
    }

}

Hope that helps.


问:
Import Maven (or Gradle) project to Eclipse in command line
I would to prepare virtual machine with Eclipse. I would like the Eclipse has pre-imported my Maven project.
Is is possible to execute some script which imports the project to the eclipse, in similar way I can pre-install plugin?

I'm not interested in mvn eclipse:eclipse. I want import with the same process like clicking mouse

PS. Similar question for Gradle.

答:
You may want to begin with converting your MVN project to a gradle one. Here is how

Once your build.gradle is created, open it and add this line:

```<code>apply plugin: 'eclipse'
</code>```

Go back to the command prompt and run gradle eclipse

Now the build creates a project file which your Eclipse IDE acan import and work on it as if it were originally created in Eclipse.

For more detail on configuring the Eclipse Plugin, see this link

Note that the assumption here is that you have ann your PATHS set correctly.

Body:
You may want to begin with converting your MVN project to a gradle one. Here is how

Once your build.gradle is created, open it and add this line:

apply plugin: 'eclipse'

Go back to the command prompt and run gradle eclipse

Now the build creates a project file which your Eclipse IDE acan import and work on it as if it were originally created in Eclipse.

For more detail on configuring the Eclipse Plugin, see this link

Note that the assumption here is that you have ann your PATHS set correctly.


问:
Repository Pattern - Validating Object and Return Message
I'm working on a website, and just trying to get my head around the general structure. I have a database in the background that I'm accessing using the "Repository Pattern". I have the below code in my UserRepository class:

```<code>public bool IsValid(User user)
{
  if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
  {
    Message = "Email address already in use";
    return false;
  }

  return true;
}
</code>```

And that is implemented here

```<code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(User user)
{
  if (ModelState.IsValid)
  {
    var context = new Context("DatabaseContext");
    var userRepo = new UserRepository(context);

    if (userRepo.IsValid(user))
    {
      userRepo.Add(user);
      // return to different view
    }
    else
    {
      // display userRepo.Message on page
      return View(user);
    }
  }

  return View(user);
}
</code>```

My problem is I don't think I'm going around the "message" bit correctly, but I can't find anything online to help me out (specifically around repository). I think I should be changing the return type of IsValid to something like a result (as I've seen with dialog boxes), but again, I'm not sure.

Any help would be much appreciated.

Thanks.

答:
I agree with what you mentioned in question. Returning custom class will be better approach IMO.

```<code>public ValidationResult IsValid(User user)
{
  ValidationResult validationResult = new ValidationResult(true, "");
  if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
  {
    validationResult.Status = false;
    validationResult.Message = "Email address already in use";
    return validationResult;
  }

  return validationResult;
}
</code>```

This way, Status and Message give you all info needed. Check the status first. If it is false, check message for exact details.

Body:
I'm working on a website, and just trying to get my head around the general structure. I have a database in the background that I'm accessing using the "Repository Pattern". I have the below code in my UserRepository class:

public bool IsValid(User user)
{
  if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
  {
    Message = "Email address already in use";
    return false;
  }

  return true;
}

And that is implemented here

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(User user)
{
  if (ModelState.IsValid)
  {
    var context = new Context("DatabaseContext");
    var userRepo = new UserRepository(context);

    if (userRepo.IsValid(user))
    {
      userRepo.Add(user);
      // return to different view
    }
    else
    {
      // display userRepo.Message on page
      return View(user);
    }
  }

  return View(user);
}

My problem is I don't think I'm going around the "message" bit correctly, but I can't find anything online to help me out (specifically around repository). I think I should be changing the return type of IsValid to something like a result (as I've seen with dialog boxes), but again, I'm not sure.

Any help would be much appreciated.

Thanks.

Body:
I agree with what you mentioned in question. Returning custom class will be better approach IMO.

public ValidationResult IsValid(User user)
{
  ValidationResult validationResult = new ValidationResult(true, "");
  if (_context.Users.Any(c => c.EmailAddress == user.EmailAddress))
  {
    validationResult.Status = false;
    validationResult.Message = "Email address already in use";
    return validationResult;
  }

  return validationResult;
}

This way, Status and Message give you all info needed. Check the status first. If it is false, check message for exact details.


问:
The case of the disappearing ActiveRecord attribute
Following the instructions in https://stackoverflow.com/a/24496452/102675 I wound up with the following:

```<code>namespace :db do
  desc 'Drop, create, migrate, seed and populate sample data'
  task seed_sample_data: [:drop, :create, :migrate, :seed, :populate_sample_data] do
    puts 'Sample Data Populated. Ready to go!'
  end

  desc 'Populate the database with sample data'
  task populate_sample_data: :environment do
    puts Inspector.column_names.include?('how_to_fix')
    # create my sample data
  end
end
</code>```

As you would expect, I get true if I run bundle exec rake db:populate_sample_data

BUT if I run bundle exec rake db:seed_sample_data I get all the migration output and then false. In other words I can't see the Inspector attribute how_to_fix even though it definitely exists as proved by the other rake run. Where did my attribute go?

答:
My guess is that this is a "caching" problem. Can you try the following?

```<code>task populate_sample_data: :environment do
  Inspector.reset_column_information
  # ...
end
</code>```

P.S. We used to have a similar problem working with different databases having the exact same schema (only except some columns here and there)

Body:
Following the instructions in https://stackoverflow.com/a/24496452/102675 I wound up with the following:

namespace :db do
  desc 'Drop, create, migrate, seed and populate sample data'
  task seed_sample_data: [:drop, :create, :migrate, :seed, :populate_sample_data] do
    puts 'Sample Data Populated. Ready to go!'
  end

  desc 'Populate the database with sample data'
  task populate_sample_data: :environment do
    puts Inspector.column_names.include?('how_to_fix')
    # create my sample data
  end
end

As you would expect, I get true if I run bundle exec rake db:populate_sample_data

BUT if I run bundle exec rake db:seed_sample_data I get all the migration output and then false. In other words I can't see the Inspector attribute how_to_fix even though it definitely exists as proved by the other rake run. Where did my attribute go?

Body:
My guess is that this is a "caching" problem. Can you try the following?

task populate_sample_data: :environment do
  Inspector.reset_column_information
  # ...
end

P.S. We used to have a similar problem working with different databases having the exact same schema (only except some columns here and there)


问:
How to pass an integer to a parameter through HashMap?
Am new to java and have a query.Please suggest me a solution :

Am doing API level testing and need to pass the request body parameters of a service like below :

答: I would suggest you create some kind of a class which will represent your map key/values so it will be easier to work with it for other developers.</p>


问:
using groupby attribute in pandas
I have a DataFrame with 3 columns (A,B,C) and a large number of rows. There are different types of elements in each of these columns: A1,A2... B1,B2... and C1, C2... respectively.

I want to find the number of times a particular combination (say (A1,B2,C2)) occurs in a row. Then I want to generate a (summary) list of all combinations whose frequency-counts exceed a fixed threshold. Example: combinations number of counts (A1,B2,C2) 5 (A2,B2,C2) 7 .... if the fixed value is 6.

I am new to pandas and numpy. Can this be done efficiently using pandas, and if so how?

答:
Using only pandas, one way could be to use DataFrame.groupby():

```<code>counts = dict()

for group in df.groupby(['It', 'Cc', 'Ct']):
    print(group)
    counts[group[0]] = len(group[1])
</code>```

A faster way is probably to transform your dataframe into a list and use Counter from collections:

```<code>from collections import Counter

listed_df = [tuple(line) for line in list(df.values)]
counts = Counter(listed_df)
</code>```

Title: using groupby attribute in pandas

Body:
Using only pandas, one way could be to use DataFrame.groupby():

counts = dict()

for group in df.groupby(['It', 'Cc', 'Ct']):
    print(group)
    counts[group[0]] = len(group[1])

A faster way is probably to transform your dataframe into a list and use Counter from collections:

from collections import Counter

listed_df = [tuple(line) for line in list(df.values)]
counts = Counter(listed_df)


问:
mvvmcross5 navigation service: In what way I should use Initialize method to change UI?
I'm playing with mvvmcross5 navigation service.
And I try to change label from Initialize method, but nothing happens.

What I doing wrong?

Here's simple code of it:

```<code>public class SecondViewModel : MvxViewModel<Dictionary<string, string>>
{
    private readonly IMvxNavigationService _navigationService;
    private string _mainPageButtonText = "test";

    public SecondViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;
    }

    public string MainPageButtonText
    {
        get
        {
            return _mainPageButtonText;
        }
        set
        {
            SetProperty(ref _mainPageButtonText, value);
        }
    }

    public IMvxAsyncCommand BackCommand => new MvxAsyncCommand(() => {

        MainPageButtonText = "it works";

        return Task.FromResult(true);
    });

    public override Task Initialize(Dictionary<string, string> parameter)
    {
        MainPageButtonText = "it does not work";

        return Task.FromResult(true);
    }
}
</code>```

答: This is a bug in MvvmCross, and will be fixed in 5.0.2. See https://github.com/MvvmCross/MvvmCross/releases/tag/5.0.2</p>

Body:
I'm playing with mvvmcross5 navigation service.
And I try to change label from Initialize method, but nothing happens.

What I doing wrong?

Here's simple code of it:

public class SecondViewModel : MvxViewModel<Dictionary<string, string>>
{
    private readonly IMvxNavigationService _navigationService;
    private string _mainPageButtonText = "test";

    public SecondViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;
    }

    public string MainPageButtonText
    {
        get
        {
            return _mainPageButtonText;
        }
        set
        {
            SetProperty(ref _mainPageButtonText, value);
        }
    }

    public IMvxAsyncCommand BackCommand => new MvxAsyncCommand(() => {

        MainPageButtonText = "it works";

        return Task.FromResult(true);
    });

    public override Task Initialize(Dictionary<string, string> parameter)
    {
        MainPageButtonText = "it does not work";

        return Task.FromResult(true);
    }
}


问:
Path and extension of image
I want to get the Path a of image of the photo albums from the iPhone device. and also i need the extension of that image with their name.</p>

答:
```<code>newFilePath = [NSHomeDirectory()
    stringByAppendingPathComponent: textFieldNormalFile_name.text];
//newFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent: @"ChosenPic.jpg"];
imageData = UIImageJPEGRepresentation(img, 1.0);
if (imageData != nil) {
    NSLog(@"HERE [%@]", newFilePath);
    [imageData writeToFile:newFilePath atomically:YES];
}
image.image =[UIImage imageNamed:newFilePath];
NSLog(@"newFilePath:%@",newFilePath);
path.text =[NSString stringWithFormat:newFilePath];
NSLog(@"path.text :%@",path.text);
</code>```

Title: Path and extension of image


问:
How to Alow Two Letters at the end of string with regex?
I have the following pattern:

```<code>^(01|04|05|06|PP|PPC)[0-9]*$
</code>```

This works if the string starts with PP and ends with numbers.

How to allow UK at the end? I want to match a string like: PPC12345678UK

答:
The best practice is to use an optional non-capturing group for optional sequences of atoms in a regex. Besides, when an alternation group is used, it is best to make sure each branch (|-separated) does not match at the same location.

So, I'd recommend:

```<code>^(?:0[1456]|PPC?)[0-9]*(?:UK)?$
</code>```

Details:

^ - start of a string

(?:0[1456]|PPC?) - either of the 2 alternatives:

0[1456] - 0 followed with 1, 4, 5 or 6

| - or

PPC? - PP or PPC.

[0-9]* - zero or more digits

(?:UK)? - an optiona UK substring

$ - end of string.

See the .NET regex demo:

And here is the regex diagram:

Body:
I have the following pattern:

^(01|04|05|06|PP|PPC)[0-9]*$

This works if the string starts with PP and ends with numbers.

How to allow UK at the end? I want to match a string like: PPC12345678UK

Body:
The best practice is to use an optional non-capturing group for optional sequences of atoms in a regex. Besides, when an alternation group is used, it is best to make sure each branch (|-separated) does not match at the same location.

So, I'd recommend:

^(?:0[1456]|PPC?)[0-9]*(?:UK)?$

Details:

^ - start of a string

(?:0[1456]|PPC?) - either of the 2 alternatives:

0[1456] - 0 followed with 1, 4, 5 or 6

| - or

PPC? - PP or PPC.

[0-9]* - zero or more digits

(?:UK)? - an optiona UK substring

$ - end of string.

See the .NET regex demo:

And here is the regex diagram:


问:
Simulate requests to url with different IPs
I have a php file on my wamp server that simply listens to new users that enters the page and prints their IPs.

I read a lot about IP spoofing and I'd like to test that.

Would it be possible to send multiple http requests from my computer and make the php "think" that different users are entering the page?

I don't care about the response from the php file.

答:
Unless you configure apache to pass a random REMOTE_ADDR parameter there is no easy way to do it from your computer alone. What you can try is using proxies to connect, this will offcourse require that you have a public IP or a server.

Edit: GordonM made agood point in the comment, you can use multiple VM's to simulate a set of servers with their own IP addresses.


问:
Sagepay error 5080 After updating woocommerce
My developer recently updated my WooCommerce website in WordPress and now my Sagepay payment gateway directs to error

5080 Form transaction registration failed

First time this issue has happened and Sagepay has been working fine until this.

答: Log into My Sage Pay, click the 'Transactions' tab, then click 'Invalid'. The entries in the list should give you a more detailed indication of what is wrong.... </p>


问:
How to setup Dotnetnuke Scheduled Job on ASP.NET (C#)
How can I setup a custom Scheduler Task in DotNetNuke to run my own automated code?</p>

答:
In short you build a DLL that the DNN scheduler can run in the background at given intervals. You then use the DNN scheduled task interface to set up this DLL once you have added it to the DNN /bin folder.

I've built a sample project which demonstrates a DNN scheduled task in C# with a separate project that can run the task code outside of DNN to make debugging easier.

You can read my blog post about it here:

http://www.bilgewater.co.uk/post/20/1/2017/Build-and-Debug-a-DNN-Scheduled-Task

The source code is available on Github here:

https://github.com/GusBeare/DNNSchedule

Hope it helps.


问:
Multiple line using named ranges VBA
I am attempting to plot multiple named ranges on to a chart. These named ranges (named for example Time_Series_1) are of the form:

=INDIRECT(Ranges!$AJ$3) where this argument Ranges!$AJ$3 is for example

```<code> ="'Source Data'!"&ADDRESS(N3,(Comparisons!$G$28+5))&":"&ADDRESS(N3(Comparisons!$I$28+5))
</code>```

The code I'm attempting to use to plot the these ranges (I have started with one as any more remain to be impossible as one is not working) is:

```<code>Sheets("Comparisons").Select
Sheet10.ChartObjects("Chart 2").Activate

Set Rng = range("Time_Series_1")
Set Date_Rng = range("Time_Series_Dates_1")

With ActiveChart
    .SetSourceData Source:=Rng
    .XValues = Date_Rng
End With
</code>```

It's not working! The Chart remains blank. Completely empty. What am I not updating? What am I not activating?

Thanks

答:
```<code> ActiveChart.SeriesCollection(1).XValues = Date_Rng
 ActiveChart.SeriesCollection(1).Values = Rng
 ActiveChart.Axes(xlCategory, xlPrimary).HasTitle = True
 ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Dates"
 ActiveChart.Axes(xlValue, xlPrimary).HasTitle = True
  ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Pounds"
 ActiveChart.Axes(xlCategory).HasMajorGridlines = True
</code>```

Title: Multiple line using named ranges VBA

Body:
I am attempting to plot multiple named ranges on to a chart. These named ranges (named for example Time_Series_1) are of the form:

=INDIRECT(Ranges!$AJ$3) where this argument Ranges!$AJ$3 is for example

 ="'Source Data'!"&ADDRESS(N3,(Comparisons!$G$28+5))&":"&ADDRESS(N3(Comparisons!$I$28+5))

The code I'm attempting to use to plot the these ranges (I have started with one as any more remain to be impossible as one is not working) is:

Sheets("Comparisons").Select
Sheet10.ChartObjects("Chart 2").Activate

Set Rng = range("Time_Series_1")
Set Date_Rng = range("Time_Series_Dates_1")

With ActiveChart
    .SetSourceData Source:=Rng
    .XValues = Date_Rng
End With

It's not working! The Chart remains blank. Completely empty. What am I not updating? What am I not activating?

Thanks


问:
Spring MVC Interceptor error response result in blank page
In my spring MVC app (3.1.4-release, Servlet 2.5),
I am not able to display a custom 403 error page when trigger from my HandlerInterceptorAdapter.

My web.xml :

```<code><error-page>
    <error-code>404</error-code>
    <location>/404</location>
</error-page>
<error-page>
    <error-code>403</error-code>
    <location>/403</location>
</error-page>
</code>```

My Error Controller :

```<code>@Controller
public class HTTPErrorController {

 @RequestMapping(value="403")
 public ModelAndView error403(){
     return new ModelAndView("/errors/403");
 }

 @RequestMapping(value="404")
 public ModelAndView error404(){
     return new ModelAndView("/errors/404");
 }
}
</code>```

My Handler interceptor :

```<code>public class CSRFHandlerInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    // Validate CSRF token on POST request only.
    if (request.getMethod().equalsIgnoreCase("post")) {
        if (!CSRFTokenManager.verifyCSRFToken(request)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Bad or missing CSRF value");
            return false;
        }
    }
    return true;
}
</code>```

When the sendError is sent, I have a blank page in firefox and in Ie.
404 exception is working correctly but can't figure out how to make the 403 display my custom error page.

Firefox screenshot:
http://hpics.li/8b6ab9f

Httpfox screenshot :
http://hpics.li/b032ca0

** I am using apache-tomcat-7.0.42

Thanks

答:
I got a similar problem.

For my situation, I figured out it is because my error page do response.forward and than goto Interceptor again. (infinite loop)

i.e., You can try to simplify your /error/403 page to plaintext: "Here is 403".

Body:
In my spring MVC app (3.1.4-release, Servlet 2.5),
I am not able to display a custom 403 error page when trigger from my HandlerInterceptorAdapter.

My web.xml :

<error-page>
    <error-code>404</error-code>
    <location>/404</location>
</error-page>
<error-page>
    <error-code>403</error-code>
    <location>/403</location>
</error-page>

My Error Controller :

@Controller
public class HTTPErrorController {

 @RequestMapping(value="403")
 public ModelAndView error403(){
     return new ModelAndView("/errors/403");
 }

 @RequestMapping(value="404")
 public ModelAndView error404(){
     return new ModelAndView("/errors/404");
 }
}

My Handler interceptor :

public class CSRFHandlerInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    // Validate CSRF token on POST request only.
    if (request.getMethod().equalsIgnoreCase("post")) {
        if (!CSRFTokenManager.verifyCSRFToken(request)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Bad or missing CSRF value");
            return false;
        }
    }
    return true;
}

When the sendError is sent, I have a blank page in firefox and in Ie.
404 exception is working correctly but can't figure out how to make the 403 display my custom error page.

Firefox screenshot:
http://hpics.li/8b6ab9f

Httpfox screenshot :
http://hpics.li/b032ca0

** I am using apache-tomcat-7.0.42

Thanks


问:
Regex Option in C# and Regex in Visual Studio
I learn about regular expression, and i have two quastions;

I saw, that I can define an options to the regex, but i don't succes to understand whah are the ECMAScript, CultureInvariant and ExplicitCapture options, can anyone explain in simply words and give an example to aforementioned options?

in visual studio, can replce and find by regex, but the syntax of vs differents from the syntax that regex object uses,does anyone know why?

答:
ExplicitCapture makes all parentheses non-capturing unless you use named captures. This can make regexes a bit more readable because you can write (...) where you otherwise would have had to write (?:...) to make a non-capturing group.

The downside, of course, is that if you do  want to capture part of the match, you have to write Name: (?<name>.*) instead of Name: (.*), for example.

ECMAScript causes the regex engine to behave like an ECMASCript (e. g., JavaScript) regex engine, which means dropping a lot of regex features of the .NET regex engine - but it allows you to use JavaScript regexes unchanged.

CultureInvariant tells the regex engine to ignore cultural differences in case matching. For example, in Turkish, the uppercase version of i is not I as it is in English, but İ, so a culture-sensitive, case-insensitive match of i would not match I on a Turkish system.

You might want to check out this link and this link for more info on this.


问:
Calling method from a specific childViewControllers class
Alright, hope I can explain this as clearly as possible.

I have a Parent ViewController which has a ContainerView, this will contain different viewControllers/Class. I'm changing the content of this container at runtime like this:

```<code>    let newController = (storyboard?.instantiateViewController(withIdentifier: classIdentifierFromStoryboard))! as UIViewController
    let oldController = childViewControllers.last! as UIViewController

    oldController.willMove(toParentViewController: nil)
    addChildViewController(newController)
    newController.view.frame = oldController.view.frame

    transition(from: oldController, to: newController, duration: 0, options: .transitionCrossDissolve, animations:{ () -> Void in
        }, completion: { (finished) -> Void in

    })

    oldController.removeFromParentViewController()
    newController.didMove(toParentViewController: self)
</code>```

So for example, the current controller that shows on UI is firstVC, which kinda look like

```<code>class firstVC {
    func removeAnnotations() {
        //something that removes annotation from MapVC
     }
}
</code>```

On a certain event on the parent controller, how can I access the instance of firstVC so that i'll be able to call removeAnnotations? As of the moment I am getting nil, using this on parent controller firstVC.removeAnnotations, assumably this calls another instance of the class. Any help would be great! Hope my explanation makes sense. Thanks!

答:
in this code is child view controller ProfileViewController

in first create one object of child view controller like this

```<code> var objectProfile:ProfileViewController!
</code>```

then viewDidLoad method

```<code> override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        objectProfile = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
        objectProfile.view.frame = CGRect(x:  -(self.view.frame.size.width - 40), y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)
        self.view.addSubview(objectProfile.view)
        self.navigationController?.didMove(toParentViewController: objectProfile)

        objectProfile.view.isHidden = true

    }
</code>```

then button click method code here

```<code> @IBAction func btnProfilePressed(_ sender: UIButton) {

        UIView.animate(withDuration: 0.3) {

            self.objectProfile.view.frame = CGRect(x:  0, y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)

        }

    }
</code>```

then touchesBegan

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        objectProfile.view.isHidden = false

        UIView.animate(withDuration: 0.3) {

            self.objectProfile.view.frame = CGRect(x:  -(self.view.frame.size.width - 40), y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)

       }

    }
</code>```

complete set this code out put is

Body:
Alright, hope I can explain this as clearly as possible.

I have a Parent ViewController which has a ContainerView, this will contain different viewControllers/Class. I'm changing the content of this container at runtime like this:

    let newController = (storyboard?.instantiateViewController(withIdentifier: classIdentifierFromStoryboard))! as UIViewController
    let oldController = childViewControllers.last! as UIViewController

    oldController.willMove(toParentViewController: nil)
    addChildViewController(newController)
    newController.view.frame = oldController.view.frame

    transition(from: oldController, to: newController, duration: 0, options: .transitionCrossDissolve, animations:{ () -> Void in
        }, completion: { (finished) -> Void in

    })

    oldController.removeFromParentViewController()
    newController.didMove(toParentViewController: self)

So for example, the current controller that shows on UI is firstVC, which kinda look like

class firstVC {
    func removeAnnotations() {
        //something that removes annotation from MapVC
     }
}

On a certain event on the parent controller, how can I access the instance of firstVC so that i'll be able to call removeAnnotations? As of the moment I am getting nil, using this on parent controller firstVC.removeAnnotations, assumably this calls another instance of the class. Any help would be great! Hope my explanation makes sense. Thanks!

Body:
in this code is child view controller ProfileViewController

in first create one object of child view controller like this

 var objectProfile:ProfileViewController!

then viewDidLoad method

 override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        objectProfile = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
        objectProfile.view.frame = CGRect(x:  -(self.view.frame.size.width - 40), y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)
        self.view.addSubview(objectProfile.view)
        self.navigationController?.didMove(toParentViewController: objectProfile)

        objectProfile.view.isHidden = true

    }

then button click method code here

 @IBAction func btnProfilePressed(_ sender: UIButton) {

        UIView.animate(withDuration: 0.3) {

            self.objectProfile.view.frame = CGRect(x:  0, y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)

        }

    }

then touchesBegan

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        objectProfile.view.isHidden = false

        UIView.animate(withDuration: 0.3) {

            self.objectProfile.view.frame = CGRect(x:  -(self.view.frame.size.width - 40), y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)

       }

    }

complete set this code out put is


问:
Debug Node.JS on VS Code EADDRINUSE error
I am trying to debug a Node.JS application on VS Code but, when the terminal opens, I get this message:

Error: listen EADDRINUSE :::5858

My application uses a framework called StrawJS (https://github.com/simonswain/straw) and it starts some different processes at the same time. I think that this is the cause of the error because there are many different processes trying to use the same debugger.

I found a similar question (VSCode will not stop on breakpoints when first node prcess forks a second) but configure the port on the attach.js file didn't work, the problem persists.

This is my actual launch.json file:

```<code>{
"version": "0.2.0",
"configurations": [
    {
        "name": "Launch",
        "type": "node",
        "request": "launch",
        "port": 5858,
        "program": "${workspaceRoot}/run.js",
        "stopOnEntry": false,
        "args": [],
        "cwd": "${workspaceRoot}",
        "preLaunchTask": null,
        "runtimeExecutable": null,
        "runtimeArgs": [
            "--nolazy"
        ],
        "env": {
            "NODE_ENV": "development"
        },
        "externalConsole": true,
        "sourceMaps": false,
        "outDir": null
    }
]}
</code>```

Thank you!

答:
I had the same issue. If you started the node --debug from CMD, you have to only Attach to Process in your VS Code (if you try to launch it again from VS Code on the same port it will cause an error - this was my mistake).

Define the attach configuration object in launch.json with something like this:

```<code>{
    "type": "node",
    "request": "attach",
    "name": "Attach to Process",
    "port": 5858
}
</code>```

choose Attach to Process in the dropdown in the upper left corner and press green play button - Start Debugging.

Body:
I am trying to debug a Node.JS application on VS Code but, when the terminal opens, I get this message:

Error: listen EADDRINUSE :::5858

My application uses a framework called StrawJS (https://github.com/simonswain/straw) and it starts some different processes at the same time. I think that this is the cause of the error because there are many different processes trying to use the same debugger.

I found a similar question (VSCode will not stop on breakpoints when first node prcess forks a second) but configure the port on the attach.js file didn't work, the problem persists.

This is my actual launch.json file:

{
"version": "0.2.0",
"configurations": [
    {
        "name": "Launch",
        "type": "node",
        "request": "launch",
        "port": 5858,
        "program": "${workspaceRoot}/run.js",
        "stopOnEntry": false,
        "args": [],
        "cwd": "${workspaceRoot}",
        "preLaunchTask": null,
        "runtimeExecutable": null,
        "runtimeArgs": [
            "--nolazy"
        ],
        "env": {
            "NODE_ENV": "development"
        },
        "externalConsole": true,
        "sourceMaps": false,
        "outDir": null
    }
]}

Thank you!

Body:
I had the same issue. If you started the node --debug from CMD, you have to only Attach to Process in your VS Code (if you try to launch it again from VS Code on the same port it will cause an error - this was my mistake).

Define the attach configuration object in launch.json with something like this:

{
    "type": "node",
    "request": "attach",
    "name": "Attach to Process",
    "port": 5858
}

choose Attach to Process in the dropdown in the upper left corner and press green play button - Start Debugging.


问:
Path Finding in 3d environment in Java
I understand that there are a couple of links about path finding in 2d.Is there any java example that shows how to implement path findings in 3d environment.

I have already seen lot of code and explanations about this.but none of them will really help.How to implement this in 3d enviorment

答: If you mean 3d pathfinding as 2d pathfinding in 3d space. For example, you have a 3d scene and something needs to find its way around the walls and rooms. If this is the case you can just make some system to keep track of all your walls (say... BSP tree?) and then implement a common pathfinding algorithm such as A*.</p>

Title: Path Finding in 3d environment in Java


问:
How to make enter key as tab for input and submit if button found in angularjs?
I have a view where there are two buttons. one for save and another for update.: I want to use enter key as tab. If it reaches last input and find button, the form will be submitted (ng-click function will be triggered). Is it possible to do with two button or i should rely on only one button?

I tried:

```<code>     $('#truckform input ,#truckform button').on("keypress", function(e) {
                 // ENTER PRESSED
                if (e.keyCode == 13) {

                    console.log('tag')
                   // FOCUS ELEMENT
                    var inputs = $(this).parents("form").eq(0).find(":input");
                    var idx = inputs.index(this);
console.log(idx)

                    console.log(inputs.length)
                    if (idx == inputs.length - 1) {
                        inputs[0].select()
                    } else {
                        inputs[idx + 1].focus(); //  handles submit buttons
                        inputs[idx + 1].select();
                    }
                    return false;
                }
            });
</code>```

I gives the error in console when button gets focus:

```<code>Uncaught TypeError: inputs[(idx + 1)].select is not a function
at HTMLInputElement.<anonymous> (truckEntry.js:56)
at HTMLInputElement.dispatch (jquery-2.2.3.min.js:3)
at HTMLInputElement.r.handle (jquery-2.2.3.min.js:3)
</code>```

But after the error, the saveData() function is triggered. But in the update mode, the updateData() is not triggered and the error remains all times till i press enter. How can i maake it functional? Any suggestion?
  My view:

```<code>  <form  name="truckform" id="truckform" novalidate>
               <table id="truckformTbl">
                   <tr>
                       <td class="text-center" colspan="6">
                           <h4 class="ok"> Truck Entry/Exit Form</h4>
                       </td>
                   </tr>
                    <tr ng-hide="hideManifestDetailsInput">
                        <th>Manifest No : </th>
                        <td>
                            <input type="text" ng-pattern='/^[0-9]{1,10}[/]{1}([0-9]{1,2}|[(A|a)]{1})$/' required="required" ng-disabled="disbleManifestNoInpForEditMode"  ng-model="ManifestNo" name="ManifestNo" id="Manifest_no" class="form-control input-sm" placeholder="Manifest No.">
                            <span class="error" ng-show='truckform.ManifestNo.$error.pattern'>
                                Input like: 256/12 Or 256/A
                            </span>
                            <span class="error" ng-show="submitted && !ManifestNo && !truckform.ManifestNo.$error.pattern">
                              Manifest No is required
                            </span>

                            <span class="error" ng-show="truckExceedInManifest">Manifest is full</span>
                        </td>
                        <th>  Manifest Date :</th>
                        <td>
                            <input type="text"  ng-model="manifest_date" required="required" name="manifest_date" id="manifest_date" class="form-control datePicker input-sm" placeholder="Manifest date">

                            <span ng-show="submitted && !manifest_date" class="error">Select a date</span>
                        </td>
                        <th> Goods Name :</th>

                        <td style="width: 15em; vertical-align: top" rowspan="8">
                           {{-- <select class="form-control input-sm" name="goods_id" ng-model="goods_id"
                                    ng-options="good.id as good.id +'-'+good.cargo_name group by good.category for good in allGoodsData ">

                                <option value="" selected="selected">Select Goods Name</option>
                            </select>
                            <span class="error" ng-show="truckform.goods_id.$dirty && truckform.goods_id.$touched && !goods_id ">
                             Select at least one goods
                            </span>--}}

                            <tags-input ng-model="goods_id"
                                        display-property="cargo_name"
                                        placeholder="Add New Item"
                                        replace-spaces-with-dashes="false"
                                        add-from-autocomplete-only="true"
                                        on-tag-added="tagAdded($tag)"
                                        on-tag-removed="tagRemoved($tag)">

                                <auto-complete source="loadGoods($query)"
                                               min-length="0"
                                               debounce-delay="0"
                                               max-results-to-show="10">

                                </auto-complete>

                            </tags-input>
                            <span ng-show="submitted && !goods_id ||goods_id.length==0" class="error">Choose at least one goods!</span>
                        </td>
                    </tr>

<tr>
    <td colspan="4"> </td>
</tr>
                    <tr>
                        <th>Truck Type :</th>
                        <td>
                            <input type="text" ng-model="truck_type" name="truck_type" id="truck_type" class="form-control input-sm" value="{{old('truck_type')}}"  placeholder="Truck Type">
                            <span class="error" ng-show="submitted && !truck_type">
                             Truck Type is required
                            </span>
                        </td>

                        <th>  Truck No :</th>
                        <td>
                            <input type="number" min="1" required="required" ng-model="truck_no" name="truck_no" id="truckNo" class="form-control input-sm" placeholder="Truck No" value="{{old('truck_no')}}">
                            <span class="error" ng-show="submitted && !truck_no">
                             Truck No is required
                            </span>
                        </td>

                    </tr>

                    <tr>
                        <td colspan="4"> </td>
                    </tr>

                    <tr>
                        <th>Driver Card No :</th>
                        <td>
                            <input type="number" ng-model="driver_card" name="DriverCardNo" id="DriverCardNo" class="form-control input-sm" placeholder="Driver Card No." value="{{old('DriverCardNo')}}">

                            <span class="error" ng-show="submitted && !driver_card">
                             Driver Card No. is required
                            </span>
                        </td>

                        <th>  Weight Bridge:</th>
                        <td>
                            <label class="radio-inline">
                                <input type="radio" name="fff" ng-init="weightment_flag=1"  ng-model="weightment_flag" ng-checked="true"  value="1">Yes
                            </label>
                            <label class="radio-inline">
                                <input type="radio"  ng-model="weightment_flag"  value="0" >No
                            </label>
                        </td>

                    </tr>
                   <tr>
                       <td colspan="4"> </td>
                   </tr>

                   <tr>
                       <th>  Driver Name :</th>
                       <td style="width: 15em;">
                           <input type="text" ng-model="driver_name" name="DriverName" id="driverName" class="form-control input-sm" placeholder="Driver Name" value="{{old('DriverName')}}">
                           <span class="error" ng-show="submitted && !driver_name">
                             Driver Name is required
                            </span>
                       </td>
                   </tr>
                    <tr>
                        <td colspan="3"></td>

                        <td colspan="1" class="text-center">
                            <br>
                            <button type="button" ng-click="saveData(truckform)" ng-hide="updateBtn" class="btn btn-primary btn-block center-block">
                                <span class="fa fa-download"></span>
                                Save
                            </button>
                            <button type="button" ng-click="updateData(truckform)" ng-show="updateBtn"  class="btn btn-primary center-block">
                                <span class="fa fa-download"></span>
                                Update
                            </button>
                        </td>
                        <td colspan="2"> </td>
                    </tr>

                   <tr>
                       <td colspan="2"></td>
                       <td class="text-center" colspan="3">

                           <div id="success" class="col-md-12 alert alert-success" ng-show="successMsg">
                               Successfully @{{ successMsgTxt }}!
                           </div>

                           <div id="error" class="col-md-12 alert alert-warning" ng-show="errorMsg">
                                @{{ errorMsgTxt }}!
                           </div>
                       </td>
                       <td colspan="1"> </td>
                   </tr>
                </table>
                </form>
</code>```

答:
You can use enter key as tab as follows: </p>

```<code>  $('input').bind("keypress", function(e) {
     // ENTER PRESSED
    if (e.which == 13) {
        e.preventDefault();
        $(this).next().focus();
      }
    }
  });
</code>```

<p>Small plunker here </p>

Body:
I have a view where there are two buttons. one for save and another for update.: I want to use enter key as tab. If it reaches last input and find button, the form will be submitted (ng-click function will be triggered). Is it possible to do with two button or i should rely on only one button?

I tried:

     $('#truckform input ,#truckform button').on("keypress", function(e) {
                 // ENTER PRESSED
                if (e.keyCode == 13) {

                    console.log('tag')
                   // FOCUS ELEMENT
                    var inputs = $(this).parents("form").eq(0).find(":input");
                    var idx = inputs.index(this);
console.log(idx)

                    console.log(inputs.length)
                    if (idx == inputs.length - 1) {
                        inputs[0].select()
                    } else {
                        inputs[idx + 1].focus(); //  handles submit buttons
                        inputs[idx + 1].select();
                    }
                    return false;
                }
            });

I gives the error in console when button gets focus:

Uncaught TypeError: inputs[(idx + 1)].select is not a function
at HTMLInputElement.<anonymous> (truckEntry.js:56)
at HTMLInputElement.dispatch (jquery-2.2.3.min.js:3)
at HTMLInputElement.r.handle (jquery-2.2.3.min.js:3)

But after the error, the saveData() function is triggered. But in the update mode, the updateData() is not triggered and the error remains all times till i press enter. How can i maake it functional? Any suggestion?
  My view:

  <form  name="truckform" id="truckform" novalidate>

 Truck Entry/Exit Form

                        Manifest No :

                            <input type="text" ng-pattern='/^[0-9]{1,10}[/]{1}([0-9]{1,2}|[(A|a)]{1})$/' required="required" ng-disabled="disbleManifestNoInpForEditMode"  ng-model="ManifestNo" name="ManifestNo" id="Manifest_no" class="form-control input-sm" placeholder="Manifest No.">

                                Input like: 256/12 Or 256/A

                              Manifest No is required

                            Manifest is full

                          Manifest Date :

                            <input type="text"  ng-model="manifest_date" required="required" name="manifest_date" id="manifest_date" class="form-control datePicker input-sm" placeholder="Manifest date">

                            Select a date

                         Goods Name :

                           {{-- <select class="form-control input-sm" name="goods_id" ng-model="goods_id"
                                    ng-options="good.id as good.id +'-'+good.cargo_name group by good.category for good in allGoodsData ">

                                <option value="" selected="selected">Select Goods Name</option>
                            </select>

                             Select at least one goods
                            --}}

                            <tags-input ng-model="goods_id"
                                        display-property="cargo_name"
                                        placeholder="Add New Item"
                                        replace-spaces-with-dashes="false"
                                        add-from-autocomplete-only="true"
                                        on-tag-added="tagAdded($tag)"
                                        on-tag-removed="tagRemoved($tag)">

                                <auto-complete source="loadGoods($query)"
                                               min-length="0"
                                               debounce-delay="0"
                                               max-results-to-show="10">

                                </auto-complete>

                            </tags-input>
                            Choose at least one goods!

                        Truck Type :

                            <input type="text" ng-model="truck_type" name="truck_type" id="truck_type" class="form-control input-sm" value="{{old('truck_type')}}"  placeholder="Truck Type">

                             Truck Type is required

                          Truck No :

                            <input type="number" min="1" required="required" ng-model="truck_no" name="truck_no" id="truckNo" class="form-control input-sm" placeholder="Truck No" value="{{old('truck_no')}}">

                             Truck No is required

                        Driver Card No :

                            <input type="number" ng-model="driver_card" name="DriverCardNo" id="DriverCardNo" class="form-control input-sm" placeholder="Driver Card No." value="{{old('DriverCardNo')}}">

                             Driver Card No. is required

                          Weight Bridge:

                                <input type="radio" name="fff" ng-init="weightment_flag=1"  ng-model="weightment_flag" ng-checked="true"  value="1">Yes

                                <input type="radio"  ng-model="weightment_flag"  value="0" >No

                         Driver Name :

                           <input type="text" ng-model="driver_name" name="DriverName" id="driverName" class="form-control input-sm" placeholder="Driver Name" value="{{old('DriverName')}}">

                             Driver Name is required

                            <button type="button" ng-click="saveData(truckform)" ng-hide="updateBtn" class="btn btn-primary btn-block center-block">

                                Save
                            </button>
                            <button type="button" ng-click="updateData(truckform)" ng-show="updateBtn"  class="btn btn-primary center-block">

                                Update
                            </button>

                               Successfully @{{ successMsgTxt }}!

                                @{{ errorMsgTxt }}!

                </form>

Body:
You can use enter key as tab as follows:

  $('input').bind("keypress", function(e) {
     // ENTER PRESSED
    if (e.which == 13) {
        e.preventDefault();
        $(this).next().focus();
      }
    }
  });

Small plunker here