问:
How to use Polymer lifecycle hooks
I have a component that contains video. My component is nested in a dom-if and can disappear. When this happens the video (and it sound) keep playing.

Is there a way in which my component can detect that is has  disappeared from the DOM? I have tried to use the 'detached' callback as described here: https://www.polymer-project.org/1.0/docs/devguide/registering-elements

```<code>Polymer({
  is: 'my-component-with-video',

  properties: {
     // some properties
  },

  detached: function() {
    console.log('Component detached');
    // more code to stop video
  },
</code>```

but when my element is removed by the dom-if nothing happens, I don't see the console.log message. What am I doing wrong?

答:
No need for any workaround other than simply using your dom-if and rather than

```<code><dom-if if="[[condietionBoolean]]">
<your-video-element id="giveanId"></your-video-element>
</dom-if>
</code>```

write the if statement like below and so each time your condition changes, you check and make sure the video is paused if when you like. See below.

```<code>...
<dom-if if="[[_shouldShowVideo(conditionBoolean)]]">
<your-video-element id="giveanId"></your-video-element>
</dom-if>

...

Polymer({
  is: 'my-component-with-video',

  properties: {

     conditionBoolean : {
        type: Boolean,
     },

  },

_shouldShowVideo: function(conditionBoolean ) {
   if (!conditionBoolean) this.$$(#yourVideoElementId).pause();
   return conditionBoolean ;
}
</code>```

});

Title: How to use Polymer lifecycle hooks

Body:
I have a component that contains video. My component is nested in a dom-if and can disappear. When this happens the video (and it sound) keep playing.

Is there a way in which my component can detect that is has  disappeared from the DOM? I have tried to use the 'detached' callback as described here: https://www.polymer-project.org/1.0/docs/devguide/registering-elements

Polymer({
  is: 'my-component-with-video',

  properties: {
     // some properties
  },

  detached: function() {
    console.log('Component detached');
    // more code to stop video
  },

but when my element is removed by the dom-if nothing happens, I don't see the console.log message. What am I doing wrong?

Body:
No need for any workaround other than simply using your dom-if and rather than

<dom-if if="[[condietionBoolean]]">
<your-video-element id="giveanId"></your-video-element>
</dom-if>

write the if statement like below and so each time your condition changes, you check and make sure the video is paused if when you like. See below.

...
<dom-if if="[[_shouldShowVideo(conditionBoolean)]]">
<your-video-element id="giveanId"></your-video-element>
</dom-if>

...

Polymer({
  is: 'my-component-with-video',

  properties: {

     conditionBoolean : {
        type: Boolean,
     },

  },

_shouldShowVideo: function(conditionBoolean ) {
   if (!conditionBoolean) this.$$(#yourVideoElementId).pause();
   return conditionBoolean ;
}

});


来源: stackexchange

问:
How to print json array from Response<ResponseBody> response in retorift2.0
I developed android application with retorfit 2.0. I tweeter in our application. I am getting json array format data from url when check in browser. I am getting response in my application like code: 200ok and responce is like : repoces@012345 printed as raw data. How can I print response as array format.

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://cdn.syndication.twimg.com/")
                .addConverterFactory(GsonConverterFactory.create())

                .build();

        RequestInterface requestInterface = retrofit.create(RequestInterface.class);

        Call<ResponseBody> response = requestInterface.gettwetter("vinodh654");

        response.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("Tweeter Respose",response.code()+" "+response.message()+" "+response.body().toString());

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("Tweeter Respose","Fail");
            }
        });```

答:
Try this </p>

```<code> @Override
         public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
                String responseString = response.body().string();
                Log.d("Response",response.code()+" "+response.message()+" "+data;
         }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try this

 @Override
         public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
                String responseString = response.body().string();
                Log.d("Response",response.code()+" "+response.message()+" "+data;
         }


问:
send data from raspberry pi to cordova app and vice versa
I want code that will run on Raspberry pi constantly that will send me some sensor data to my Cordova android app. And also the code for sending the data to RPI from the Cordova app. Can anyone help on this?</p>

答:
You can host a server on your PI and use a generic client-server socket communication to transfer data. You can use any JavaScript library at the cordova end. ( Well, It runs on js )  and any other technology at the PI end.

You can use libraries like Socket.io, or pusher

https://socket.io/

https://pusher.com/docs/libraries

Note that pusher has a daily limit and some communication.

Hope this help. :)


问:
PHP create xls from array
I try to create xls file from array and download it with the browser with this code:

```<code>$sheet = array(
    array(
      'a1 data',
      'b1 data',
      'c1 data',
      'd1 data',
    )
  );

  $doc = new PHPExcel();
  $doc->getActiveSheet()->fromArray($sheet, null, 'A1');

  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="your_name.xls"');
  header('Cache-Control: max-age=0');

  // Do your stuff here

  $writer = PHPExcel_IOFactory::createWriter($doc, 'Excel5');
</code>```

The problem is that i get a empty file.Any idea what can be the issue?

答:
```<code>        $header = ['c1.', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11'];
        header('Content-Disposition: attachment; filename="data'.date('d-m-y').'.xls"');
        header("Content-Type: application/vnd.ms-excel");

        $output = fopen('php://output', 'w');
        fputcsv($output,  $header  , "\t");
        foreach ($Data as $value) {
            $tmp_data = [];
            array_push($tmp_data, $value['c1']);
            array_push($tmp_data, $value['c2']);
            array_push($tmp_data, $value['c3']);
            array_push($tmp_data, $value['c4']);
            array_push($tmp_data, $value['c5'] );
            array_push($tmp_data, $value['c6']);
            array_push($tmp_data, $value['c7']);
            array_push($tmp_data, $value['c8']);
            array_push($tmp_data,  $value['c9']);
            array_push($tmp_data, $value['c10']);
            array_push($tmp_data, $value['c11']);
            fputcsv($output,  $tmp_data ,  "\t" );
        }
        fclose($output);
</code>```

Title: PHP create xls from array

Body:
I try to create xls file from array and download it with the browser with this code:

$sheet = array(
    array(
      'a1 data',
      'b1 data',
      'c1 data',
      'd1 data',
    )
  );

  $doc = new PHPExcel();
  $doc->getActiveSheet()->fromArray($sheet, null, 'A1');

  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="your_name.xls"');
  header('Cache-Control: max-age=0');

  // Do your stuff here

  $writer = PHPExcel_IOFactory::createWriter($doc, 'Excel5');

The problem is that i get a empty file.Any idea what can be the issue?


问:
Hide registration and login form when user is logged in ASP.NET
I am new at ASP.NET and I am having some difficulties. What I have below is a Registration and Login, both in one page. However, when a user is logged in, I would like the registration and login form to be hided.
There is a LOGOUT option when the user is logged in.
Any guidance would be great, thank you!</p>

```<code><%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %>

<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    End Sub

    Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs)

    End Sub

    Protected Sub Login1_Authenticate1(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs)

    End Sub

    Protected Sub Login1_Authenticate2(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs)

    End Sub

Protected Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As System.EventArgs)

End Sub
</script>

<%-- Add content controls here --%>
<asp:Content ID="Content1" runat="server"
    contentplaceholderid="ContentPlaceHolder1">
    <table width="640px"><tr>
    <td width="360px">
                    <p>
                        <asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
                            <WizardSteps>
                                <asp:CreateUserWizardStep runat="server" />
                                <asp:CompleteWizardStep runat="server" />
                            </WizardSteps>
                        </asp:CreateUserWizard>
</p>
                    <br />
                    <br />
                    </td>
                    <td width="270px">
                        <p>
        <asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Home.aspx">
        </asp:Login>
        <asp:LoginView ID="LoginView1" runat="server">
            <AnonymousTemplate>
                Please log In
            </AnonymousTemplate>
        </asp:LoginView>
</p>
    <p>
        <asp:LoginStatus ID="LoginStatus1" runat="server" />
</p>
</td>
</tr>
</table>

</asp:Content>
</code>```

答:
You can use User.Identity.IsAuthenticated to figure out if they're authenticated or not. If they are, you can set the visibility of your control to false.

In your Page_Load method, put something that looks like this:

```<code>if (User.Identity.IsAuthenticated)
            CreateUserWizard1.Visible = Login1.Visible = False
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am new at ASP.NET and I am having some difficulties. What I have below is a Registration and Login, both in one page. However, when a user is logged in, I would like the registration and login form to be hided.
There is a LOGOUT option when the user is logged in.
Any guidance would be great, thank you!

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %>

<%-- Add content controls here --%>
<asp:Content ID="Content1" runat="server"
    contentplaceholderid="ContentPlaceHolder1">

                        <asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
                            <WizardSteps>
                                <asp:CreateUserWizardStep runat="server" />
                                <asp:CompleteWizardStep runat="server" />
                            </WizardSteps>
                        </asp:CreateUserWizard>

        <asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Home.aspx">
        </asp:Login>
        <asp:LoginView ID="LoginView1" runat="server">
            <AnonymousTemplate>
                Please log In
            </AnonymousTemplate>
        </asp:LoginView>

        <asp:LoginStatus ID="LoginStatus1" runat="server" />

</asp:Content>

Body:
You can use User.Identity.IsAuthenticated to figure out if they're authenticated or not. If they are, you can set the visibility of your control to false.

In your Page_Load method, put something that looks like this:

if (User.Identity.IsAuthenticated)
            CreateUserWizard1.Visible = Login1.Visible = False


问:
Removing #id from the url (bootstrap)
I've just created the bootstrap navbar on my website and I have the trouble with my url...
For example I have something like this: </p>

```<code><div class="navbar-collapse collapse">
  <ul class="nav navbar-nav navbar-right">
    <li>
      <a data-toggle="collapse" data-target=".navbar-collapse" href="#about">
        About
      </a>
    </li>
  </ul>
</div>
</code>```

<p>And my website url looks like this: "something.html#about"
I would like to remove the #about from the url. I read that I should remove? the href from this li item, and put the #about in data-target but it doesn't work for me. What is the easiest way to fix this? Thanks for any respond. </p>

答:
you can use data-target instead of href. It will help you to get rid of #about from the browser URL.

So instead of

```<code>href="#about"
</code>```

use

```<code>data-target="#about"
</code>```

Title: Removing #id from the url (bootstrap)

Body:
I've just created the bootstrap navbar on my website and I have the trouble with my url...
For example I have something like this:

        About

And my website url looks like this: "something.html#about"
I would like to remove the #about from the url. I read that I should remove? the href from this li item, and put the #about in data-target but it doesn't work for me. What is the easiest way to fix this? Thanks for any respond.

Body:
you can use data-target instead of href. It will help you to get rid of #about from the browser URL.

So instead of

href="#about"

use

data-target="#about"


问:
Unsupported Data Type when using SQL Data Sync to Azure
I'd like to sync an on-premise SQL Server 2012 SP2 database to Azure using SQL Data Sync.
When I try to do the sync I get "Unsupported Data Type" error on one of the tables for the ID_Index column:

The Azure Management Portal gives no further explanantion for the error.
The table design in SQL Server Management Studio:

The table creation script:

```<code>CREATE TABLE [dbo].[FlightPlanData](
  [ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_FlightPlanData_ID]  DEFAULT (newid()),
  [Airline_ID] [int] NOT NULL,
  [FlightID_FK] [uniqueidentifier] NOT NULL,
  [FlightPlanID] [int] NOT NULL,
  [DateInserted] [datetime] NOT NULL CONSTRAINT [DF_FlightPlanData_DateInserted]  DEFAULT (getdate()),
  [Type] [varchar](20) NOT NULL CONSTRAINT [DF_FlightPlanData_Type]  DEFAULT (''),
  [FileName] [varchar](100) NOT NULL CONSTRAINT [DF_FlightPlanData_FileName]  DEFAULT (''),
  [ClientID_FK] [uniqueidentifier] NULL,
  [ID_Index] [int] IDENTITY(1,1) NOT NULL,
    CONSTRAINT [PK_FlightPlanData] PRIMARY KEY NONCLUSTERED ([ID] ASC))

CREATE CLUSTERED INDEX [IX_FlightPlanData] ON [dbo].[FlightPlanData]([ID_Index] ASC)
</code>```

The table has a GUID primary key, but it's not clustered, instead we use a clustered in index (ID_Index).
I can't remove the ID_Index column, and I'd prefer not to make it the primary key. Is there any way to solve this?
I heard Azure requires a clustered index for each table, but it doesn't have to be the primary key. So what's the problem here?

答: A table cannot have an identity column that is not the primary key. This is one of the general requirements of SQL Data Sync. For more information, please visit this GitHub documentation.</p>

Body:
I'd like to sync an on-premise SQL Server 2012 SP2 database to Azure using SQL Data Sync.
When I try to do the sync I get "Unsupported Data Type" error on one of the tables for the ID_Index column:

The Azure Management Portal gives no further explanantion for the error.
The table design in SQL Server Management Studio:

The table creation script:

CREATE TABLE [dbo].[FlightPlanData](
  [ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_FlightPlanData_ID]  DEFAULT (newid()),
  [Airline_ID] [int] NOT NULL,
  [FlightID_FK] [uniqueidentifier] NOT NULL,
  [FlightPlanID] [int] NOT NULL,
  [DateInserted] [datetime] NOT NULL CONSTRAINT [DF_FlightPlanData_DateInserted]  DEFAULT (getdate()),
  [Type] [varchar](20) NOT NULL CONSTRAINT [DF_FlightPlanData_Type]  DEFAULT (''),
  [FileName] [varchar](100) NOT NULL CONSTRAINT [DF_FlightPlanData_FileName]  DEFAULT (''),
  [ClientID_FK] [uniqueidentifier] NULL,
  [ID_Index] [int] IDENTITY(1,1) NOT NULL,
    CONSTRAINT [PK_FlightPlanData] PRIMARY KEY NONCLUSTERED ([ID] ASC))

CREATE CLUSTERED INDEX [IX_FlightPlanData] ON [dbo].[FlightPlanData]([ID_Index] ASC)

The table has a GUID primary key, but it's not clustered, instead we use a clustered in index (ID_Index).
I can't remove the ID_Index column, and I'd prefer not to make it the primary key. Is there any way to solve this?
I heard Azure requires a clustered index for each table, but it doesn't have to be the primary key. So what's the problem here?


问:
How to get publication status using Alexa Skill Management Api
I have created an Alexa Skill using Alexa Skill Management API's.

Now using the API
https://api.amazonalexa.com/v0/skills/{skill-id}/submit.

This API returns success which means that my skill is submitted for
certification.

But How to get the publication status that whether the skill is live or
under certification.

How can I get the publication status of skill.

答:
You can use the CLI to do that,

```<code>get-skill-status
</code>```

Reference: https://developer.amazon.com/docs/smapi/ask-cli-command-reference.html#get-model-status-subcommand

Body:
You can use the CLI to do that,

get-skill-status

Reference: https://developer.amazon.com/docs/smapi/ask-cli-command-reference.html#get-model-status-subcommand


问:
Can i pop to Specific ViewController?
I am using navigation based application. I push First ViewController to Second ViewController and from Second ViewController to Third ViewController. Now I want to pop from Third ViewController to First ViewController.I am performing this task using the below code but my application crashed.

Please any body give me some proper guidelines. I can't use pop to rootViewController because it's different viewController. Thanks in advance...

In Third ViewControler i have written this:

```<code>FirstViewCtr *x=[[FirstViewCtr alloc] initWithNibName:@"FirstViewCtr" bundle:nil];
[self.navigationController popToViewController:x animated:NO];
</code>```

答:
Updated for Swift 3:

used below simple code, for pop to specific view controller;

```<code> for vc in self.navigationController!.viewControllers as Array {
          if vc.isKind(of: YourViewControllerName) {
               self.navigationController!.popToViewController(vc, animated: true)
               break
          }
    }
</code>```

Title: Can i pop to Specific ViewController?

Body:
I am using navigation based application. I push First ViewController to Second ViewController and from Second ViewController to Third ViewController. Now I want to pop from Third ViewController to First ViewController.I am performing this task using the below code but my application crashed.

Please any body give me some proper guidelines. I can't use pop to rootViewController because it's different viewController. Thanks in advance...

In Third ViewControler i have written this:

FirstViewCtr *x=[[FirstViewCtr alloc] initWithNibName:@"FirstViewCtr" bundle:nil];
[self.navigationController popToViewController:x animated:NO];

Body:
Updated for Swift 3:

used below simple code, for pop to specific view controller;

 for vc in self.navigationController!.viewControllers as Array {
          if vc.isKind(of: YourViewControllerName) {
               self.navigationController!.popToViewController(vc, animated: true)
               break
          }
    }


问:
How to calculate the range of primitive data types?
According to docs.oracle.com:-

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

Byte - 8 bits

 2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0

128 64  32   16   8   4   2   1)

Adding all these numbers we get a total of 255. Then how's the range which is -128 to 127 calculated. Is it hard-coded somewhere or there's some more technicality to this range?

Any suggestions would be appreciated.

答:
Formula for Range calculation is : -2^(n-1) to (2^(n-1)-1)

where n = no. of bits of primitive datatype.
Example:

For int datatype, n is 32, in short datatype, n is 16 etc.

So, int range will be: -2^(32-1) to (2^(32-1)-1)

By using the same formula Range of byte, short, float and double could be calculated.

ContentLicense: CC BY-SA 4.0


问:
How to post data using PUT method in Swift 3?
Here I need to post data using PUT method to the server but i am unable to post it and it's working fine in postman. Is my json function was wrong if it is wrong can anyone help me how to implement this ?

```<code>func itemsIncrementingandDecrementingtocartDownloadJsonWithURL(itemsApi: String){
        print(itemsApi)
        let url = URL(string: itemsApi)
        var request = URLRequest(url: url! as URL)
        request.httpMethod = "PUT"
        let parameters : [String: Any] = ["cartItem":
            [
                "item_id": itemId!,
                "qty": quantity!,
                "quote_id": "\(self.key!)"
            ]
        ]
        print(parameters)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let session = URLSession(configuration:URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
        let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in

            if error != nil {

                //handle error
            }
            else {

                let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("Parsed JSON: '\(jsonStr)'")
            }
        }
        dataTask.resume()
    }
</code>```

答:
At first serialize the parameters to json string and add string to request http body.

```<code>let postData = JSONSerialization.data(withJSONObject: parameters, options: [])
request.httpBody = postData as Data
</code>```

This will help you.

Body:
Here I need to post data using PUT method to the server but i am unable to post it and it's working fine in postman. Is my json function was wrong if it is wrong can anyone help me how to implement this ?

func itemsIncrementingandDecrementingtocartDownloadJsonWithURL(itemsApi: String){
        print(itemsApi)
        let url = URL(string: itemsApi)
        var request = URLRequest(url: url! as URL)
        request.httpMethod = "PUT"
        let parameters : [String: Any] = ["cartItem":
            [
                "item_id": itemId!,
                "qty": quantity!,
                "quote_id": "\(self.key!)"
            ]
        ]
        print(parameters)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let session = URLSession(configuration:URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
        let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in

            if error != nil {

                //handle error
            }
            else {

                let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("Parsed JSON: '\(jsonStr)'")
            }
        }
        dataTask.resume()
    }

Body:
At first serialize the parameters to json string and add string to request http body.

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])
request.httpBody = postData as Data

This will help you.


问:
Jenkins Declarative Pipeline won't work with Docker Swarm
Running this simple pipeline:

```<code>pipeline {
    agent { label 'docker-swarm' }
    /* ------------------- */
    stages {
        stage("Build") {
            agent {
                docker {
                  reuseNode true
                  image 'maven:3.5.0-jdk-8'
                }
            }
            steps {
                sh 'mvn -version'
            }
        }
    }
}
</code>```

Produces this error:

Queued: All nodes of label ‘docker-swarm’ are offline

After ~1 minute the error message changes to:

Cannot connect to the Docker daemon. Is the docker daemon running on this host?

The strange thing is that when I test the connection in Manage Jenkins → Cloud it can connect without a problem:

Anybody got an idea hot to fix this?

答:
Update 11/27/2017:  The screenshot shows an incorrect configuration which does not use the swarm, but instead uses a single manager node.  To use the swarm, I switched to port 3376 and the Test Connection output changes to Version = swarm/1.2.8, API Version = 1.22.  I noticed my mistake after never seeing builds run on the other nodes in the swarm, and the swarm manager getting overwhelmed.

In the original question it is not clear what versions of the various Jenkins plugins are being used, nor how the swarm was configured.

I have successfully used:

Jenkins 2.73.3

Docker Plugin 1.0.4

Standalone (aka Classic) Docker Swarm

At the time I write this, the newer Docker Swarm mode was not supported by the Docker Plugin. Although a non-swarm docker engine supposedly would work.

Configured like so:

The credentials provide the certificates needed to connect to the swarm.  I do recall it taking me a few tries to get that right.

The following pipeline works:

```<code>pipeline {
    agent {
        docker 'maven:3.5.0-jdk-8'
    }
    stages {
        stage('Build') {
            steps {
                sh 'mvn -version'
            }
        }
    }
}
</code>```

Giving output:

```<code>Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-03T19:39:06Z)
Maven home: /usr/share/maven
Java version: 1.8.0_141, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-openjdk-amd64/jre
Default locale: en, platform encoding: UTF-8
OS name: "linux", version: "4.4.93-boot2docker", arch: "amd64", family: "unix"
</code>```

The key differences with the pipeline in the original question are:

Use of a single pipeline scoped agent with the image.

Not using reuseNode.

Not using label.

I have not personally tried reuseNode or label.

Body:
Running this simple pipeline:

pipeline {
    agent { label 'docker-swarm' }
    /* ------------------- */
    stages {
        stage("Build") {
            agent {
                docker {
                  reuseNode true
                  image 'maven:3.5.0-jdk-8'
                }
            }
            steps {
                sh 'mvn -version'
            }
        }
    }
}

Produces this error:

Queued: All nodes of label ‘docker-swarm’ are offline

After ~1 minute the error message changes to:

Cannot connect to the Docker daemon. Is the docker daemon running on this host?

The strange thing is that when I test the connection in Manage Jenkins → Cloud it can connect without a problem:

Anybody got an idea hot to fix this?

Body:
Update 11/27/2017:  The screenshot shows an incorrect configuration which does not use the swarm, but instead uses a single manager node.  To use the swarm, I switched to port 3376 and the Test Connection output changes to Version = swarm/1.2.8, API Version = 1.22.  I noticed my mistake after never seeing builds run on the other nodes in the swarm, and the swarm manager getting overwhelmed.

In the original question it is not clear what versions of the various Jenkins plugins are being used, nor how the swarm was configured.

I have successfully used:

Jenkins 2.73.3

Docker Plugin 1.0.4

Standalone (aka Classic) Docker Swarm

At the time I write this, the newer Docker Swarm mode was not supported by the Docker Plugin. Although a non-swarm docker engine supposedly would work.

Configured like so:

The credentials provide the certificates needed to connect to the swarm.  I do recall it taking me a few tries to get that right.

The following pipeline works:

pipeline {
    agent {
        docker 'maven:3.5.0-jdk-8'
    }
    stages {
        stage('Build') {
            steps {
                sh 'mvn -version'
            }
        }
    }
}

Giving output:

Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-03T19:39:06Z)
Maven home: /usr/share/maven
Java version: 1.8.0_141, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-openjdk-amd64/jre
Default locale: en, platform encoding: UTF-8
OS name: "linux", version: "4.4.93-boot2docker", arch: "amd64", family: "unix"

The key differences with the pipeline in the original question are:

Use of a single pipeline scoped agent with the image.

Not using reuseNode.

Not using label.

I have not personally tried reuseNode or label.


问:
Qt, C++, How to Quit QThread
I have a calculator and a calculator method startCalculations() which is to put onto a QThread. I successfully connect mStopCalcButton and the thread's quit()/terminate(). However, when I press mStopCalcButton, the thread does not quit/terminate.

Here is the code in question...

```<code>mStopCalcButton->setEnabled(true);

QThread* thread = new QThread;
Calculator* calculator = new Calculator();
calculator->moveToThread(thread);
connect(thread, SIGNAL(started()), calculator, SLOT(startCalculations()));  //when thread starts, call startCalcuations
connect(calculator, SIGNAL(finished()), thread, SLOT(quit()));
connect(calculator, SIGNAL(finished()), calculator, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();

connect(mStopCalcButton, SIGNAL(released()), thread, SLOT(quit()) );
</code>```

In the calculator, this is the only defined method...

```<code>void Calculator::startCalcuations()
{
    int x = 0;
    while (true)
        qDebug() << x++;
}
</code>```

Why does my QThread not quit?

答:
The first thing, function QThread::quit() only tell that thread to exit it's event loop, but do nothing related to terminate or exit. you can read Qt document here: QThread:quit()

To terminate a thread, in general implement, you should change your thread's running function code by using stop flag rather than infinitive loop. Whenever you want to terminate thread, you only need change that stop flag and wait for thread terminating.

Using stop flag:

```<code>void Calculator::startCalcuations()
{
    int x = 0;
    while (!mStopFlag) {
        qDebug() << x++;
        // In addition, you should add a little sleep here to avoid CPU overhelming
        // like as msleep(100);
    }
}
</code>```

Terminate thread by turning on the stop flag:

```<code>void YourClass::requestTerminateThread()
{
    mStopFlag = true;
    if(!thread.wait(500))
    {
        thread.terminate(); // tell OS to terminate thread
        thread.wait(); // because thread may not be immediately terminated by OS policies
    }
}
</code>```

In addition, as you can see my comment on above code, you should add some thread sleep time to avoid CPU overhelming.

For more information, please clearly read QThread document specs first.

Title: Qt, C++, How to Quit QThread

Body:
I have a calculator and a calculator method startCalculations() which is to put onto a QThread. I successfully connect mStopCalcButton and the thread's quit()/terminate(). However, when I press mStopCalcButton, the thread does not quit/terminate.

Here is the code in question...

mStopCalcButton->setEnabled(true);

QThread* thread = new QThread;
Calculator* calculator = new Calculator();
calculator->moveToThread(thread);
connect(thread, SIGNAL(started()), calculator, SLOT(startCalculations()));  //when thread starts, call startCalcuations
connect(calculator, SIGNAL(finished()), thread, SLOT(quit()));
connect(calculator, SIGNAL(finished()), calculator, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();

connect(mStopCalcButton, SIGNAL(released()), thread, SLOT(quit()) );

In the calculator, this is the only defined method...

void Calculator::startCalcuations()
{
    int x = 0;
    while (true)
        qDebug() << x++;
}

Why does my QThread not quit?

Body:
The first thing, function QThread::quit() only tell that thread to exit it's event loop, but do nothing related to terminate or exit. you can read Qt document here: QThread:quit()

To terminate a thread, in general implement, you should change your thread's running function code by using stop flag rather than infinitive loop. Whenever you want to terminate thread, you only need change that stop flag and wait for thread terminating.

Using stop flag:

void Calculator::startCalcuations()
{
    int x = 0;
    while (!mStopFlag) {
        qDebug() << x++;
        // In addition, you should add a little sleep here to avoid CPU overhelming
        // like as msleep(100);
    }
}

Terminate thread by turning on the stop flag:

void YourClass::requestTerminateThread()
{
    mStopFlag = true;
    if(!thread.wait(500))
    {
        thread.terminate(); // tell OS to terminate thread
        thread.wait(); // because thread may not be immediately terminated by OS policies
    }
}

In addition, as you can see my comment on above code, you should add some thread sleep time to avoid CPU overhelming.

For more information, please clearly read QThread document specs first.


答:
Try add this.</p>

```<code>let data = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
request.httpBody = data
</code>```

Title: How to post data using PUT method in Swift 3?

Body:
Try add this.

let data = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
request.httpBody = data


问:
Reinstalling Eclipse without losing projects
Just a quick question, if I reinstall Eclipse, will I lose work that I have on the application, or will it stay in my files? Does deleting the app delete the folder made for eclipse? Thanks!</p>

答: You have to save your workspaces, if you have your projects in a workspace, you can save the folder and later when you reinstall eclipse import the folder. that's the better way.</p>


问:
Deciding between various methods for authentication in Angular 4
I have read two tutorials of implementing Authentication in Angular 4.

The first one overrides the RouterOutlet class, and declare public routes, where the login is not required.

However, the second approach is to use  canActivate AuthGuard Interface provided by Angular 4.

I am struggling to find out which approach is the correct or efficient one to implement.

Moreover, how can I implement authorization in Angular 4.  I read about canActivateChild interface, but it seems too complicated.

答:
I would recommend you to use AuthGuard.

Following is a simple example how you can implement AuthGuard.

Module.ts

```<code>// Routes
const routes : Routes = [
{
    path: '',
    component: HomeComponent,
    canActivate : [AuthService] //<== Activate AuthGuard
},
{
    path: 'login',
    component: LoginComponent
},
{
    path: '**',
    redirectTo: ''
}
];
'

@NgModule({
    declarations: [
    AppComponent,
    LoginComponent,
    HomeComponent
    ],
    providers: [AuthService], //<== Add AuthService here
    bootstrap: [AppComponent]
})
</code>```

AuthService

```<code>import { Injectable }     from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot }    from '@angular/router';

@Injectable()
export class AuthService implements CanActivate {

    constructor(private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url; //<== Get URL if needed

        if (localStorage.getItem('token')) { // <== Check for token
            return true;
        }else {
            this.router.navigate(['/login']);
            return false;
        }
    }
}
</code>```

Body:
I would recommend you to use AuthGuard.

Following is a simple example how you can implement AuthGuard.

Module.ts

// Routes
const routes : Routes = [
{
    path: '',
    component: HomeComponent,
    canActivate : [AuthService] //<== Activate AuthGuard
},
{
    path: 'login',
    component: LoginComponent
},
{
    path: '**',
    redirectTo: ''
}
];
'

@NgModule({
    declarations: [
    AppComponent,
    LoginComponent,
    HomeComponent
    ],
    providers: [AuthService], //<== Add AuthService here
    bootstrap: [AppComponent]
})

AuthService

import { Injectable }     from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot }    from '@angular/router';

@Injectable()
export class AuthService implements CanActivate {

    constructor(private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url; //<== Get URL if needed

        if (localStorage.getItem('token')) { // <== Check for token
            return true;
        }else {
            this.router.navigate(['/login']);
            return false;
        }
    }
}


问:
What is the difference between Span<T> and Memory<T> in C# 7.2?
C# 7.2 introduces two new types: Span<T> and Memory<T> that have better performance over earlier C# types like string[].

Question: What is the difference between Span<T> and Memory<T>? Why would I use one over the other?

答:
Span<T> is stack-only in nature while Memory<T> can exist on the heap.

Span<T> is a new type we are adding to the platform to represent
  contiguous regions of arbitrary memory, with performance
  characteristics on par with T[]. Its APIs are similar to the array,
  but unlike arrays, it can point to either managed or native memory, or
  to memory allocated on the stack.

Memory <T> is a type complementing Span<T>. As discussed in its design
  document, Span<T> is a stack-only type. The stack-only nature of
  Span<T> makes it unsuitable for many scenarios that require storing
  references to buffers (represented with Span<T>) on the heap, e.g. for
  routines doing asynchronous calls.

```<code>async Task DoSomethingAsync(Span<byte> buffer) {
    buffer[0] = 0;
    await Something(); // Oops! The stack unwinds here, but the buffer below
                       // cannot survive the continuation.
    buffer[0] = 1;
}
</code>```

To address this problem, we will provide a set of complementary types,
  intended to be used as general purpose exchange types representing,
  just like Span <T>, a range of arbitrary memory, but unlike Span <T>
  these types will not be stack-only, at the cost of significant
  performance penalties for reading and writing to the memory.

```<code>async Task DoSomethingAsync(Memory<byte> buffer) {
    buffer.Span[0] = 0;
    await Something(); // The stack unwinds here, but it's OK as Memory<T> is
                       // just like any other type.
    buffer.Span[0] = 1;
}
</code>```

In the sample above, the Memory <byte> is used to represent the buffer.
  It is a regular type and can be used in methods doing asynchronous
  calls. Its Span property returns Span<byte>, but the returned value
  does not get stored on the heap during asynchronous calls, but rather
  new values are produced from the Memory<T> value. In a sense,
  Memory<T> is a factory of Span<T>.

Reference Document: here

Body:
Span<T> is stack-only in nature while Memory<T> can exist on the heap.

Span<T> is a new type we are adding to the platform to represent
  contiguous regions of arbitrary memory, with performance
  characteristics on par with T[]. Its APIs are similar to the array,
  but unlike arrays, it can point to either managed or native memory, or
  to memory allocated on the stack.

Memory <T> is a type complementing Span<T>. As discussed in its design
  document, Span<T> is a stack-only type. The stack-only nature of
  Span<T> makes it unsuitable for many scenarios that require storing
  references to buffers (represented with Span<T>) on the heap, e.g. for
  routines doing asynchronous calls.

async Task DoSomethingAsync(Span<byte> buffer) {
    buffer[0] = 0;
    await Something(); // Oops! The stack unwinds here, but the buffer below
                       // cannot survive the continuation.
    buffer[0] = 1;
}

To address this problem, we will provide a set of complementary types,
  intended to be used as general purpose exchange types representing,
  just like Span <T>, a range of arbitrary memory, but unlike Span <T>
  these types will not be stack-only, at the cost of significant
  performance penalties for reading and writing to the memory.

async Task DoSomethingAsync(Memory<byte> buffer) {
    buffer.Span[0] = 0;
    await Something(); // The stack unwinds here, but it's OK as Memory<T> is
                       // just like any other type.
    buffer.Span[0] = 1;
}

In the sample above, the Memory <byte> is used to represent the buffer.
  It is a regular type and can be used in methods doing asynchronous
  calls. Its Span property returns Span<byte>, but the returned value
  does not get stored on the heap during asynchronous calls, but rather
  new values are produced from the Memory<T> value. In a sense,
  Memory<T> is a factory of Span<T>.

Reference Document: here


问:
angularjs custom sum filter doesn't work
im trying to do sum  operation on my table  Like

```<code>Item   Price
abc    10
xyz    20
Ites=>2   Price=>30
</code>```

For this i wrote simple custome filter

```<code>.filter('SumOfAmt', function () {
    return function (data, key) {
        if (angular.isUndefined(data) || angular.isUndefined(key))
            return 0;
        var sum = 0;
        angular.forEach(data, function (value) {
            sum = sum + parseInt(value[key]);
</code>```

Html code

```<code>  <form name="form1" ng-submit="SaveDb(form1.$valid)" novalidate>

   <b>cost</b><input type="number"  ng-model="cost" required />
</form>
</code>```

This is my Table when user enter in form it display in table

```<code>    <table class="table table-bordered">
 <tr>
                        <td>Name</td>
                        <td>Price</td>
                    </tr>
                    <tr ng-repeat="Emp in EmployeeList">
 <td>{{Emp.EmpName}}</td>
                        <td>{{Emp.Cost | currency}}</td>
                    </tr>
               This is {{EmployeeList|SumOfAmt:'Cost'}}
            </table>
</code>```

答:
And what's wrong?

With your custom filter you can get the right sum, you just need to return sum:

```<code>.filter('SumOfAmt', function () {
    return function (data, key) {
        if (angular.isUndefined(data) || angular.isUndefined(key))
            return 0;
        var sum = 0;
        angular.forEach(data, function (value) {
            sum = sum + parseInt(value[key]);
        });
        return sum;
    };
});
</code>```

But another alternative is:

```<code>.filter('SumOfAmt', function () {
    return function (data, key) {
        if (angular.isUndefined(data) || angular.isUndefined(key))
            return 0;
        return data.map(function(a){return parseInt(a[key])}).reduce((a, b) => a + b, 0);
    };
});
</code>```

Body:
im trying to do sum  operation on my table  Like

Item   Price
abc    10
xyz    20
Ites=>2   Price=>30

For this i wrote simple custome filter

.filter('SumOfAmt', function () {
    return function (data, key) {
        if (angular.isUndefined(data) || angular.isUndefined(key))
            return 0;
        var sum = 0;
        angular.forEach(data, function (value) {
            sum = sum + parseInt(value[key]);

Html code

  <form name="form1" ng-submit="SaveDb(form1.$valid)" novalidate>

   cost<input type="number"  ng-model="cost" required />
</form>

This is my Table when user enter in form it display in table

                        Name
                        Price

 {{Emp.EmpName}}
                        {{Emp.Cost | currency}}

               This is {{EmployeeList|SumOfAmt:'Cost'}}

Body:
And what's wrong?

With your custom filter you can get the right sum, you just need to return sum:

.filter('SumOfAmt', function () {
    return function (data, key) {
        if (angular.isUndefined(data) || angular.isUndefined(key))
            return 0;
        var sum = 0;
        angular.forEach(data, function (value) {
            sum = sum + parseInt(value[key]);
        });
        return sum;
    };
});

But another alternative is:

.filter('SumOfAmt', function () {
    return function (data, key) {
        if (angular.isUndefined(data) || angular.isUndefined(key))
            return 0;
        return data.map(function(a){return parseInt(a[key])}).reduce((a, b) => a + b, 0);
    };
});