问:
sql statistics io scan count explanation
Simple question, but I haven't found a good explanation on google. When using Set Statistics IO ON, the logical reads and scan count is provided in the message window of management studio. If I have:

tblExample, scan count 5, logical reads 20

What does scan count signify?

答:
From Books On Line

Scan count:
Number of index or table scans performed.

logical reads:
Number of pages read from the data cache.

physical reads:
Number of pages read from disk.

read-ahead reads:
Number of pages placed into the cache for the query.

See also here: http://technet.microsoft.com/en-us/library/ms184361.aspx

OwnerDisplayName: Paulj

OwnerDisplayName: SQLMenace


来源: stackexchange

问:
Combining Rows by Code
Data set:

```<code>  CREATE TABLE Returned(
  Code varchar(20) not null,
  RUnits int not null,
  RCost int not null,
  RPrice int not null,
  RDate date not null);

  Insert into Returned(Code, Runits, rcost, rprice, rdate)
  values
  ('ORANGES123', 10, 200, 500, '2017-04-01'),
  ('BANANAS123', 15, 350, 900, '2017-04-01'),
  ('APPLES123', 7, 234, 756, '2017-04-01'),
    ('ORANGES123', 10, 200, 500, '2017-04-02'),
  ('BANANAS123', 15, 350, 900, '2017-04-02'),
  ('APPLES123', 7, 234, 756, '2017-04-02');

  CREATE TABLE Cancelled(
  Code varchar(20) not null,
  CUnits int not null,
  CCost int not null,
  CPrice int not null,
  CDate date not null
  );

    Insert into Cancelled(Code, Cunits, Ccost, Cprice, Cdate)
  values
  ('ORANGES123', 3, 100, 200, '2017-04-01'),
  ('BANANAS123', 5, 243, 500, '2017-04-01'),
  ('APPLES123', 10, 235, 537, '2017-04-01'),
  ('ORANGES123', 3, 100, 200, '2017-04-02'),
  ('BANANAS123', 5, 243, 500, '2017-04-02'),
  ('APPLES123', 10, 235, 537, '2017-04-02');
</code>```

Sqlfiddle here:

http://sqlfiddle.com/#!9/f10634

Background:

I have 2 tables. A table for returns, and a table for cancels. I want to get a summation over the past week of the total number of units/cost/price for a given item code. For example, from the sqlfiddle, ORANGES123, I want my query to return:

```<code>ItemCode  , TotalReturnedUnits, TotalReturnedCost, TotalReturnedPrice,TotalCancelledUnits, TotalCancelledCost, TotalCancelledPrice
ORANGES123,                 20,               400,               1000,                  6,                200,                 400
</code>```

This seems simple but for some reason when I'm doing an inner join by ItemCode between my two tables in SQL Server, Units between the Cancelled and Returned tables are being combined and the counts are being cross-polluted between Returned/Cancelled.

I feel like I'm missing something very simple.

Any help would be appreciated.

The actual query I'm working with is here. I tried to model the sqlfiddle as close as possible:

```<code>SELECT sales.Code AS Code,
       sales.Quantity AS QtyReturned,
       price.WghtAvgCost * sales.Quantity AS ReturnedCost,
       price.CurrentPrice * sales.Quantity AS ReturnedPrice,
       orders.CancelledUnits,
       orders.CancelledCost,
       orders.CancelledPrice,
       price.CurrentPriceType AS PriceType
FROM salesTable sales
     INNER JOIN costPriceTable price ON sales.Code= price.Code
                                                  AND (sales.BusinessDate BETWEEN price.StartDate AND price.EndDate)
                                                  AND sales.LocationId = price.LocationId
    INNER JOIN  ordersTable orders
       ON sales.Code= orders.Code
</code>```

ContentLicense: CC BY-SA 3.0

Title: Combining Rows by Code

Body:
Data set:

  CREATE TABLE Returned(
  Code varchar(20) not null,
  RUnits int not null,
  RCost int not null,
  RPrice int not null,
  RDate date not null);

  Insert into Returned(Code, Runits, rcost, rprice, rdate)
  values
  ('ORANGES123', 10, 200, 500, '2017-04-01'),
  ('BANANAS123', 15, 350, 900, '2017-04-01'),
  ('APPLES123', 7, 234, 756, '2017-04-01'),
    ('ORANGES123', 10, 200, 500, '2017-04-02'),
  ('BANANAS123', 15, 350, 900, '2017-04-02'),
  ('APPLES123', 7, 234, 756, '2017-04-02');

  CREATE TABLE Cancelled(
  Code varchar(20) not null,
  CUnits int not null,
  CCost int not null,
  CPrice int not null,
  CDate date not null
  );

    Insert into Cancelled(Code, Cunits, Ccost, Cprice, Cdate)
  values
  ('ORANGES123', 3, 100, 200, '2017-04-01'),
  ('BANANAS123', 5, 243, 500, '2017-04-01'),
  ('APPLES123', 10, 235, 537, '2017-04-01'),
  ('ORANGES123', 3, 100, 200, '2017-04-02'),
  ('BANANAS123', 5, 243, 500, '2017-04-02'),
  ('APPLES123', 10, 235, 537, '2017-04-02');

Sqlfiddle here:

http://sqlfiddle.com/#!9/f10634

Background:

I have 2 tables. A table for returns, and a table for cancels. I want to get a summation over the past week of the total number of units/cost/price for a given item code. For example, from the sqlfiddle, ORANGES123, I want my query to return:

ItemCode  , TotalReturnedUnits, TotalReturnedCost, TotalReturnedPrice,TotalCancelledUnits, TotalCancelledCost, TotalCancelledPrice
ORANGES123,                 20,               400,               1000,                  6,                200,                 400

This seems simple but for some reason when I'm doing an inner join by ItemCode between my two tables in SQL Server, Units between the Cancelled and Returned tables are being combined and the counts are being cross-polluted between Returned/Cancelled.

I feel like I'm missing something very simple.

Any help would be appreciated.

The actual query I'm working with is here. I tried to model the sqlfiddle as close as possible:

SELECT sales.Code AS Code,
       sales.Quantity AS QtyReturned,
       price.WghtAvgCost * sales.Quantity AS ReturnedCost,
       price.CurrentPrice * sales.Quantity AS ReturnedPrice,
       orders.CancelledUnits,
       orders.CancelledCost,
       orders.CancelledPrice,
       price.CurrentPriceType AS PriceType
FROM salesTable sales
     INNER JOIN costPriceTable price ON sales.Code= price.Code
                                                  AND (sales.BusinessDate BETWEEN price.StartDate AND price.EndDate)
                                                  AND sales.LocationId = price.LocationId
    INNER JOIN  ordersTable orders
       ON sales.Code= orders.Code

Body:
Start with this - I think you can figure the rest out...

SELECT *, 'returned' source FROM returned
 UNION ALL
SELECT *, 'cancelled' FROM cancelled;
+------------+--------+-------+--------+------------+-----------+
| Code       | RUnits | RCost | RPrice | RDate      | source    |
+------------+--------+-------+--------+------------+-----------+
| ORANGES123 |     10 |   200 |    500 | 2017-04-01 | returned  |
| BANANAS123 |     15 |   350 |    900 | 2017-04-01 | returned  |
| APPLES123  |      7 |   234 |    756 | 2017-04-01 | returned  |
| ORANGES123 |     10 |   200 |    500 | 2017-04-02 | returned  |
| BANANAS123 |     15 |   350 |    900 | 2017-04-02 | returned  |
| APPLES123  |      7 |   234 |    756 | 2017-04-02 | returned  |
| ORANGES123 |      3 |   100 |    200 | 2017-04-01 | cancelled |
| BANANAS123 |      5 |   243 |    500 | 2017-04-01 | cancelled |
| APPLES123  |     10 |   235 |    537 | 2017-04-01 | cancelled |
| ORANGES123 |      3 |   100 |    200 | 2017-04-02 | cancelled |
| BANANAS123 |      5 |   243 |    500 | 2017-04-02 | cancelled |
| APPLES123  |     10 |   235 |    537 | 2017-04-02 | cancelled |
+------------+--------+-------+--------+------------+-----------+


问:
Event from PrimeNG p-datatable when row is added
I have a p-datatable bound to a list of entries. I want to set focus on newly, dynamically created rows; specifically on an input in the new row. But how?

Whenever I dynamically add an entry to the bound list of entries a new datatable row is added. Works fine. But I need to know when that has happened and I need access to the new row so I can set the focus. I've been looking for some kind of onRowAdded event, but p-datatable doesn't seem to have one. How to get around this?

```<code><p-dataTable [value]="entries">
   . . .
   <p-column>
      <ng-template let-item="rowData" pTemplate="body">
          <input type="time" [value]="item.StartTime"/>
   . . .
</code>```

答:
Ok, so I found a solution/workaround, independent of the p-datatable.

I set up an angular QueryList on one of the templated elements in the rendered row and subscribe to changes on it. This way I can get to the newly added rows in order to set focus.

So, in the html:

```<code><p-dataTable [value]="entries">
   <p-column">
      <ng-template let-item="rowData" pTemplate="body">
          <input #myInput />
</code>```

... and in the codebehind:

```<code>@ViewChildren('myInput') startTimeInputList: QueryList<ElementRef>;
. . .
ngAfterViewInit() {
   this.startTimeInputList.changes.subscribe((p) => {
       this._renderer.invokeElementMethod(p.last.nativeElement, 'focus');
   });
}
</code>```

Body:
I have a p-datatable bound to a list of entries. I want to set focus on newly, dynamically created rows; specifically on an input in the new row. But how?

Whenever I dynamically add an entry to the bound list of entries a new datatable row is added. Works fine. But I need to know when that has happened and I need access to the new row so I can set the focus. I've been looking for some kind of onRowAdded event, but p-datatable doesn't seem to have one. How to get around this?

   . . .

      <ng-template let-item="rowData" pTemplate="body">
          <input type="time" [value]="item.StartTime"/>
   . . .

Body:
Ok, so I found a solution/workaround, independent of the p-datatable.

I set up an angular QueryList on one of the templated elements in the rendered row and subscribe to changes on it. This way I can get to the newly added rows in order to set focus.

So, in the html:

<p-dataTable [value]="entries">
   <p-column">
      <ng-template let-item="rowData" pTemplate="body">
          <input #myInput />

... and in the codebehind:

@ViewChildren('myInput') startTimeInputList: QueryList<ElementRef>;
. . .
ngAfterViewInit() {
   this.startTimeInputList.changes.subscribe((p) => {
       this._renderer.invokeElementMethod(p.last.nativeElement, 'focus');
   });
}


问:
Xamarin Android-Video player Black screen
I'm using the Xamarin Android Player emulator to test the app I'm developing. The emulator doesn't play video at all. There's a black screen in place of the videoview.

I've written very simple code just to test the video playback. The code is below:

```<code>namespace Training
{
    [Activity(Label = "", Icon = "@drawable/icon", Theme = "@style/MyTheme")]
    class videotest : ActionBarActivity
    {
        private Android.Support.V7.Widget.Toolbar mToolbar;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.videotest);
            mToolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(mToolbar);
            SupportActionBar.Title = "";

            var videoView = FindViewById<VideoView>(Resource.Id.SampleVideoView);
            var uri = Android.Net.Uri.Parse("http://www.printopack.somee.com/Uploaded/Grad2.mp4");
            videoView.SetVideoURI(uri);
            videoView.Start();

        }

    }
}
</code>```

答: Try testing it on a real device. When I was working with video views in Xamarin.Android the same thing happened to me on the emulator but on a real device it worked just fine.</p>

Body:
I'm using the Xamarin Android Player emulator to test the app I'm developing. The emulator doesn't play video at all. There's a black screen in place of the videoview.

I've written very simple code just to test the video playback. The code is below:

namespace Training
{
    [Activity(Label = "", Icon = "@drawable/icon", Theme = "@style/MyTheme")]
    class videotest : ActionBarActivity
    {
        private Android.Support.V7.Widget.Toolbar mToolbar;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.videotest);
            mToolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(mToolbar);
            SupportActionBar.Title = "";

            var videoView = FindViewById<VideoView>(Resource.Id.SampleVideoView);
            var uri = Android.Net.Uri.Parse("http://www.printopack.somee.com/Uploaded/Grad2.mp4");
            videoView.SetVideoURI(uri);
            videoView.Start();

        }

    }
}


问:
Delphi: playing mp3 in 64-bit exe
Targeting Windows7+ systems, what's a simple way to play MP3s from my Delphi (10.2 Tokyo) app compiled in 64-bit? I had been using DSPack with 32-bit, but in 64-bit it won't compile. Had a look at BASS but it's also not working on 64-bit.

Preferably something working directly with the Windows API would be preferable over including external dlls with the app.

答:
One simple way is to use mciSendString.

```<code>uses
  Winapi.MMSystem;
....
mciSendString('open audiofile.mp3 type mpegvideo alias song1', nil, 0, 0);
mciSendString('play song1', nil, 0, 0);
</code>```

Title: Delphi: playing mp3 in 64-bit exe

Body:
One simple way is to use mciSendString.

uses
  Winapi.MMSystem;
....
mciSendString('open audiofile.mp3 type mpegvideo alias song1', nil, 0, 0);
mciSendString('play song1', nil, 0, 0);


问:
Oracle database 11: select * from table fails
I have a weird issue. In one of the production DB servers we are trying to run

```<code>select * from SCHEMA_NAME.TABLE_NAME
</code>```

When we run the query we are getting invalid identifier error. But when we select a particular column and run the same select query on the same table , we are able to get the output.

Please help me to understand the root cause.

Type created:

```<code>create or replace
TYPE           "TEST_TYPE" is object
(
MULTIROW_ID VARCHAR2(100 CHAR),
LOSS_ENTRY_TYPE VARCHAR2(1000 CHAR),
SUB_CATEGORY    VARCHAR2(1000 CHAR),
LOSS_AMOUNT NUMBER,
LOSS_ENTRY_CURR  VARCHAR2(100 CHAR)
);
</code>```

Type 2 created:

```<code>create or replace
TYPE           "TEST_TYPE1" AS TABLE OF TEST_TYPE;
</code>```

Main create table query using above table type columns:

```<code>CREATE TABLE "MS_TEST_DATA"
   (    "REGION" VARCHAR2(4000 CHAR),
    "Entries" "TEST_TYPE1" ,
    "ILE_DET_FUNCTION_OF_DISC_COM" VARCHAR2(4000 CHAR)
   )
    NESTED TABLE "Entries" STORE AS "TEST_TYPE3";
</code>```

If I run this locally, I am able to access the table with select * query.
but in server I don't have all the accesses. There I have read-only access to tables. I can only run select * queries.

答: Avoid using  double quotes in DDL scripts. If it is system generated, write a script to eliminate double quotes wherever possible.</p>

Body:
I have a weird issue. In one of the production DB servers we are trying to run

select * from SCHEMA_NAME.TABLE_NAME

When we run the query we are getting invalid identifier error. But when we select a particular column and run the same select query on the same table , we are able to get the output.

Please help me to understand the root cause.

Type created:

create or replace
TYPE           "TEST_TYPE" is object
(
MULTIROW_ID VARCHAR2(100 CHAR),
LOSS_ENTRY_TYPE VARCHAR2(1000 CHAR),
SUB_CATEGORY    VARCHAR2(1000 CHAR),
LOSS_AMOUNT NUMBER,
LOSS_ENTRY_CURR  VARCHAR2(100 CHAR)
);

Type 2 created:

create or replace
TYPE           "TEST_TYPE1" AS TABLE OF TEST_TYPE;

Main create table query using above table type columns:

CREATE TABLE "MS_TEST_DATA"
   (    "REGION" VARCHAR2(4000 CHAR),
    "Entries" "TEST_TYPE1" ,
    "ILE_DET_FUNCTION_OF_DISC_COM" VARCHAR2(4000 CHAR)
   )
    NESTED TABLE "Entries" STORE AS "TEST_TYPE3";

If I run this locally, I am able to access the table with select * query.
but in server I don't have all the accesses. There I have read-only access to tables. I can only run select * queries.


问:
Ant do not delete file with no name like .gitignore .git
I want to use git to delete a folder,the folder contains some file with no name and only have extension,such as .gitignore,.log

I did it as below,and I also tried many other ways,but still can not delete them,can anyone help me?Thanks in advance!

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="test" default="clean">
  <target name="clean">
     <delete>
       <fileset dir="E:\test\tmt"/>
     </delete>
  <echo message="Finished delete file"/>
  </target>
</project>
</code>```

答:
In the following snippet...

```<code><delete>
    <fileset dir="E:\test\tmt"/>
</delete>
</code>```

....gitignore won't be deleted because .gitignore is in Ant's Default Exclude Set.

You can configure Ant to ignore the Default Exclude Set with the defaultexcludes attribute...

```<code><delete>
    <fileset dir="E:\test\tmt" defaultexcludes="false"/>
</delete>
</code>```

...or even better, use the following instead...

```<code><delete dir="E:\test\tmt"/>
</code>```

defaultexcludes isn't needed in this case because the Default Exclude Set only applies to pattern sets such as <fileset>.

Body:
I want to use git to delete a folder,the folder contains some file with no name and only have extension,such as .gitignore,.log

I did it as below,and I also tried many other ways,but still can not delete them,can anyone help me?Thanks in advance!

<?xml version="1.0" encoding="UTF-8"?>
<project name="test" default="clean">
  <target name="clean">
     <delete>
       <fileset dir="E:\test\tmt"/>
     </delete>
  <echo message="Finished delete file"/>
  </target>
</project>

Body:
In the following snippet...

<delete>
    <fileset dir="E:\test\tmt"/>
</delete>

....gitignore won't be deleted because .gitignore is in Ant's Default Exclude Set.

You can configure Ant to ignore the Default Exclude Set with the defaultexcludes attribute...

<delete>
    <fileset dir="E:\test\tmt" defaultexcludes="false"/>
</delete>

...or even better, use the following instead...

<delete dir="E:\test\tmt"/>

defaultexcludes isn't needed in this case because the Default Exclude Set only applies to pattern sets such as <fileset>.


问:
MySQL Query Browser alternatives
I usually use MySQL Query Browser for my queries, but I always run into issues with the connections timing out and the Query Browser locking up, so I'm looking into alternatives.  The new MySQL Workbench is much too slow and heavyweight, I prefer that the Administrative tools and the Query tools are separate (although it wouldn't be as much of a problem if the application wasn't so slow).  I run on Ubuntu 10.04 x64.  I'd like to avoid Windows/Wine-based solutions as much as possible.  I also have had bad experiences (slow, buggy) with JVM-based MySQL applications, although perhaps other people know more lightweight ones.

I want something lightweight that can show me the schemas, tables, and column tree, and present a decent UI for editing tables.

Any suggestions would be appreciated.

答:
Although it does run on Java and may not be the prettiest thing ever, I pretty much always use Squirrel SQL client. If you haven't tried it, I recommend looking at it.
Squirrel SQL Client</p>

ContentLicense: CC BY-SA 2.5

Title: MySQL Query Browser alternatives


问:
Relation between HTTP.sys request queue and IIS app pool
I read this from < IIS 7.0 resource kit >

HTTP.sys maintains a request queue for each worker process. It sends the HTTP requests to the request queue for the worker process that serves the application pool where the requested application is located.
  For each application, HTTP.sys maintains the URI namespace routing table with one entry. The routing table data is used to determine which application pool responds to requests from what parts of the namespace. Each request queue corresponds to  one application pool. And application pool corresponds to one request queues within HTTP.sys and one or more worker processes.

The bold parts confused me.
My understanding is: HTTP.sys matain a request queue for each worker process. An application pool can have one or more worker processes. So an application pool should also corresponds to one or more request queues. Why only one in the bold sentence?

And btw, could anyone give a more clear explanation about the URI namespace routing table? Some examples would be better.

Thanks.

答:
I am struggling with the same question... but I think the process is as follows:

Request intercepted by HTTP.sys

HTTP.sys makes initial contact with WAS

WAS read the ApplicationHost.config and passes it the WWW service.

WWW service configures HTTP.sys (from this point, the HTTP.sys has set up the corresponding application pool queue I guess)

HTTP.sys checks if an worker process is available, (contacts WAS via WWW) if not, the request is stored in the application queue.

=> if a worker process is available, the request is now forwarded to the correct worker pool

If no worker process is available, the request is stored in the application queue. HTTP.sys will now notify WAS (via the WWW service) that a new request has been added to the queue. The WWW service will ask WAS for a worker process. WAS will spawn one and let WWW know that an app pool has been created. Now WWW can pass the request to the corresponding worker process(by adding it to its queue queue). Then WWW will let HTTP.sys know that a worker process is spawned, so the next request, HTTP.sys can forward the request immmediatly...

I am not completely sure if this is technically all correct, so if anyone could correct/confirm this, that would be great!


问:
Perl: Cannot Access Web Service with SSL
This is my first Perl script. I have installed SOAP::Lite using CPAN and it seems to have gone okay.

I'm trying to access a simple HelloWorld .NET web service. I'm getting an error that seems to be related to Perl or SOAP::Lite not being able to verify the SSL certificate.

Although it looks like it's returning a code of 500, I created a Java client that was able to call the web method just fine, so I don't think the problem is on the web service end.

Can anyone point me in the right direction as to how I might get this working?

Script:

```<code>#!/usr/bin/perl

use SOAP::Lite 'trace', 'debug';

$api_ns = "https://www.mydomain.com/edgedev/";
$api_url = "https://www.mydomain.com/edgedev/ws.asmx";
$action = "HelloWorld";

my $soap = SOAP::Lite
                -> readable(1)
                -> ns($api_ns, 'tns')
                -> proxy($api_url)
                -> on_action(sub { return "\"$action\""});

print $soap->HelloWorld()->result;
</code>```

Result

```<code><soap:Envelope
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:tns="https://www.mydomain.com/edgedev/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <tns:HelloWorld xsi:nil="true" />
      </soap:Body>
</soap:Envelope>
SOAP::Transport::HTTP::Client::send_receive: 500 Can't connect to www.mydomain.com:443 (certificate verify failed)
Content-Type: text/plain
Client-Date: Tue, 12 Feb 2013 16:40:28 GMT
Client-Warning: Internal response

Can't connect to www.mydomain.com:443 (certificate verify failed)

You can disable hostname check by setting environment variable PERL_LWP_SSL_VERIFY_HOSTNAME=0

LWP::Protocol::https::Socket: SSL connect attempt failed with unknown errorerror:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed at /usr/lib/perl5/vendor_perl/5.10.0/LWP/Protocol/http.pm line 57.
500 Can't connect to www.mydomain.com:443 (certificate verify failed) at ./soaptest.pl line 15
</code>```

答:
Boy did this work for me!
I threw this into stubmaker.pl and my script which uses the stubmaker.pl output.</p>

```<code>IO::Socket::SSL::set_defaults(SSL_verify_mode => "SSL_VERIFY_NONE");
use SOAP::Lite +trace => qw( debug );

$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}=0;
</code>```

Body:
This is my first Perl script. I have installed SOAP::Lite using CPAN and it seems to have gone okay.

I'm trying to access a simple HelloWorld .NET web service. I'm getting an error that seems to be related to Perl or SOAP::Lite not being able to verify the SSL certificate.

Although it looks like it's returning a code of 500, I created a Java client that was able to call the web method just fine, so I don't think the problem is on the web service end.

Can anyone point me in the right direction as to how I might get this working?

Script:

#!/usr/bin/perl

use SOAP::Lite 'trace', 'debug';

$api_ns = "https://www.mydomain.com/edgedev/";
$api_url = "https://www.mydomain.com/edgedev/ws.asmx";
$action = "HelloWorld";

my $soap = SOAP::Lite
                -> readable(1)
                -> ns($api_ns, 'tns')
                -> proxy($api_url)
                -> on_action(sub { return "\"$action\""});

print $soap->HelloWorld()->result;

Result

<soap:Envelope
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:tns="https://www.mydomain.com/edgedev/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <tns:HelloWorld xsi:nil="true" />
      </soap:Body>
</soap:Envelope>
SOAP::Transport::HTTP::Client::send_receive: 500 Can't connect to www.mydomain.com:443 (certificate verify failed)
Content-Type: text/plain
Client-Date: Tue, 12 Feb 2013 16:40:28 GMT
Client-Warning: Internal response

Can't connect to www.mydomain.com:443 (certificate verify failed)

You can disable hostname check by setting environment variable PERL_LWP_SSL_VERIFY_HOSTNAME=0

LWP::Protocol::https::Socket: SSL connect attempt failed with unknown errorerror:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed at /usr/lib/perl5/vendor_perl/5.10.0/LWP/Protocol/http.pm line 57.
500 Can't connect to www.mydomain.com:443 (certificate verify failed) at ./soaptest.pl line 15

Body:
Boy did this work for me!
I threw this into stubmaker.pl and my script which uses the stubmaker.pl output.

IO::Socket::SSL::set_defaults(SSL_verify_mode => "SSL_VERIFY_NONE");
use SOAP::Lite +trace => qw( debug );

$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}=0;


问:
Text-align isn't working for form element
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

```<code><header>
  <nav>
    <ul>
      <li><a href="">One</a></li>
      <li><a href="">Two</a></li>
      <li><a href="">Three</a></li>
      <li><a href="">Four</a></li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header>
</code>```

My css:

```<code>ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}
</code>```

Jsfiddle: https://jsfiddle.net/dsotpsq4/

答:
Use flex box on your  and add justify-content:space-between;

add this code to your css:

```<code>nav{
  display:flex;
  justify-content:space-between;
  align-items:center;
}
</code>```

See code snippet:

ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}

nav{
  display:flex;
  justify-content:space-between;
  align-items:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    <ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
      <li>Four</li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header></code>```

Body:
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

One

Two

Three

Four

    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>

My css:

ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}

Jsfiddle: https://jsfiddle.net/dsotpsq4/

Body:
Use flex box on your <nav> and add justify-content:space-between;

add this code to your css:

nav{
  display:flex;
  justify-content:space-between;
  align-items:center;
}

See code snippet:

ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}

nav{
  display:flex;
  justify-content:space-between;
  align-items:center;
}

<header>
  <nav>
    <ul>
      <li><a href="">One</a></li>
      <li><a href="">Two</a></li>
      <li><a href="">Three</a></li>
      <li><a href="">Four</a></li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header>


问:
Is there a way to see if there is already a banner in view with ionic content banner?
I have an issue in my app where if there are 2 errors happening at the same time then I get 2 banners overlapping each other and I can't see the error messages. Is there a way to check if there is already an open banner? Angular 1.5.3 and https://github.com/djett41/ionic-content-banner</p>

```<code>var showContentBanner = function (type, data) {
   $ionicContentBanner.show({
                            text: data,
                            type: type,
                            interval: 3000,
                            transition: 'vertical'
                        });
}
</code>```

答:
You have to; before opening a banner; closing it :</p>

```<code>//define a global variable
var contentBannerInstance;

//CLOSE content banner if it exists!!!
      if (contentBannerInstance) {
        contentBannerInstance();
        contentBannerInstance = null;
      }

//open the banner
 contentBannerInstance = $ionicContentBanner.show({ ...})
</code>```

Body:
I have an issue in my app where if there are 2 errors happening at the same time then I get 2 banners overlapping each other and I can't see the error messages. Is there a way to check if there is already an open banner? Angular 1.5.3 and https://github.com/djett41/ionic-content-banner

var showContentBanner = function (type, data) {
   $ionicContentBanner.show({
                            text: data,
                            type: type,
                            interval: 3000,
                            transition: 'vertical'
                        });
}

Body:
You have to; before opening a banner; closing it :

//define a global variable
var contentBannerInstance;

//CLOSE content banner if it exists!!!
      if (contentBannerInstance) {
        contentBannerInstance();
        contentBannerInstance = null;
      }

//open the banner
 contentBannerInstance = $ionicContentBanner.show({ ...})


问:
Remove quotes from a list of strings (that are supposed to be tuples)
I am pulling out a row from a file. Row looks like this:

```<code>['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']
</code>```

Is there a way to convert those strings into tuples? I tried x.strip() for x in row but it didn`t help.

Thanks in advance.

Body:
I am pulling out a row from a file. Row looks like this:

['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']

Is there a way to convert those strings into tuples? I tried x.strip() for x in row but it didn`t help.

Thanks in advance.

Body:
You can do it easily using eval.

# bad practice
a = ['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']
b = [eval(tuple_str.strip()) for tuple_str in a]

UPDATE

As you can see in the comments below, it is safer to use literal_eval.


问:
Azure WCF Service Consume Azure WCF Service
I current have a solution with an Azure WCF service and a Windows Phone 7 project. I can run the development fabric locally and browse to the url (http://127.0.0.1:81/API/V1.svc) of my service fine. When I do Add Service Reference from the Windows Phone application it will discover the service fine, but when I try to view the methods on the service I get the error "Unable to launch the ASP.NET Development Server because port '50149' is in use." If I click OK I get "There was an error downloading metadata from the address. Please verify that you have entered a valid address."

I don't quite understand why it is discovering it on port 50149 since I browse to it on port 81 but I tried using port 81 when adding the service and I got

There was an error downloading 'http://localhost:81/API/V1.svc'.
Unable to connect to the remote server
No connection could be made because the target machine actively refused it 127.0.0.1:81
Metadata contains a reference that cannot be resolved: 'http://localhost:81/API/V1.svc'.
There was no endpoint listening at http://localhost:81/API/V1.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Unable to connect to the remote server
No connection could be made because the target machine actively refused it 127.0.0.1:81
If the service is defined in the current solution, try building the solution and adding the service reference again.

Here is my service model section

```<code><system.serviceModel>
   <services>
     <service name="DocDemon.API.V1">
       <endpoint name="basicHttpBinding" binding="basicHttpBinding" contract="DocDemon.API.IV1" />
     </service>
   </services>
  <behaviors>
   <serviceBehaviors>
    <behavior name="">
     <serviceMetadata httpGetEnabled="true"  />
     <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
   </serviceBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
   <bindings>

   </bindings>
 </system.serviceModel>
</code>```

Do I need to defined and end point in here?

Does it have something to do with the WP7 project and the Azure WCF being in the same solution? (Do I have to have the WCF running when I trying to add service reference from the WP7 app?)

答: I moved the WP7 Application into its own solution and then it was able to detect the web service fine when that application was running in the local DevFabric.  The WP7 application was just unable to find it when they were in the same solution.</p>

Body:
I current have a solution with an Azure WCF service and a Windows Phone 7 project. I can run the development fabric locally and browse to the url (http://127.0.0.1:81/API/V1.svc) of my service fine. When I do Add Service Reference from the Windows Phone application it will discover the service fine, but when I try to view the methods on the service I get the error "Unable to launch the ASP.NET Development Server because port '50149' is in use." If I click OK I get "There was an error downloading metadata from the address. Please verify that you have entered a valid address."

I don't quite understand why it is discovering it on port 50149 since I browse to it on port 81 but I tried using port 81 when adding the service and I got

There was an error downloading 'http://localhost:81/API/V1.svc'.
Unable to connect to the remote server
No connection could be made because the target machine actively refused it 127.0.0.1:81
Metadata contains a reference that cannot be resolved: 'http://localhost:81/API/V1.svc'.
There was no endpoint listening at http://localhost:81/API/V1.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Unable to connect to the remote server
No connection could be made because the target machine actively refused it 127.0.0.1:81
If the service is defined in the current solution, try building the solution and adding the service reference again.

Here is my service model section

<system.serviceModel>
   <services>
     <service name="DocDemon.API.V1">
       <endpoint name="basicHttpBinding" binding="basicHttpBinding" contract="DocDemon.API.IV1" />
     </service>
   </services>
  <behaviors>
   <serviceBehaviors>
    <behavior name="">
     <serviceMetadata httpGetEnabled="true"  />
     <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
   </serviceBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
   <bindings>

   </bindings>
 </system.serviceModel>

Do I need to defined and end point in here?

Does it have something to do with the WP7 project and the Azure WCF being in the same solution? (Do I have to have the WCF running when I trying to add service reference from the WP7 app?)


问:
How can I set valid value to visual bell?
I want to get a visual bell in my mvim. I set :set vb to get the visual bell. However, the flash is not obvious because the flash duration is too short.

According to the help:

In the GUI, 't_vb' defaults to "|f", which inverts the display
      for 20 msec.  If you want to use a different time, use "|40f",
      where 40 is the time in msec.

So the default 20 msec is short, I want to change it to a longer time.

My problem is I couldn't set the value of 't_vb' to a valid value:

I set by press Ctrl-V then Esc then |100f, vim complaint with "Invalid Argument"

I set like :set t_vb="<Esc>|100f", vim did not complain but it didn't work either.

How can I set the value for 't_vb' properly? Thanks!

答:
You need to escape the |

Like so:

:set t_vb=^[\|100f

(where ^[ is entered by using Ctrl-V followed by Esc.)


问:
Why can a .exe file not be launched from this piece of code?
I'm working on a packet analyser program and have encountered some issues:

I want to open an exe file that would capture packets and write to another file.

I want to open it in elevated mode.

I have written somewhat :

```<code>import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;

public class Options extends javax.swing.JFrame {
    private void recActionPerformed(java.awt.event.ActionEvent evt) {
        if (Desktop.isDesktopSupported()) {
            try {
                File myFile = new File(
                        "C:\\Users\\HP\\Documents\\response\\Server_Analyser\\src\\server_analyser\\serverdump\\reader.exe");
                Desktop.getDesktop().open(myFile);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, "Sorry cannot find desired file !");
            }
        }
    }
}
</code>```

答:
The Desktop.getDesktop().open(FILE) command opens the file with the associated program only. This would work for example with a .txt file that is associated with notepad. As a .exe is not associated, as it is a program on its own, it won't work.

To run a .exe from your java code you can use this command

```<code>Process process = new ProcessBuilder("C:\\Users\\HP\\Documents\\response\\Server_Analyser\\src\\server_analyser\\serverdump\\reader.exe").start();
</code>```

This way you also can control the executed program over your java application and e.g. shut it down again.

Body:
I'm working on a packet analyser program and have encountered some issues:

I want to open an exe file that would capture packets and write to another file.

I want to open it in elevated mode.

I have written somewhat :

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;

public class Options extends javax.swing.JFrame {
    private void recActionPerformed(java.awt.event.ActionEvent evt) {
        if (Desktop.isDesktopSupported()) {
            try {
                File myFile = new File(
                        "C:\\Users\\HP\\Documents\\response\\Server_Analyser\\src\\server_analyser\\serverdump\\reader.exe");
                Desktop.getDesktop().open(myFile);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, "Sorry cannot find desired file !");
            }
        }
    }
}

Body:
The Desktop.getDesktop().open(FILE) command opens the file with the associated program only. This would work for example with a .txt file that is associated with notepad. As a .exe is not associated, as it is a program on its own, it won't work.

To run a .exe from your java code you can use this command

Process process = new ProcessBuilder("C:\\Users\\HP\\Documents\\response\\Server_Analyser\\src\\server_analyser\\serverdump\\reader.exe").start();

This way you also can control the executed program over your java application and e.g. shut it down again.


问:
Show differences with another user in TFS
I have Eclipse Neon.

I want to show differences with my file and same file in another computer/user which I have permission to.

Can I do that? I know it's possible in Intellij.

答:
This depends the user is using a sever workspace or a local workspace. You could use tf status command to display information about pending changes to files and folders in one or more workspaces.

You can also use this command to view pending changes in a remote
  server workspace (for example, changes made by another user on another
  dev machine) by using the /collection, /user, and /workspace
  options. However, you cannot view pending changes in a remote local
  workspace.

Then you could just use a diff tool to show the difference.


问:
Lombok Builder with defaults in Spring Data
I have the following (simplified) class:

```<code>@Entity
@Data
@Builder
@NoArgsConstructor // @Builder creates the all-args version but I need this one elsewhere.
@AllArgsConstructor(access = AccessLevel.PRIVATE) // Having @NoArgsConstructor disables the @AllArgsConstructor needed by @Builder unless I have this explicitly applied
public class MyClass {

  // ...
  @Builder.Default
  private String foo = "Some Default Value"
  // ...

}
</code>```

This works fine in the general case, but a problem comes about when this Entity gets built by Spring (specifically Spring Data Repository in response to a REST request to create it).  Spring sees the all-args constructor and uses it, setting a null value for foo (in this case it wasn't set in the POST data) and I end up with a null value for foo instead of the expected "Some Default Value".  The @Builder.Default.

It does not work to simply create the setter and prevent nulls.  I could write out the AllArgsConstructor explicitly, but that (somewhat) defeats the purpose of Lombok to some extent.  Not a horrible solution, but not ideal.

Can anyone think of any workarounds for this?

答:
I know you can specify default values with the non-lombok default values. I haven't tried it with this particular case, but its worth a shot.

@Value("#{prop['my.property'] ?: 12345}")

Maybe you should try using the RequiredArgs Constructor which only specifies a constructor that uses "one argument per final / non-null field" and that won't override the var.

https://projectlombok.org/features/constructor

Body:
I have the following (simplified) class:

@Entity
@Data
@Builder
@NoArgsConstructor // @Builder creates the all-args version but I need this one elsewhere.
@AllArgsConstructor(access = AccessLevel.PRIVATE) // Having @NoArgsConstructor disables the @AllArgsConstructor needed by @Builder unless I have this explicitly applied
public class MyClass {

  // ...
  @Builder.Default
  private String foo = "Some Default Value"
  // ...

}

This works fine in the general case, but a problem comes about when this Entity gets built by Spring (specifically Spring Data Repository in response to a REST request to create it).  Spring sees the all-args constructor and uses it, setting a null value for foo (in this case it wasn't set in the POST data) and I end up with a null value for foo instead of the expected "Some Default Value".  The @Builder.Default.

It does not work to simply create the setter and prevent nulls.  I could write out the AllArgsConstructor explicitly, but that (somewhat) defeats the purpose of Lombok to some extent.  Not a horrible solution, but not ideal.

Can anyone think of any workarounds for this?


问:
How to get heap dump from java app running by HashiCorp Nomad?
I have java application that running by HashiCorp Nomad. At process status output I have nomad executor process running by root and java app process running by nobody.

When I try execute command:
jmap -dump:format=b,file=filename.bin <app_pid>

I got message:

Unable to open socket file: target process not responding or HotSpot VM not loaded
The -F option can be used when the target process is not responding

When I try execute command: jmap -dump:format=b,file=filename.bin <app_pid> -F

I got next trace:

Attaching to core -F from executable 5584, please wait...
Error attaching to core file: cannot open binary file
sun.jvm.hotspot.debugger.DebuggerException: cannot open binary file
        at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.attach0(Native Method)
        at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.attach(LinuxDebuggerLocal.java:286)
        at sun.jvm.hotspot.HotSpotAgent.attachDebugger(HotSpotAgent.java:673)
        at sun.jvm.hotspot.HotSpotAgent.setupDebuggerLinux(HotSpotAgent.java:611)
        at sun.jvm.hotspot.HotSpotAgent.setupDebugger(HotSpotAgent.java:337)
        at sun.jvm.hotspot.HotSpotAgent.go(HotSpotAgent.java:304)
        at sun.jvm.hotspot.HotSpotAgent.attach(HotSpotAgent.java:156)
        at sun.jvm.hotspot.tools.Tool.start(Tool.java:191)
        at sun.jvm.hotspot.tools.Tool.execute(Tool.java:118)
        at sun.jvm.hotspot.tools.HeapDumper.main(HeapDumper.java:83)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sun.tools.jmap.JMap.runTool(JMap.java:201)
        at sun.tools.jmap.JMap.main(JMap.java:130)

答:
jmap without -F should be run by the same user as the target Java process (nobody in your case).

jmap -F should be run by root, and -F argument should precede <app_pid>:

```<code>jmap -dump:format=b,file=filename.bin -F <app_pid>
</code>```

See details in this answers.

Body:
jmap without -F should be run by the same user as the target Java process (nobody in your case).

jmap -F should be run by root, and -F argument should precede <app_pid>:

jmap -dump:format=b,file=filename.bin -F <app_pid>

See details in this answers.


问:
Add column to table and then update it inside transaction
I am creating a script that will be run in a MS SQL server. This script will run multiple statements and needs to be transactional, if one of the statement fails the overall execution is stopped and any changes are rolled back.

I am having trouble creating this transactional model when issuing ALTER TABLE statements to add columns to a table and then updating the newly added column. In order to access the newly added column right away, I use a GO command to execute the ALTER TABLE statement, and then call my UPDATE statement. The problem I am facing is that I cannot issue a GO command inside an IF statement. The IF statement is important within my transactional model. This is a sample code of the script I am trying to run. Also notice that issuing a  GO command, will discard the @errorCode variable, and will need to be declared down in the code before being used (This is not in the code below).

```<code>BEGIN TRANSACTION

DECLARE @errorCode INT
SET @errorCode = @@ERROR

-- **********************************
-- * Settings
-- **********************************
IF @errorCode = 0
BEGIN
 BEGIN TRY
  ALTER TABLE Color ADD [CodeID] [uniqueidentifier] NOT NULL DEFAULT ('{00000000-0000-0000-0000-000000000000}')
  GO
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

IF @errorCode = 0
BEGIN
 BEGIN TRY
  UPDATE Color
  SET CodeID= 'B6D266DC-B305-4153-A7AB-9109962255FC'
  WHERE [Name] = 'Red'
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

-- **********************************
-- * Check @errorCode to issue a COMMIT or a ROLLBACK
-- **********************************
IF @errorCode = 0
BEGIN
 COMMIT
 PRINT 'Success'
END
ELSE
BEGIN
 ROLLBACK
 PRINT 'Failure'
END
</code>```

So what I would like to know is how to go around this problem, issuing ALTER TABLE statements to add a column and then updating that column, all within a script executing as a transactional unit.

答:
I almost agree with Remus but you can do this with SET XACT_ABORT ON and XACT_STATE

Basically

SET XACT_ABORT ON will abort each batch on error and ROLLBACK

Each batch is separated by GO

Execution jumps to the next batch on error

Use XACT_STATE() will test if the transaction is still valid

Tools like Red Gate SQL Compare use this technique

Something like:

```<code>SET XACT_ABORT ON
GO
BEGIN TRANSACTION
GO

IF COLUMNPROPERTY(OBJECT_ID('Color'), 'CodeID', ColumnId) IS NULL
   ALTER TABLE Color ADD CodeID [uniqueidentifier] NULL
GO

IF XACT_STATE() = 1
  UPDATE Color
  SET CodeID= 'B6D266DC-B305-4153-A7AB-9109962255FC'
  WHERE [Name] = 'Red'
GO

IF XACT_STATE() = 1
 COMMIT TRAN
--else would be rolled back
</code>```

I've also removed the default. No value = NULL for GUID values. It's meant to be unique: don't try and set every row to all zeros because it will end in tears...

Body:
I am creating a script that will be run in a MS SQL server. This script will run multiple statements and needs to be transactional, if one of the statement fails the overall execution is stopped and any changes are rolled back.

I am having trouble creating this transactional model when issuing ALTER TABLE statements to add columns to a table and then updating the newly added column. In order to access the newly added column right away, I use a GO command to execute the ALTER TABLE statement, and then call my UPDATE statement. The problem I am facing is that I cannot issue a GO command inside an IF statement. The IF statement is important within my transactional model. This is a sample code of the script I am trying to run. Also notice that issuing a  GO command, will discard the @errorCode variable, and will need to be declared down in the code before being used (This is not in the code below).

BEGIN TRANSACTION

DECLARE @errorCode INT
SET @errorCode = @@ERROR

-- **********************************
-- * Settings
-- **********************************
IF @errorCode = 0
BEGIN
 BEGIN TRY
  ALTER TABLE Color ADD [CodeID] [uniqueidentifier] NOT NULL DEFAULT ('{00000000-0000-0000-0000-000000000000}')
  GO
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

IF @errorCode = 0
BEGIN
 BEGIN TRY
  UPDATE Color
  SET CodeID= 'B6D266DC-B305-4153-A7AB-9109962255FC'
  WHERE [Name] = 'Red'
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

-- **********************************
-- * Check @errorCode to issue a COMMIT or a ROLLBACK
-- **********************************
IF @errorCode = 0
BEGIN
 COMMIT
 PRINT 'Success'
END
ELSE
BEGIN
 ROLLBACK
 PRINT 'Failure'
END

So what I would like to know is how to go around this problem, issuing ALTER TABLE statements to add a column and then updating that column, all within a script executing as a transactional unit.

Body:
I almost agree with Remus but you can do this with SET XACT_ABORT ON and XACT_STATE

Basically

SET XACT_ABORT ON will abort each batch on error and ROLLBACK

Each batch is separated by GO

Execution jumps to the next batch on error

Use XACT_STATE() will test if the transaction is still valid

Tools like Red Gate SQL Compare use this technique

Something like:

SET XACT_ABORT ON
GO
BEGIN TRANSACTION
GO

IF COLUMNPROPERTY(OBJECT_ID('Color'), 'CodeID', ColumnId) IS NULL
   ALTER TABLE Color ADD CodeID [uniqueidentifier] NULL
GO

IF XACT_STATE() = 1
  UPDATE Color
  SET CodeID= 'B6D266DC-B305-4153-A7AB-9109962255FC'
  WHERE [Name] = 'Red'
GO

IF XACT_STATE() = 1
 COMMIT TRAN
--else would be rolled back

I've also removed the default. No value = NULL for GUID values. It's meant to be unique: don't try and set every row to all zeros because it will end in tears...


问:
Spring: get current user through injection
Currently I am getting the user with the usual

```<code>SecurityContextHolder.getContext().getAuthentication().getPrincipal
</code>```

I wonder if it is possible to get it through the bean factory, like this

```<code>@Service
class UserProvider implements BeanFactoryAware {
    BeanFactory beanFactory;

    public Principal get(){
        return (Principal) beanFactory.getBean("Principal");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
</code>```

Does Spring store a session scoped bean containing the current authenticated user?

答:
You can use your custom bean post processor in conjunction with dynamic proxy to achieve this.

Something like:

```<code>@SpringBootApplication
public class So44435897Application {

    public static void main(String[] args) {
        SpringApplication.run(So44435897Application.class, args);
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface ApplicationUser { }

    @Component
    public static class CurrentUserBeanPostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            ReflectionUtils.doWithFields(bean.getClass(), field -> {
                ReflectionUtils.makeAccessible(field);
                if (field.getAnnotation(ApplicationUser.class) != null) {
                    final Object proxyInstance = Proxy.newProxyInstance(bean.getClass().getClassLoader(),
                            new Class[] { UserDetails.class }, (proxy, method, args) -> {
                                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                                if (authentication != null && authentication.isAuthenticated()) {
                                    final Object principal = authentication.getPrincipal();
                                    return method.invoke(principal, args);
                                }
                                throw new NullPointerException();
                            });
                    field.set(bean, proxyInstance);
                }
            });
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    }

    @RestController
    public static class HomeController {
        final UserService userService;

        @Autowired
        public HomeController(UserService userService) {
            this.userService = userService;
        }

        @GetMapping
        public String me() {
            return userService.getName();
        }
    }

    @Service
    public static class UserService {
        @ApplicationUser
        UserDetails user;

        String getName() {
            return user.getUsername();
        }
    }
}
</code>```

=>

```<code>$ curl -u admin:admin -XGET 'localhost:8080'
admin%
</code>```

Body:
Currently I am getting the user with the usual

SecurityContextHolder.getContext().getAuthentication().getPrincipal

I wonder if it is possible to get it through the bean factory, like this

@Service
class UserProvider implements BeanFactoryAware {
    BeanFactory beanFactory;

    public Principal get(){
        return (Principal) beanFactory.getBean("Principal");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}

Does Spring store a session scoped bean containing the current authenticated user?

Body:
You can use your custom bean post processor in conjunction with dynamic proxy to achieve this.

Something like:

@SpringBootApplication
public class So44435897Application {

    public static void main(String[] args) {
        SpringApplication.run(So44435897Application.class, args);
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface ApplicationUser { }

    @Component
    public static class CurrentUserBeanPostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            ReflectionUtils.doWithFields(bean.getClass(), field -> {
                ReflectionUtils.makeAccessible(field);
                if (field.getAnnotation(ApplicationUser.class) != null) {
                    final Object proxyInstance = Proxy.newProxyInstance(bean.getClass().getClassLoader(),
                            new Class[] { UserDetails.class }, (proxy, method, args) -> {
                                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                                if (authentication != null && authentication.isAuthenticated()) {
                                    final Object principal = authentication.getPrincipal();
                                    return method.invoke(principal, args);
                                }
                                throw new NullPointerException();
                            });
                    field.set(bean, proxyInstance);
                }
            });
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    }

    @RestController
    public static class HomeController {
        final UserService userService;

        @Autowired
        public HomeController(UserService userService) {
            this.userService = userService;
        }

        @GetMapping
        public String me() {
            return userService.getName();
        }
    }

    @Service
    public static class UserService {
        @ApplicationUser
        UserDetails user;

        String getName() {
            return user.getUsername();
        }
    }
}

=>

$ curl -u admin:admin -XGET 'localhost:8080'
admin%


问:
Create New Objects vs Overwrite Existing Object (Performance)
I have to create a huge amount of slightly different objects for testing. All have their properties altered to be distinct object, but once I create the object & do something with it, I no longer need it.
Should I create a new local object or, just overwrite & reassign the object that exists outside scope of the loop?

New (local) objects

```<code>int testCases = 10;
for(int i=0; i<testCases; i++){
    TestObject localObject = new TestObject();  //local variable for the loop
    //change properties & do stuff with the test object
}
</code>```

Reassign/Overwrite Existing object

```<code>TestObject myObject;
int testCases = 10;
for(int i=0; i<testCases; i++){
    myObject = new TestObject();    //reassign object that exists outside the loop
    //change properties & do stuff with the test object
}
</code>```

The "change properties & do stuff" isn't that important, I know how to create the different versions of my object, just not sure if I should be destroying them each iteration.

答:
There is no functional difference between the two code snippets you posted. The allocation is happening on every loop iteration regardless of where you put the local variable in the code.

If you want to save on allocations, though, I can think of two possible solutions for you:

Use struct instead of class - This causes only stack space to be used instead of the heap. Only heap usage contributes to GC pressure. If you are passing around the struct a lot, though, you will need to pass by ref instead of by value to avoid the copying. Structs also "want" to be immutable, so you are a little restricted in how you use them, but not usually a big deal. See here if you need to know more about structs/value types.

Use object reset/reuse semantics - instead of allocating a new object and filling it with data, just refill the same object with data over and over, without ever reallocating it. You essentially treat the object as a pooled object. Pooling can get complicated fast in non-trivial situations, but it's a good way to avoid additional memory pressure in some situations.

ContentLicense: CC BY-SA 4.0

Body:
I have to create a huge amount of slightly different objects for testing. All have their properties altered to be distinct object, but once I create the object & do something with it, I no longer need it.
Should I create a new local object or, just overwrite & reassign the object that exists outside scope of the loop?

New (local) objects

int testCases = 10;
for(int i=0; i<testCases; i++){
    TestObject localObject = new TestObject();  //local variable for the loop
    //change properties & do stuff with the test object
}

Reassign/Overwrite Existing object

TestObject myObject;
int testCases = 10;
for(int i=0; i<testCases; i++){
    myObject = new TestObject();    //reassign object that exists outside the loop
    //change properties & do stuff with the test object
}

The "change properties & do stuff" isn't that important, I know how to create the different versions of my object, just not sure if I should be destroying them each iteration.


问:
python exit code from subprocess
I have one python content as below, and why I got ipmitool completion code is 00, but always return "failed"?</p>

```<code>import subprocess
def sdr(hostname,username,password):
    IPMI_SERVER=hostname
    IPMI_USERNAME=username
    IPMI_PASSWORD=password
    p = subprocess.run(["ipmitool.exe", "-H", IPMI_SERVER, "-U", IPMI_USERNAME, "-P", IPMI_PASSWORD, "-I", "lanplus", "raw", "0x06","0x01"], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    #p = subprocess.run(["ipmitool.exe -H 192.168.2.140 -I lanplus -U admin -P admin sdr elist full"], stdout=subprocess.PIPE)
    output= p.returncode
    return output

if sdr("192.168.2.140","admin","admin"):
    print ("successfully")
else:
    print ("failed")
</code>```

答: The p.returncode is an int, so if it is successful it will be 0, which is False in your if statement, therefore it will execute print("failed")

Title: python exit code from subprocess

Body:
I have one python content as below, and why I got ipmitool completion code is 00, but always return "failed"?

import subprocess
def sdr(hostname,username,password):
    IPMI_SERVER=hostname
    IPMI_USERNAME=username
    IPMI_PASSWORD=password
    p = subprocess.run(["ipmitool.exe", "-H", IPMI_SERVER, "-U", IPMI_USERNAME, "-P", IPMI_PASSWORD, "-I", "lanplus", "raw", "0x06","0x01"], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    #p = subprocess.run(["ipmitool.exe -H 192.168.2.140 -I lanplus -U admin -P admin sdr elist full"], stdout=subprocess.PIPE)
    output= p.returncode
    return output

if sdr("192.168.2.140","admin","admin"):
    print ("successfully")
else:
    print ("failed")


问:
Django render redirect to page with changing url
I am creating a custom login for my django application and problem occurs when i click logout on template I programmed it so it go to index page but the url in the browser remains http://127.0.0.1:8000/logout/ even reaching index page. I want it to become http://127.0.0.1:8000/ .

views.py

```<code>def logout(request):
    try:
        del request.session['uid']
        return render(request, 'home.html')
    except:
        pass
    return render(request, 'home.html')

def home_page(request):
    return render(request, 'home.html')
</code>```

template

```<code> <p>
    Publisher Dashboard, Welcome {{ user.name }}.
    <a href="{% url 'logout' %}" class="btn btn-primary">Logout</a>
</p>
</code>```

urls.py

```<code>from django.conf.urls import url
from django.contrib import admin
from mainapp import views

urlpatterns = [
url(r'^$', views.home_page, name='homepage'),
url(r'^registration/$', views.signup_user, name='signup_user'),
....
url(r'^logout/$', views.logout, name='logout'),
]
</code>```

答:
Currently you are rendering the 'home.html template, instead of redirecting the user to the homepage.

If you want to redirect then you should return an HttpResponseRedirect response, or use the redirect shortcut.

```<code>from django.shortcuts import redirect

def logout(request):
    ...
    return redirect('/')
</code>```

Body:
I am creating a custom login for my django application and problem occurs when i click logout on template I programmed it so it go to index page but the url in the browser remains http://127.0.0.1:8000/logout/ even reaching index page. I want it to become http://127.0.0.1:8000/ .

views.py

def logout(request):
    try:
        del request.session['uid']
        return render(request, 'home.html')
    except:
        pass
    return render(request, 'home.html')

def home_page(request):
    return render(request, 'home.html')

template

    Publisher Dashboard, Welcome {{ user.name }}.
    Logout

urls.py

from django.conf.urls import url
from django.contrib import admin
from mainapp import views

urlpatterns = [
url(r'^$', views.home_page, name='homepage'),
url(r'^registration/$', views.signup_user, name='signup_user'),
....
url(r'^logout/$', views.logout, name='logout'),
]

Body:
Currently you are rendering the 'home.html template, instead of redirecting the user to the homepage.

If you want to redirect then you should return an HttpResponseRedirect response, or use the redirect shortcut.

from django.shortcuts import redirect

def logout(request):
    ...
    return redirect('/')


问:
Android Studio error 13=permission denied in linux
i am using android studio latest version in linux(elementary luna to be specific). I installed jdk, android studio and sdk successfully, android studio opens us perfectly and even i can work on my app. but when i bulid app it gives error 13: permission denied and it opens a black circle image png in new tab.

```<code>Information:Gradle tasks [:app:compileDebugSources]
:app:preBuild
:app:preDebugBuild
:app:checkDebugManifest
:app:preReleaseBuild
:app:prepareComAndroidSupportAppcompatV72103Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42103Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources
:app:mergeDebugResources FAILED
/home/suUs12/AndroidStudioProjects/MyApplication/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/drawable-mdpi/abc_btn_radio_to_on_mtrl_000.png
Error:Error: Cannot run program "/home/suUs12/Android/Sdk/build-tools/21.1.2/aapt": error=13, Permission denied
Error:Execution failed for task ':app:mergeDebugResources'.
> /home/suUs12/AndroidStudioProjects/MyApplication/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/drawable-mdpi/abc_btn_radio_to_on_mtrl_000.png:
Error: Cannot run program "/home/suUs12/Android/Sdk/build-tools/21.1.2/aapt": error=13, Permission denied
Information:BUILD FAILED
Information:Total time: 30.305 secs
Information:2 errors
Information:0 warnings
</code>```

i dont understand the problem. i did searched on internet and tried many methods like

changing permissions with chmod:

chmod +x /home/alex/android-studio/sdk/build-tools/android-4.2.2/dx

it executes successfully but with no effect on the problem itself,

2.closing and re-importing project,

3.i also tried this,

```<code>sudo apt-get install lib32stdc++
sudo apt-get install lib32z1
</code>```

and i get following result

```<code>suUs12@suUs12:~/Android/Sdk$ sudo apt-get install lib32stdc++6
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package lib32stdc++6 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'lib32stdc++6' has no installation candidate
</code>```

i guess this is not issue since my system is 32 bit and this is for 64 bit systems.

Can anyone help? since i am really counting on it.

my system configurations:(if useful)

-OS Version: 0.2.1 "Luna" ( 32-bit ),
Built on: Ubuntu 12.04 ( "Precise" )

-installed OpenJdk 7:
java version "1.6.0_34"
OpenJDK Runtime Environment (IcedTea6 1.13.6) (6b34-1.13.6-1ubuntu0.12.04.1)

OpenJDK Client VM (build 23.25-b01, mixed mode, sharing)

答: I Solved This Problem By :  Right Click On Main Folder Like Android-Studio and then Go to Properties and then Click On Permission and check CheckBox For Allow Executing File As a Program Then Run Android Studio In Terminal :)</p>

Body:
i am using android studio latest version in linux(elementary luna to be specific). I installed jdk, android studio and sdk successfully, android studio opens us perfectly and even i can work on my app. but when i bulid app it gives error 13: permission denied and it opens a black circle image png in new tab.

Information:Gradle tasks [:app:compileDebugSources]
:app:preBuild
:app:preDebugBuild
:app:checkDebugManifest
:app:preReleaseBuild
:app:prepareComAndroidSupportAppcompatV72103Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42103Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources
:app:mergeDebugResources FAILED
/home/suUs12/AndroidStudioProjects/MyApplication/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/drawable-mdpi/abc_btn_radio_to_on_mtrl_000.png
Error:Error: Cannot run program "/home/suUs12/Android/Sdk/build-tools/21.1.2/aapt": error=13, Permission denied
Error:Execution failed for task ':app:mergeDebugResources'.
> /home/suUs12/AndroidStudioProjects/MyApplication/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/drawable-mdpi/abc_btn_radio_to_on_mtrl_000.png:
Error: Cannot run program "/home/suUs12/Android/Sdk/build-tools/21.1.2/aapt": error=13, Permission denied
Information:BUILD FAILED
Information:Total time: 30.305 secs
Information:2 errors
Information:0 warnings

i dont understand the problem. i did searched on internet and tried many methods like

changing permissions with chmod:

chmod +x /home/alex/android-studio/sdk/build-tools/android-4.2.2/dx

it executes successfully but with no effect on the problem itself,

2.closing and re-importing project,

3.i also tried this,

sudo apt-get install lib32stdc++
sudo apt-get install lib32z1

and i get following result

suUs12@suUs12:~/Android/Sdk$ sudo apt-get install lib32stdc++6
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package lib32stdc++6 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'lib32stdc++6' has no installation candidate

i guess this is not issue since my system is 32 bit and this is for 64 bit systems.

Can anyone help? since i am really counting on it.

my system configurations:(if useful)

-OS Version: 0.2.1 "Luna" ( 32-bit ),
Built on: Ubuntu 12.04 ( "Precise" )

-installed OpenJdk 7:
java version "1.6.0_34"
OpenJDK Runtime Environment (IcedTea6 1.13.6) (6b34-1.13.6-1ubuntu0.12.04.1)

OpenJDK Client VM (build 23.25-b01, mixed mode, sharing)


问:
Cannot access native WpfButton in UI Test, get Exception: System.NotSupportedExceptions
I'm trying to access a native Wpf control property within the UI test framework (MS UI Tests). My specific issue is that, when I try accessing a WpfButton control property (e.g., IsVisible) using the function call WpfButtonObject.GetProperty("IsVisible"), the exception "System.NotSupportedExceptions" occurs. I'm able to see this WpfButton property using Snoop; so, I'm wondering if the GetProperty call is correct? Please see my related code below. Thanks for any insight.

UIMap.cs: Test function for a pressing a WpfButton. Please note the call uIButton.GetPropery("IsVisible"). This is where the exception occurs:

```<code>public void PressButtonTest()
    {
        WpfButton uIButton = this.UIMainWindowWindow.UIButtonButton;
        object state = uIButton.GetProperty("IsVisible"); // Throws SystemNotSupportedException exception
        bool stateBool = (bool)state;
        Assert.IsTrue(stateBool, "Button is visible");
        PressButton();
    }
</code>```

UIMap.Designer.cs: WpfButton property:

```<code>public WpfButton UIButtonButton
    {
        get
        {
            if ((this.mUIButtonButton == null))
            {
                this.mUIButtonButton = new WpfButton(this);
                #region Search Criteria
                this.mUIButtonButton.SearchProperties[WpfButton.PropertyNames.AutomationId] = "button";
                this.mUIButtonButton.WindowTitles.Add("MainWindow");
                #endregion
            }
            return this.mUIButtonButton;
        }
    }
</code>```

答:
Here's what I've done:

```<code>Point point;
bool isClickable = uIButton.TryGetClickablePoint(out point);
Assert.IsTrue(isClickable, "No clickable point was found, button not visible.");
</code>```

By the way, your message in your Assert (2nd parameter) is inaccurate because it's only used on fail... in your case, when the button would not be visible. So in your output it would say "Button is visible" on failure when in fact it was not.

Body:
I'm trying to access a native Wpf control property within the UI test framework (MS UI Tests). My specific issue is that, when I try accessing a WpfButton control property (e.g., IsVisible) using the function call WpfButtonObject.GetProperty("IsVisible"), the exception "System.NotSupportedExceptions" occurs. I'm able to see this WpfButton property using Snoop; so, I'm wondering if the GetProperty call is correct? Please see my related code below. Thanks for any insight.

UIMap.cs: Test function for a pressing a WpfButton. Please note the call uIButton.GetPropery("IsVisible"). This is where the exception occurs:

public void PressButtonTest()
    {
        WpfButton uIButton = this.UIMainWindowWindow.UIButtonButton;
        object state = uIButton.GetProperty("IsVisible"); // Throws SystemNotSupportedException exception
        bool stateBool = (bool)state;
        Assert.IsTrue(stateBool, "Button is visible");
        PressButton();
    }

UIMap.Designer.cs: WpfButton property:

public WpfButton UIButtonButton
    {
        get
        {
            if ((this.mUIButtonButton == null))
            {
                this.mUIButtonButton = new WpfButton(this);
                #region Search Criteria
                this.mUIButtonButton.SearchProperties[WpfButton.PropertyNames.AutomationId] = "button";
                this.mUIButtonButton.WindowTitles.Add("MainWindow");
                #endregion
            }
            return this.mUIButtonButton;
        }
    }

Body:
Here's what I've done:

Point point;
bool isClickable = uIButton.TryGetClickablePoint(out point);
Assert.IsTrue(isClickable, "No clickable point was found, button not visible.");

By the way, your message in your Assert (2nd parameter) is inaccurate because it's only used on fail... in your case, when the button would not be visible. So in your output it would say "Button is visible" on failure when in fact it was not.


问:
Laravel destroy won't delete data from database
Trying to delete an entry from database using the following in Laravel 5.4 without success.

My View

```<code>{!! Form::open(['method' => 'DELETE', 'route' => ['faculty.delete', $faculty->id]]) !!}
    <button type="submit" class="btn btn-danger btn-sm">Delete</button>
{!! Form::close() !!}
</code>```

My Route

```<code>Route::delete('faculty/delete/{id}', 'FacultyController@destroy')->name('faculty.delete');//delete faculty
</code>```

My Controller

```<code>public function destroy(Faculty $faculty)
{
    //Log::info($faculty);
    $faculty->delete();
    return redirect('faculties/faculty');
}
</code>```

The log in the controller returns an empty value when I allow it to run.

The problem is that the code does not delete the item from the table.

答:
You need to change faculty/delete/{id} to faculty/delete/{faculty}.

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.

Since the $faculty variable is type-hinted as the App\Faculty Eloquent model and the variable name matches the {faculty} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.

https://laravel.com/docs/5.4/routing#route-model-binding

Body:
Trying to delete an entry from database using the following in Laravel 5.4 without success.

My View

{!! Form::open(['method' => 'DELETE', 'route' => ['faculty.delete', $faculty->id]]) !!}
    <button type="submit" class="btn btn-danger btn-sm">Delete</button>
{!! Form::close() !!}

My Route

Route::delete('faculty/delete/{id}', 'FacultyController@destroy')->name('faculty.delete');//delete faculty

My Controller

public function destroy(Faculty $faculty)
{
    //Log::info($faculty);
    $faculty->delete();
    return redirect('faculties/faculty');
}

The log in the controller returns an empty value when I allow it to run.

The problem is that the code does not delete the item from the table.


问:
Spring @RestController won't product application/xml
I have a @RestController with the following method

```<code>@RequestMapping(path = "/thing", method = RequestMethod.GET,
    produces = { MediaType.APPLICATION_XML_VALUE })
public List<Thing> listThings() {
    return thingMapper.listThings();
}
</code>```

But when I make a GET request with Accept:application/xml in the header, the Content-Length of the response is 0 and it doesn't produce anything. I know that data is being returned by my query and if I remove the produces attribute and make a plain get request it returns the data as json....I just cant get it to produce xml. Any ideas?

EDIT: I should mention that I am using the Spring Boot web starter

答:
If you have the Jackson XML extension (jackson-dataformat-xml) on the
  classpath, it will be used to render XML responses and the very same
  example as we used for JSON would work. To use it, add the following
  dependency to your project:

```<code><dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>
</code>```

See here

Body:
I have a @RestController with the following method

@RequestMapping(path = "/thing", method = RequestMethod.GET,
    produces = { MediaType.APPLICATION_XML_VALUE })
public List<Thing> listThings() {
    return thingMapper.listThings();
}

But when I make a GET request with Accept:application/xml in the header, the Content-Length of the response is 0 and it doesn't produce anything. I know that data is being returned by my query and if I remove the produces attribute and make a plain get request it returns the data as json....I just cant get it to produce xml. Any ideas?

EDIT: I should mention that I am using the Spring Boot web starter

Body:
If you have the Jackson XML extension (jackson-dataformat-xml) on the
  classpath, it will be used to render XML responses and the very same
  example as we used for JSON would work. To use it, add the following
  dependency to your project:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

See here


问:
Error (10170): Verilog HDL syntax error at TrafficLight.v(59) near text "endcase"; expecting "end"
I am new to veriloghdl and I am getting this error in verilog hdl

```<code>Error (10170): Verilog HDL syntax error at TrafficLight.v(59) near text "endcase";  expecting "end"
</code>```

Can anyone tell me what is wrong?

my code is

```<code>module TrafficLight(t, state, next_state, clk, out);

input t, clk;
output out;
localparam s0=3'b000, s1=3'b001, s2=3'b010, s3=3'b011, s4=3'b100, s5=3'b101;
reg[2:0] state, next_state, tt;
always@(posedge clk)
    begin
    case(state)
        3'b000:
            if(tt < 5)
                next_state = s0;
            else
                begin
                next_state = s1;
                assign out [5:0] = 6'b100001;
                end
        3'b001:
            if(tt < 1)
                next_state = s1;
            else
            begin
                next_state = s2;
                assign out [5:0] = 6'b010001;
            end
        3'b010:
            if(tt < 1)
                next_state = s2;
            else
            begin
                next_state = s3;
                assign out [5:0] = 6'b001001;
            end
        3'b011:
            if(tt < 5)
                next_state = s3;
            else
            begin
                next_state = s4;
                assign out [5:0] = 6'b001100;
            end
        3'b100:
            if(tt < 1)
                next_state = s4;
            else
            begin
                next_state = s5;
                assign out [5:0] = 6'b001010;
            end
        3'b101:
            if(tt < 1)
                next_state = s0;
            else
                begin
                next_state = s5;
                assign out [5:0] = 6'b001001;
                end
    endcase

    always@(posedge clk);
        begin
        state = next_state;
        tt = tt - 1;
        end

endmodule
</code>```

The error occured I think on the lines endcase and endmodule. I think I would have to close them with something.

答:
There are a couple of errors in your code -

You missed the "end" after the "endcase" statement. The end is required for the begin block just before the case statement.

You have added ";" in the always block declaration.

```<code>always@(posedge clk);
    begin
    state = next_state;
    tt = tt - 1;
    end
</code>```

There is no need of an ";" in the always block.

```<code>module TrafficLight(t, state, next_state, clk, out);

input t, clk;
output out;
localparam s0=3'b000, s1=3'b001, s2=3'b010, s3=3'b011, s4=3'b100, s5=3'b101;
reg[2:0] state, next_state, tt;
</code>```

In the above snippet I see that you have added "state" and "next_state" as ports to the module but haven't assigned any direction to them. Either remove them as ports or make them as "input" or "output".

You would also need to remove the "assign" statement when driving the out reg. Since it is inside a procedural block you don't need an "assign" here.

You can find all the updates to your code here

Body:
I am new to veriloghdl and I am getting this error in verilog hdl

Error (10170): Verilog HDL syntax error at TrafficLight.v(59) near text "endcase";  expecting "end"

Can anyone tell me what is wrong?

my code is

module TrafficLight(t, state, next_state, clk, out);

input t, clk;
output out;
localparam s0=3'b000, s1=3'b001, s2=3'b010, s3=3'b011, s4=3'b100, s5=3'b101;
reg[2:0] state, next_state, tt;
always@(posedge clk)
    begin
    case(state)
        3'b000:
            if(tt < 5)
                next_state = s0;
            else
                begin
                next_state = s1;
                assign out [5:0] = 6'b100001;
                end
        3'b001:
            if(tt < 1)
                next_state = s1;
            else
            begin
                next_state = s2;
                assign out [5:0] = 6'b010001;
            end
        3'b010:
            if(tt < 1)
                next_state = s2;
            else
            begin
                next_state = s3;
                assign out [5:0] = 6'b001001;
            end
        3'b011:
            if(tt < 5)
                next_state = s3;
            else
            begin
                next_state = s4;
                assign out [5:0] = 6'b001100;
            end
        3'b100:
            if(tt < 1)
                next_state = s4;
            else
            begin
                next_state = s5;
                assign out [5:0] = 6'b001010;
            end
        3'b101:
            if(tt < 1)
                next_state = s0;
            else
                begin
                next_state = s5;
                assign out [5:0] = 6'b001001;
                end
    endcase

    always@(posedge clk);
        begin
        state = next_state;
        tt = tt - 1;
        end

endmodule

The error occured I think on the lines endcase and endmodule. I think I would have to close them with something.

Body:
There are a couple of errors in your code -

You missed the "end" after the "endcase" statement. The end is required for the begin block just before the case statement.

You have added ";" in the always block declaration.

always@(posedge clk);
    begin
    state = next_state;
    tt = tt - 1;
    end

There is no need of an ";" in the always block.

module TrafficLight(t, state, next_state, clk, out);

input t, clk;
output out;
localparam s0=3'b000, s1=3'b001, s2=3'b010, s3=3'b011, s4=3'b100, s5=3'b101;
reg[2:0] state, next_state, tt;

In the above snippet I see that you have added "state" and "next_state" as ports to the module but haven't assigned any direction to them. Either remove them as ports or make them as "input" or "output".

You would also need to remove the "assign" statement when driving the out reg. Since it is inside a procedural block you don't need an "assign" here.

You can find all the updates to your code here


问:
upload multiple files with move_uploaded_file() function by using foreach loop
I'm trying to upload multiple files with for each loop. what should I use in the first parameter of move_uploaded_file() function in this case </p>

```<code>            foreach ($_FILES["prodImg"]["name"] as $pImage) {
                $nbr++;
                $col = 'image' . $nbr;
                $fileName = basename($pImage);
                $target_file = $target_dir . "" . $fileName;
                $rqt = "UPDATE prodimages SET $col=? WHERE prodId= ? ";
                $stmt = $con->prepare($rqt);
                $stmt->execute(array($fileName, $pID));
                move_uploaded_file($pImage, $target_file);
            }
</code>```

答:
As you can see in the docs you can use $_FILES["prodImg"]["tmp_name"][$i]:

```<code>foreach ($_FILES["prodImg"]["name"] as $i => $pImage) {
    move_uploaded_file($_FILES["prodImg"]["tmp_name"][$i], /*..*/);
}
</code>```

You can always var_dump($_FILES); to see what it looks like.

Body:
I'm trying to upload multiple files with for each loop. what should I use in the first parameter of move_uploaded_file() function in this case

            foreach ($_FILES["prodImg"]["name"] as $pImage) {
                $nbr++;
                $col = 'image' . $nbr;
                $fileName = basename($pImage);
                $target_file = $target_dir . "" . $fileName;
                $rqt = "UPDATE prodimages SET $col=? WHERE prodId= ? ";
                $stmt = $con->prepare($rqt);
                $stmt->execute(array($fileName, $pID));
                move_uploaded_file($pImage, $target_file);
            }

Body:
As you can see in the docs you can use $_FILES["prodImg"]["tmp_name"][$i]:

foreach ($_FILES["prodImg"]["name"] as $i => $pImage) {
    move_uploaded_file($_FILES["prodImg"]["tmp_name"][$i], /*..*/);
}

You can always var_dump($_FILES); to see what it looks like.


问:
Adding multiple list views to same resource - Admin-On-Rest
I have a tale Resource that I want to display in different ways for the same user, depending on the tale status

Tale with status = NEW should be shown with List1

Tales with status = APPROVED etc need to be shown as List2 (I need to display different properties of the tale)

How to achieve this using Admin-On-Rest?

On Adding the same resource twice (as below) and allocating different List Views to both is only causing the first to be displayed and the second is ignored

```<code><Resource name="tales" list={EditorAssignedList} edit={EditTale} options={{ label: 'Assigned Tales' }}/>
<Resource name="tales" list={EditorTaleTrack} options={{ label: 'Your Tales' }}/>
</code>```

The following error is logged.

```<code>flattenChildren(...): Encountered two children with the same key, `1:$tales`. Child keys must be unique;
</code>```

Any strategies on how to inject unique key into the resource.

答:
The above answer is not really that useful if you also want to add CRUD capabilities to the same route but through different List Menus. If you have 2 list views List1 and List2 with CRUD components. Enter edit (for example) from List2 and hit save you will be redirect to List1

A more broad solution is to create a custom wrapper to your REST Client.
Inspiration from below.
https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload

for my case it looked like this.

I created a dummy resource 'trackTale' in App.js. The in restWrapper.js

```<code>const RESTWrapper = requestHandler => (type, resource, params) => {

      if (type === 'GET_LIST' && resource === 'trackTale') {
        const page =  params.pagination.page
        const perPage = params.pagination.perPage
        const {field, order} = params.sort
        const query = {}
        query['where'] = {...params.filter}
        if (field) {query['order'] = [field + ' ' + order]}
        if (perPage > 0) {
            query['limit'] = perPage;
            if (page >= 0) {
                query['skip'] = (page - 1) * perPage
            }
        }
        //Key part here hardcoding the tales route to trackTale

const url = config.host + '/' + 'tales?' +  queryParameters({filter: JSON.stringify(query)})
        const options = {};
        options.user = {authenticated: true}
        options.user.token = localStorage.getItem('token');
        options.method = 'GET';
        return fetchUtils.fetchJson(url, options)
          .then((response) => {
            const {headers, json} = response;
            //admin on rest needs the {data} key
            return {data: json,
                    total: parseInt(headers.get('x-total-count').split('/').pop(), 10)}
        })
    }
}

//below function is very very specific to how loopback.js expects to recieve REST queries. Please customize it for your API needs
const queryParameters = data => Object.keys(data)
    .map(key => [key, data[key]].map(encodeURIComponent).join('='))
    .join('&');
</code>```

This will work for all cases. Can still create a custom Menu if your different routes do not have CRUD.

Body:
I have a tale Resource that I want to display in different ways for the same user, depending on the tale status

Tale with status = NEW should be shown with List1

Tales with status = APPROVED etc need to be shown as List2 (I need to display different properties of the tale)

How to achieve this using Admin-On-Rest?

On Adding the same resource twice (as below) and allocating different List Views to both is only causing the first to be displayed and the second is ignored

<Resource name="tales" list={EditorAssignedList} edit={EditTale} options={{ label: 'Assigned Tales' }}/>
<Resource name="tales" list={EditorTaleTrack} options={{ label: 'Your Tales' }}/>

The following error is logged.

flattenChildren(...): Encountered two children with the same key, `1:$tales`. Child keys must be unique;

Any strategies on how to inject unique key into the resource.

Body:
The above answer is not really that useful if you also want to add CRUD capabilities to the same route but through different List Menus. If you have 2 list views List1 and List2 with CRUD components. Enter edit (for example) from List2 and hit save you will be redirect to List1

A more broad solution is to create a custom wrapper to your REST Client.
Inspiration from below.
https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload

for my case it looked like this.

I created a dummy resource 'trackTale' in App.js. The in restWrapper.js

const RESTWrapper = requestHandler => (type, resource, params) => {

      if (type === 'GET_LIST' && resource === 'trackTale') {
        const page =  params.pagination.page
        const perPage = params.pagination.perPage
        const {field, order} = params.sort
        const query = {}
        query['where'] = {...params.filter}
        if (field) {query['order'] = [field + ' ' + order]}
        if (perPage > 0) {
            query['limit'] = perPage;
            if (page >= 0) {
                query['skip'] = (page - 1) * perPage
            }
        }
        //Key part here hardcoding the tales route to trackTale

const url = config.host + '/' + 'tales?' +  queryParameters({filter: JSON.stringify(query)})
        const options = {};
        options.user = {authenticated: true}
        options.user.token = localStorage.getItem('token');
        options.method = 'GET';
        return fetchUtils.fetchJson(url, options)
          .then((response) => {
            const {headers, json} = response;
            //admin on rest needs the {data} key
            return {data: json,
                    total: parseInt(headers.get('x-total-count').split('/').pop(), 10)}
        })
    }
}

//below function is very very specific to how loopback.js expects to recieve REST queries. Please customize it for your API needs
const queryParameters = data => Object.keys(data)
    .map(key => [key, data[key]].map(encodeURIComponent).join('='))
    .join('&');

This will work for all cases. Can still create a custom Menu if your different routes do not have CRUD.


问:
drop_all() freezes in Flask with SQLAlchemy
I am writing test cases for a Flask application.

I have a setUp method which drops the tables in the db before re-creating them again.
It looks like this:

```<code>def setUp(self):
    # other stuff...
    myapp.db.drop_all()
    myapp.db.create_all()
    # db creation...
</code>```

This works fine for the first test, but it freezes at drop_all before the second test is run.

EDIT:
The stack trace looks like this when interrupting the process

```<code>  File "populate.py", line 70, in create_test_db
    print (myapp.db.drop_all())
  File ".../flask_sqlalchemy/__init__.py", line 864, in drop_all
    self._execute_for_all_tables(app, bind, 'drop_all')
  File ".../flask_sqlalchemy/__init__.py", line 848, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), tables=tables)
  File ".../sqlalchemy/sql/schema.py", line 3335, in drop_all
  ....
  File "/Library/Python/2.7/site-packages/MySQLdb/cursors.py", line 190, in execute
    r = self._query(query)
</code>```

Anybody has a clue how to fix this?

答:
Just close all sessions in your app and after that invoke drop_all

```<code>    def __init__(self, conn_str):
        self.engine = create_engine(conn_str)
        self.session_factory = sessionmaker(engine)

    def drop_all(self):
        self.session_factory.close_all() # <- don't forget to close
        Base.metadata.drop_all(self._engine)
</code>```

more information about Sessions in SQLAlchemy
http://docs.sqlalchemy.org/en/latest/orm/session_api.html?highlight=close_all

Body:
I am writing test cases for a Flask application.

I have a setUp method which drops the tables in the db before re-creating them again.
It looks like this:

def setUp(self):
    # other stuff...
    myapp.db.drop_all()
    myapp.db.create_all()
    # db creation...

This works fine for the first test, but it freezes at drop_all before the second test is run.

EDIT:
The stack trace looks like this when interrupting the process

  File "populate.py", line 70, in create_test_db
    print (myapp.db.drop_all())
  File ".../flask_sqlalchemy/__init__.py", line 864, in drop_all
    self._execute_for_all_tables(app, bind, 'drop_all')
  File ".../flask_sqlalchemy/__init__.py", line 848, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), tables=tables)
  File ".../sqlalchemy/sql/schema.py", line 3335, in drop_all
  ....
  File "/Library/Python/2.7/site-packages/MySQLdb/cursors.py", line 190, in execute
    r = self._query(query)

Anybody has a clue how to fix this?

Body:
Just close all sessions in your app and after that invoke drop_all

    def __init__(self, conn_str):
        self.engine = create_engine(conn_str)
        self.session_factory = sessionmaker(engine)

    def drop_all(self):
        self.session_factory.close_all() # <- don't forget to close
        Base.metadata.drop_all(self._engine)

more information about Sessions in SQLAlchemy
http://docs.sqlalchemy.org/en/latest/orm/session_api.html?highlight=close_all


问:
Text-align isn't working for form element
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

```<code><header>
  <nav>
    <ul>
      <li><a href="">One</a></li>
      <li><a href="">Two</a></li>
      <li><a href="">Three</a></li>
      <li><a href="">Four</a></li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header>
</code>```

My css:

```<code>ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}
</code>```

Jsfiddle: https://jsfiddle.net/dsotpsq4/

答:
If you want your entire form on the right side of the header, correct with this

```<code>header form{
  display: inline-block;
  float: right;
}
</code>```

Because form is a block and you need to move it to the right as a block

If you want the content of your form aligned on its right, change and add this

```<code>header form{
  text-align: right;
}
header form *{
  display: inline-block;
}
</code>```

Text align works only with inline and inline-block elements, so you have to say input and button are inline-blocks.

Body:
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

One

Two

Three

Four

    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>

My css:

ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}

Jsfiddle: https://jsfiddle.net/dsotpsq4/

Body:
If you want your entire form on the right side of the header, correct with this

header form{
  display: inline-block;
  float: right;
}

Because form is a block and you need to move it to the right as a block

If you want the content of your form aligned on its right, change and add this

header form{
  text-align: right;
}
header form *{
  display: inline-block;
}

Text align works only with inline and inline-block elements, so you have to say input and button are inline-blocks.