问:
SELECT DISTINCT in DataView's RowFilter
I'm trying to narrow down the rows that are in my DataView based on a relation with another table, and the RowFilter I'm using is as follows;

```<code>dv = new DataView(myDS.myTable,
                 "id IN (SELECT DISTINCT parentID FROM myOtherTable)",
                 "name asc",
                 DataViewRowState.CurrentRows);
</code>```

"myTable" and "myOther" table are related via myTable.ID and myOtherTable.parentID, and so the idea is that the DataView should only contain rows from "myTable" which have corresponding child rows in "myOtherTable".

Unfortunately, I'm getting this error;

Syntax error: Missing operand after
  'DISTINCT' operator.

The SQL is fine as far as I am aware, so I'm wondering is there some limitation on using the DISTINCT keyword as part of RowFilter's SQL? Anyone have any idea?

答: Try just leaving out the "DISTINCT". In this case, the results should be the same with or without. Troubleshoot from there.</p>

OwnerDisplayName: El Cristoir

ContentLicense: CC BY-SA 2.5

Title: SELECT DISTINCT in DataView's RowFilter

Body:
I'm trying to narrow down the rows that are in my DataView based on a relation with another table, and the RowFilter I'm using is as follows;

dv = new DataView(myDS.myTable,
                 "id IN (SELECT DISTINCT parentID FROM myOtherTable)",
                 "name asc",
                 DataViewRowState.CurrentRows);

"myTable" and "myOther" table are related via myTable.ID and myOtherTable.parentID, and so the idea is that the DataView should only contain rows from "myTable" which have corresponding child rows in "myOtherTable".

Unfortunately, I'm getting this error;

Syntax error: Missing operand after
  'DISTINCT' operator.

The SQL is fine as far as I am aware, so I'm wondering is there some limitation on using the DISTINCT keyword as part of RowFilter's SQL? Anyone have any idea?

LastEditorDisplayName: Chris Ballance

OwnerDisplayName: Mark A Johnson


来源: stackexchange

问:
css gradient background on  that stretches to 100% width and height
So I'd like to have a gradient that fills 100% of the background of a webpage. For browsers that can't handle it, a solid color is fine.

here is my current css:

```<code>html {
height: 100%;
}
body {
height: 100%;
margin: 0;
padding: 0;
background-repeat: no-repeat;
background: #afb1b4; /* Old browsers */
background: -moz-linear-gradient(top, #afb1b4 0%, #696a6d 100%) no-repeat; /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#afb1b4), color-stop(100%,#696a6d)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#AFB1B4', endColorstr='#696A6D',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* W3C */
}
</code>```

It seemed to work out while the page had little content, but as I've filled out the page with more content, navigation, etcetera, there is now some white at the bottom. maybe 100px or so. Am I doing this wrong? Do I need to be offsetting some padding somewhere?

答:
I also found that adding 'fixed' to the end seemed to do the trick:</p>

```<code>body {
margin: 0;
padding: 0;
background-repeat: no-repeat;
background: #afb1b4; /* Old browsers */
background: -moz-linear-gradient(top, #afb1b4 0%, #696a6d 100%) fixed no-repeat; /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#afb1b4), color-stop(100%,#696a6d)) fixed; /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #afb1b4 0%,#696a6d 100%) fixed; /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #afb1b4 0%,#696a6d 100%) fixed; /* Opera11.10+ */
background: -ms-linear-gradient(top, #afb1b4 0%,#696a6d 100%) fixed; /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#AFB1B4', endColorstr='#696A6D',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #afb1b4 0%,#696a6d 100%) fixed; /* W3C */
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: css gradient background on <body> that stretches to 100% width and height

Body:
So I'd like to have a gradient that fills 100% of the background of a webpage. For browsers that can't handle it, a solid color is fine.

here is my current css:

html {
height: 100%;
}
body {
height: 100%;
margin: 0;
padding: 0;
background-repeat: no-repeat;
background: #afb1b4; /* Old browsers */
background: -moz-linear-gradient(top, #afb1b4 0%, #696a6d 100%) no-repeat; /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#afb1b4), color-stop(100%,#696a6d)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#AFB1B4', endColorstr='#696A6D',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #afb1b4 0%,#696a6d 100%); /* W3C */
}

It seemed to work out while the page had little content, but as I've filled out the page with more content, navigation, etcetera, there is now some white at the bottom. maybe 100px or so. Am I doing this wrong? Do I need to be offsetting some padding somewhere?

Body:
I also found that adding 'fixed' to the end seemed to do the trick:

body {
margin: 0;
padding: 0;
background-repeat: no-repeat;
background: #afb1b4; /* Old browsers */
background: -moz-linear-gradient(top, #afb1b4 0%, #696a6d 100%) fixed no-repeat; /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#afb1b4), color-stop(100%,#696a6d)) fixed; /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #afb1b4 0%,#696a6d 100%) fixed; /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #afb1b4 0%,#696a6d 100%) fixed; /* Opera11.10+ */
background: -ms-linear-gradient(top, #afb1b4 0%,#696a6d 100%) fixed; /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#AFB1B4', endColorstr='#696A6D',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #afb1b4 0%,#696a6d 100%) fixed; /* W3C */
}


问:
Generic throw function for non-nullable types
I am trying to convert an existing project to using nullable reference types properties using non-nullable properties during initialization.

I am using this approach for getting properties which should exist:

public class Dog
{
    private Person? _person;
    public int Id { get; set; }

    public string Name { get; set; }

    public Person Person
    {
        get => _person ?? throw new InvalidOperationException(
            $"Unset property {nameof(_person)}. You probably forgot to Include it");
        set => _person = value;
    }
}
```

<p>But it's tedious to write this for almost every property, so I've tried to make a generic <code>ThrowOrGet()</code> function:</p>

<pre class="lang-cs prettyprint-override"><code>public static class Util
{
    public static T ThrowOrGet<T>([AllowNull] T obj)
    {
        if (obj == null)
        {
            throw new InvalidOperationException(
                $"Unset property {nameof(obj)}. You probably forgot to Include it");
        }
        return obj;
    }
}
</code>```

Which is used like this:

public class Dog
{
    private Person? _person;
    public int Id { get; set; }

    public string Name { get; set; }

    public Person Person
    {
        get =>  Util.ThrowOrGet(_person); ---> "Possible null reference return"
        set => _person = value;
    }
}
```

But the the function Util.ThrowOrGet(_person); now says that it's a possible null reference return. If I inline the function, it works as intended.
Is there a way to make a generic function that does this?

答:
If you're only going to use ThrowOrGet on reference types (which you should, as it doesn't make sense for value types), then you should declare it like this:

public static T ThrowOrGet<T>(T? obj) where T : class
{
    if (obj == null)
    {
        throw new InvalidOperationException(
            $"Unset property {nameof(obj)}. You probably forgot to Include it");
    }
    return obj;
}
```

This says that the function accepts a nullable argument, and always returns a non-nullable  reference. It's better to follow this pattern than rely on the attributes, as they're really just there for complex cases, which this is not.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to convert an existing project to using nullable reference types properties using non-nullable properties during initialization.

I am using this approach for getting properties which should exist:

public class Dog
{
    private Person? _person;
    public int Id { get; set; }

    public string Name { get; set; }

    public Person Person
    {
        get => _person ?? throw new InvalidOperationException(
            $"Unset property {nameof(_person)}. You probably forgot to Include it");
        set => _person = value;
    }
}

But it's tedious to write this for almost every property, so I've tried to make a generic ThrowOrGet() function:

public static class Util
{
    public static T ThrowOrGet<T>([AllowNull] T obj)
    {
        if (obj == null)
        {
            throw new InvalidOperationException(
                $"Unset property {nameof(obj)}. You probably forgot to Include it");
        }
        return obj;
    }
}

Which is used like this:

public class Dog
{
    private Person? _person;
    public int Id { get; set; }

    public string Name { get; set; }

    public Person Person
    {
        get =>  Util.ThrowOrGet(_person); ---> "Possible null reference return"
        set => _person = value;
    }
}

But the the function Util.ThrowOrGet(_person); now says that it's a possible null reference return. If I inline the function, it works as intended.
Is there a way to make a generic function that does this?

Body:
If you're only going to use ThrowOrGet on reference types (which you should, as it doesn't make sense for value types), then you should declare it like this:

public static T ThrowOrGet<T>(T? obj) where T : class
{
    if (obj == null)
    {
        throw new InvalidOperationException(
            $"Unset property {nameof(obj)}. You probably forgot to Include it");
    }
    return obj;
}

This says that the function accepts a nullable argument, and always returns a non-nullable  reference. It's better to follow this pattern than rely on the attributes, as they're really just there for complex cases, which this is not.


问:
Why using  here  (local file) chrome doesnt play the audio?
I want play a local videos using chrome

Using Press here for the video (file in same folder) chrome play the video unless audio. Why?

答:
Playing audio using below HTML5 code </p>

```<code><audio
        controls
        src="file.mp3">
            Your browser does not support the
            <code>audio</code> element.
    </audio>
</code>```

Title: Why using <a href="file.mkv"> here </a> (local file) chrome doesnt play the audio?

Body:
Playing audio using below HTML5 code

<audio
        controls
        src="file.mp3">
            Your browser does not support the
            <code>audio</code> element.
    </audio>


问:
mongoose find collection by _id in a list of array
Here's my Schema

```<code>var PositiveSchema = new mongoose.Schema({
    schoolID: {
        type: mongoose.Schema.Types.ObjectId, ref: 'School'
    },
    name: String,
    restrictAwardTo: Object
})
</code>```

Now restrictAwardTo saves the data in this format

```<code>"restrictAwardTo" : [
        {
            "_id" : "5c31907d908eb8404657cbf0",
            "firstName" : "Admin 2a"
        },
        {
            "_id" : "5c1a7677c98da061141475a8",
            "firstName" : "Justice"
        },
        {
            "_id" : "5c1a7677c98da061141475a9",
            "firstName" : "Itik"
        }
    ],
</code>```

How can I search inside my document using one of the _id listed under restrictAwardTo? I tried the solutions given below

mongooseJS find docs with IDs in an array

mongoose query: find an object by id in an array but it returns empty.

in Robo3t db.getCollection('positives').find({ 'restrictAwardTo._id' : ObjectId('5c31907d908eb8404657cbf0') })

Update: In Robo3t, this query db.getCollection('positives').find({ 'restrictAwardTo._id' : {$in: ['5c1a7677c98da061141475a7']} }) works. Now I'm making it work for mongoose too.

答:
Here's the mongoose that works for me:

```<code>Positive.find({ schoolID:  mongoose.mongo.ObjectId(schoolID), "restrictAwardTo._id": { $in: [userID]} })
</code>```

But I'm not entirely sure of the performance for large records.

Body:
Here's my Schema

var PositiveSchema = new mongoose.Schema({
    schoolID: {
        type: mongoose.Schema.Types.ObjectId, ref: 'School'
    },
    name: String,
    restrictAwardTo: Object
})

Now restrictAwardTo saves the data in this format

"restrictAwardTo" : [
        {
            "_id" : "5c31907d908eb8404657cbf0",
            "firstName" : "Admin 2a"
        },
        {
            "_id" : "5c1a7677c98da061141475a8",
            "firstName" : "Justice"
        },
        {
            "_id" : "5c1a7677c98da061141475a9",
            "firstName" : "Itik"
        }
    ],

How can I search inside my document using one of the _id listed under restrictAwardTo? I tried the solutions given below

mongooseJS find docs with IDs in an array

mongoose query: find an object by id in an array but it returns empty.

in Robo3t db.getCollection('positives').find({ 'restrictAwardTo._id' : ObjectId('5c31907d908eb8404657cbf0') })

Update: In Robo3t, this query db.getCollection('positives').find({ 'restrictAwardTo._id' : {$in: ['5c1a7677c98da061141475a7']} }) works. Now I'm making it work for mongoose too.

Body:
Here's the mongoose that works for me:

Positive.find({ schoolID:  mongoose.mongo.ObjectId(schoolID), "restrictAwardTo._id": { $in: [userID]} })

But I'm not entirely sure of the performance for large records.


问:
Copy id from a table to another
I have a procedure that sets the details of a product, I enter the details as parameters as for now, the details are entered to two different tables the Products table and the Book table, I was able to set the details in place, but I also want to get the ProductID from the Product table to the Book table where the column is also called ProductId.

```<code>ALTER PROCEDURE [dbo].[ProductDetails]

@Name nvarchar(50),
@Deascription nvarchar(255),
@Image image,
@Price nvarchar(50),
@Val1 nvarchar(50),
@Val2 nvarchar(50),
@Val3 nvarchar(50)

AS
     INSERT INTO Products
     VALUES (@Name, @Deascription, @Image, @Price);

     INSERT INTO Book(ISBN, Amount, Auther)
     VALUES (@Val1,@Val2,@Val3);

     INSERT INTO Book(ProductID)  //F_K referencing Products.ProductID
     SELECT ProductID FROM Products
     WHERE Products.ProductName=@Name AND Products.Deascription=@Deascription;
</code>```

This procedure is executed by this.

```<code>exec ProductDetails book23, 'id should be=23', NULL, 23, 233, 23, bookers;
</code>```

Now the problem is that the id shifts 1 row down when its inserted into the second table, check Pics.

答:
It's not shifting. You are doing two INSERT statements with the second one JUST inserting the ProductID.

If you want to insert everything into the same row, do something like:

```<code>INSERT INTO Book
(
    ISBN,
    Amount,
    Author,
    ProductID
)
SELECT
    @Val1,
    @Val2,
    @Val3,
    p.ProductID
FROM Products as p
 WHERE p.ProductName=@Name
 AND p.Description=@Description;
</code>```

NOTE: This is with the corrected spelling mistakes for Description, author and Amount

Title: Copy id from a table to another

Body:
I have a procedure that sets the details of a product, I enter the details as parameters as for now, the details are entered to two different tables the Products table and the Book table, I was able to set the details in place, but I also want to get the ProductID from the Product table to the Book table where the column is also called ProductId.

ALTER PROCEDURE [dbo].[ProductDetails]

@Name nvarchar(50),
@Deascription nvarchar(255),
@Image image,
@Price nvarchar(50),
@Val1 nvarchar(50),
@Val2 nvarchar(50),
@Val3 nvarchar(50)

AS
     INSERT INTO Products
     VALUES (@Name, @Deascription, @Image, @Price);

     INSERT INTO Book(ISBN, Amount, Auther)
     VALUES (@Val1,@Val2,@Val3);

     INSERT INTO Book(ProductID)  //F_K referencing Products.ProductID
     SELECT ProductID FROM Products
     WHERE Products.ProductName=@Name AND Products.Deascription=@Deascription;

This procedure is executed by this.

exec ProductDetails book23, 'id should be=23', NULL, 23, 233, 23, bookers;

Now the problem is that the id shifts 1 row down when its inserted into the second table, check Pics.

Body:
It's not shifting. You are doing two INSERT statements with the second one JUST inserting the ProductID.

If you want to insert everything into the same row, do something like:

INSERT INTO Book
(
    ISBN,
    Amount,
    Author,
    ProductID
)
SELECT
    @Val1,
    @Val2,
    @Val3,
    p.ProductID
FROM Products as p
 WHERE p.ProductName=@Name
 AND p.Description=@Description;

NOTE: This is with the corrected spelling mistakes for Description, author and Amount


问:
Add 2 input values and display result in another input box
I am new to AngularJS. Want to get values from 2 input text boxes, add them and then display them in a 3rd text box.

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.sum = ( $scope.a + $scope.b );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form>
    <input ng-model="a" type="number">
    <input ng-model="b" type="number">
    <input ng-model="sum" type="number">
  </form>
</div>

</body>
</html></code>```

答:
You can achieve without creating any function just put value = {{a+b}} in you 3rd input tag

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.sum = ( $scope.a + $scope.b ); // this will assign value sum only when one time- when controller init happen and that time a and b both is undefined
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form>
    <input ng-model="a" type="number">
    <input ng-model="b" type="number">
    <input value="{{a + b}}" type="number">
  </form>
</div>

</body>
</html></code>```

Body:
I am new to AngularJS. Want to get values from 2 input text boxes, add them and then display them in a 3rd text box.

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.sum = ( $scope.a + $scope.b );
});

<!DOCTYPE html>

  <form>
    <input ng-model="a" type="number">
    <input ng-model="b" type="number">
    <input ng-model="sum" type="number">
  </form>

Body:
You can achieve without creating any function just put value = {{a+b}} in you 3rd input tag

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.sum = ( $scope.a + $scope.b ); // this will assign value sum only when one time- when controller init happen and that time a and b both is undefined
});

<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form>
    <input ng-model="a" type="number">
    <input ng-model="b" type="number">
    <input value="{{a + b}}" type="number">
  </form>
</div>

</body>
</html>


问:
how tfidf value is used in k-means clustering
I am using K-means clustering with TF-IDF using sckit-learn library. I understand that K-means uses distance to create clusters and the distance is represented in (x axis value, y axis value) but the tf-idf is a single numerical value. My question is how is this tf-idf value converted into (x,y) value by K-means clustering.</p>

答:
TF-IDF isn't a single value (i.e. scalar). For every document, it returns a vector where each value in the vector corresponds to each word in the vocabulary.

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from scipy.sparse.csr import csr_matrix

sent1 = "the quick brown fox jumps over the lazy brown dog"
sent2 = "mr brown jumps over the lazy fox"

corpus = [sent1, sent2]
vectorizer = TfidfVectorizer(input=corpus)

X = vectorizer.fit_transform(corpus)
print(X.todense())
</code>```

[out]:

```<code>matrix([[0.50077266, 0.35190925, 0.25038633, 0.25038633, 0.25038633,
         0.        , 0.25038633, 0.35190925, 0.50077266],
        [0.35409974, 0.        , 0.35409974, 0.35409974, 0.35409974,
         0.49767483, 0.35409974, 0.        , 0.35409974]])
</code>```

It returns a 2-D matrix where the rows represents the sentences and the columns represent the vocabulary.

```<code>>>> vectorizer.vocabulary_
{'the': 8,
 'quick': 7,
 'brown': 0,
 'fox': 2,
 'jumps': 3,
 'over': 6,
 'lazy': 4,
 'dog': 1,
 'mr': 5}
</code>```

So when K-means tries to find the distance/similarity between two documents, it's performing the similarity between two rows in the matrix. E.g. assuming the similarity is just the dot product between two rows:

```<code>import numpy as np
vector1 = X.todense()[0]
vector2 = X.todense()[1]
float(np.dot(vector1, vector2.T))
</code>```

[out]:

```<code>0.7092938737640962
</code>```

Chris Potts has a nice tutorial on how vector space models like TF-IDF one is created http://web.stanford.edu/class/linguist236/materials/ling236-handout-05-09-vsm.pdf

Body:
TF-IDF isn't a single value (i.e. scalar). For every document, it returns a vector where each value in the vector corresponds to each word in the vocabulary.

from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from scipy.sparse.csr import csr_matrix

sent1 = "the quick brown fox jumps over the lazy brown dog"
sent2 = "mr brown jumps over the lazy fox"

corpus = [sent1, sent2]
vectorizer = TfidfVectorizer(input=corpus)

X = vectorizer.fit_transform(corpus)
print(X.todense())

[out]:

matrix([[0.50077266, 0.35190925, 0.25038633, 0.25038633, 0.25038633,
         0.        , 0.25038633, 0.35190925, 0.50077266],
        [0.35409974, 0.        , 0.35409974, 0.35409974, 0.35409974,
         0.49767483, 0.35409974, 0.        , 0.35409974]])

It returns a 2-D matrix where the rows represents the sentences and the columns represent the vocabulary.

>>> vectorizer.vocabulary_
{'the': 8,
 'quick': 7,
 'brown': 0,
 'fox': 2,
 'jumps': 3,
 'over': 6,
 'lazy': 4,
 'dog': 1,
 'mr': 5}

So when K-means tries to find the distance/similarity between two documents, it's performing the similarity between two rows in the matrix. E.g. assuming the similarity is just the dot product between two rows:

import numpy as np
vector1 = X.todense()[0]
vector2 = X.todense()[1]
float(np.dot(vector1, vector2.T))

[out]:

0.7092938737640962

Chris Potts has a nice tutorial on how vector space models like TF-IDF one is created http://web.stanford.edu/class/linguist236/materials/ling236-handout-05-09-vsm.pdf


问:
How to make application of Flex for Android?
Actually i have created one dashboard in flex. But now i want to integrate this dashboard or make same dashboard for Android.

How i can achieve this? I want to make dashboard for Android.

Thanks in Advance.

答:
Well, you need to start with tools.  Flash Builder 4.5 is a good start, as it includes the Flex 4.5 SDK, which you will need to build mobile apps.

With Flash Builder, it is very easy to create a new mobile application: File -> New -> Flex Mobile application.

That is the easy part.  What about converting your existing app to work on mobile?  This is where it gets a bit more tricky and will rely on your mad development skills.  :)

You see, it is very rare that a browser or desktop Flex app will translate directly to a mobile device.  The navigation paradigm is different, (including touches without the mouse) and the screen size varies from device to device.  Consider phones and tablets.  Consider landscape and portrait mode.  Each of these profiles will likely make you think about your UI.

Hopefully, you already have good separation between your UI and your behavior.  That will make it a lot easier to develop your mobile app.  You can likely re-use the vast majority of your Actionscript code (behavior) with a new UI.  You might even be able to re-use some of your components.  In all, though, your UI will probably be new.  Note also that the mobile SDK is almost completely Spark, and old MX components can't be used in mobile.

I created a screencast of building a quick mobile app that you might find useful.

I also wrote up a 2-part article about separation and sharing between mobile and other screens.

Good luck!


问:
height in vh (viewport) and max-height in px (pixels)
Is it possible to define height of element where CSS3 tells:

```<code>if viewport >= 1000px then
      element height: 300px (in pixels)
else if viewport < 1000px
      element height: 30vh (30% of viewport height)
</code>```

So all I want is to have an element that has 30% of viewport but not more than 300px. Is it possible?

This is what I've tested but didn't work:

```<code>div {
    height: 30vh;
    max-height: 300px;
}
</code>```

答:
Since there is no gist to check, I'll make a series of assumptions.

The element itself respects the height constraints

The elements within the target overflow outside their parents.

Does adding overflow: hidden to your target element solves the issue?

Regards,

Body:
Is it possible to define height of element where CSS3 tells:

if viewport >= 1000px then
      element height: 300px (in pixels)
else if viewport < 1000px
      element height: 30vh (30% of viewport height)

So all I want is to have an element that has 30% of viewport but not more than 300px. Is it possible?

This is what I've tested but didn't work:

div {
    height: 30vh;
    max-height: 300px;
}


问:
How to pass single quotes and single quote into string variable in Ansible
I'm fairly new to YML and Ansible, however I've been tasked to do some automation for my work.
I have a string variable that need to have double and single quote inside:

```<code>-d 'request=("folder":"Testing_it","attributes":{})'
</code>```

So I've have written quickly a simple play with that would check if it works:

```<code>- name: Assign variable
set_fact:
  params: " -d 'request=(\"folder\":\"Testing_it\",\"attributes\":{})'"

- name: Show output
debug:
  msg: "{{ params }}"
</code>```

I wanted to see how my variable look before continuing and this is output from Ansible:

```<code>    ok: [localhost] => {
    "msg": " -d 'request=(\"folder\":\"Testing_it\",\"attributes\":{})'"
}
</code>```

Why does the backslash is included in that variable ? Can somebody help me how should I properly code that to get it working as intended

Many thanks for your help

答:
You don't need to escape the single quotes, only the double quotes you should escape them with backslash \

to make sure your params variable is properly set, you can output them to a file and see the content:

```<code>- name: Save output
  copy: content="{{ params }}" dest=/path/to/destination/file
</code>```

Body:
I'm fairly new to YML and Ansible, however I've been tasked to do some automation for my work.
I have a string variable that need to have double and single quote inside:

-d 'request=("folder":"Testing_it","attributes":{})'

So I've have written quickly a simple play with that would check if it works:

- name: Assign variable
set_fact:
  params: " -d 'request=(\"folder\":\"Testing_it\",\"attributes\":{})'"

- name: Show output
debug:
  msg: "{{ params }}"

I wanted to see how my variable look before continuing and this is output from Ansible:

    ok: [localhost] => {
    "msg": " -d 'request=(\"folder\":\"Testing_it\",\"attributes\":{})'"
}

Why does the backslash is included in that variable ? Can somebody help me how should I properly code that to get it working as intended

Many thanks for your help

Body:
You don't need to escape the single quotes, only the double quotes you should escape them with backslash \

to make sure your params variable is properly set, you can output them to a file and see the content:

- name: Save output
  copy: content="{{ params }}" dest=/path/to/destination/file


问:
How can i bind xml element with C# model when xml have multiple Same Element?
I cannot bind my c# model with this kind of xml file. Because there is multiple element with same.
This is a example of my XML File.

```<code>  <Type>
       <Loop LoopId="2100A" Name="MEMBER NAME">
         <PER>
           <!--Contact Function Code-->
           <PER01>IP<!--Insured Party--></PER01>
           <PER02 />
           <!--Communication Number Qualifier-->
           <PER03>HP<!--Home Phone Number--></PER03>
           <!--Communication Number-->
           <PER04>6235834409</PER04>
         </PER>
       </Loop>
       <Loop LoopId="2100C" Name="MEMBER MAILING ADDRESS">
         <NM1>
           <!--Entity Identifier Code-->
           <NM101>31<!--Postal Mailing Address--></NM101>
           <!--Entity Type Qualifier-->
           <NM102>1<!--Person--></NM102>
         </NM1>
       </Loop>
       <Loop LoopId="2100G" Name="RESPONSIBLE PERSON">
         <PER>
           <!--Contact Function Code-->
           <PER01>IP<!--Insured Party--></PER01>
           <PER02 />
           <!--Communication Number Qualifier-->
           <PER03>HP<!--Home Phone Number--></PER03>
           <!--Communication Number-->
           <PER04>6235834409</PER04>
         </PER>
         <LM>
           <!--Contact Function Code-->
           <LM01>RP<!--Responsible Person--></LM01>
           <LM02 />
         </LM>
       </Loop>
   </Type>
</code>```

I have use this following code to bind. But Code is not working, cause data binding get confused.

```<code>        [XmlElement(ElementName = "Loop")]
        public L3_L1_MemberName L3_L1_MemberName { get; set; }

        [XmlElement(ElementName = "Loop")]
        public L3_L2_MemberMailingAddress L3_L2_MemberMailingAddress { get; set; }

        [XmlElement(ElementName = "Loop")]
        public L3_L3_ResponsiblePerson L3_L3_ResponsiblePerson { get; set; }
</code>```

答:
based your XML, the model looks like

```<code>[XmlRoot(ElementName = "PER")]
public class PER
{
    [XmlElement(ElementName = "PER01")]
    public string PER01 { get; set; }
    [XmlElement(ElementName = "PER02")]
    public string PER02 { get; set; }
    [XmlElement(ElementName = "PER03")]
    public string PER03 { get; set; }
    [XmlElement(ElementName = "PER04")]
    public string PER04 { get; set; }
}

[XmlRoot(ElementName = "Loop")]
public class Loop
{
    [XmlElement(ElementName = "PER")]
    public PER PER { get; set; }
    [XmlAttribute(AttributeName = "LoopId")]
    public string LoopId { get; set; }
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }
    [XmlElement(ElementName = "NM1")]
    public NM1 NM1 { get; set; }
    [XmlElement(ElementName = "LM")]
    public LM LM { get; set; }
}

[XmlRoot(ElementName = "NM1")]
public class NM1
{
    [XmlElement(ElementName = "NM101")]
    public string NM101 { get; set; }
    [XmlElement(ElementName = "NM102")]
    public string NM102 { get; set; }
}

[XmlRoot(ElementName = "LM")]
public class LM
{
    [XmlElement(ElementName = "LM01")]
    public string LM01 { get; set; }
    [XmlElement(ElementName = "LM02")]
    public string LM02 { get; set; }
}

[XmlRoot(ElementName = "Type")]
public class Type
{
    [XmlElement(ElementName = "Loop")]
    public List<Loop> Loop { get; set; }
}
</code>```

Here is the logic to DeSerialize the XML to Object

```<code>XmlSerializer serializer = new XmlSerializer(typeof(Type));
string xml = File.ReadAllText("XMLFile3.xml");
using (TextReader reader = new StringReader(xml))
{
    var results = (Type)serializer.Deserialize(reader);
    foreach (var item in results.Loop)
    {
        Console.WriteLine($"{item.LoopId} {item.Name}");
        if (item.PER != null)
        {
            Console.WriteLine($"PER:{Regex.Replace(item.PER.PER01, @"\s+", "")}-{Regex.Replace(item.PER.PER02, @"\s+", "")}-{Regex.Replace(item.PER.PER03, @"\s+", "")}-{Regex.Replace(item.PER.PER04, @"\s+", "")}");
        }

        if (item.NM1 != null)
        {
            Console.WriteLine($"NM1:{Regex.Replace(item.NM1.NM101, @"\s+", "")}-{Regex.Replace(item.NM1.NM102, @"\s+", "")}");
        }

        if (item.LM != null)
        {
            Console.WriteLine($"LM:{Regex.Replace(item.LM.LM01, @"\s+", "")}-{Regex.Replace(item.LM.LM02, @"\s+", "")}");
        }
    }
}
</code>```

OUTPUT

```<code>2100A MEMBER NAME
PER:IP--HP-6235834409
2100C MEMBER MAILING ADDRESS
NM1:31-1
2100G RESPONSIBLE PERSON
PER:IP--HP-6235834409
LM:RP-
</code>```

Body:
I cannot bind my c# model with this kind of xml file. Because there is multiple element with same.
This is a example of my XML File.

  <Type>
       <Loop LoopId="2100A" Name="MEMBER NAME">
         <PER>

           <PER01>IP</PER01>
           <PER02 />

           <PER03>HP</PER03>

           <PER04>6235834409</PER04>
         </PER>
       </Loop>
       <Loop LoopId="2100C" Name="MEMBER MAILING ADDRESS">
         <NM1>

           <NM101>31</NM101>

           <NM102>1</NM102>
         </NM1>
       </Loop>
       <Loop LoopId="2100G" Name="RESPONSIBLE PERSON">
         <PER>

           <PER01>IP</PER01>
           <PER02 />

           <PER03>HP</PER03>

           <PER04>6235834409</PER04>
         </PER>
         <LM>

           <LM01>RP</LM01>
           <LM02 />
         </LM>
       </Loop>
   </Type>

I have use this following code to bind. But Code is not working, cause data binding get confused.

        [XmlElement(ElementName = "Loop")]
        public L3_L1_MemberName L3_L1_MemberName { get; set; }

        [XmlElement(ElementName = "Loop")]
        public L3_L2_MemberMailingAddress L3_L2_MemberMailingAddress { get; set; }

        [XmlElement(ElementName = "Loop")]
        public L3_L3_ResponsiblePerson L3_L3_ResponsiblePerson { get; set; }

Body:
based your XML, the model looks like

[XmlRoot(ElementName = "PER")]
public class PER
{
    [XmlElement(ElementName = "PER01")]
    public string PER01 { get; set; }
    [XmlElement(ElementName = "PER02")]
    public string PER02 { get; set; }
    [XmlElement(ElementName = "PER03")]
    public string PER03 { get; set; }
    [XmlElement(ElementName = "PER04")]
    public string PER04 { get; set; }
}

[XmlRoot(ElementName = "Loop")]
public class Loop
{
    [XmlElement(ElementName = "PER")]
    public PER PER { get; set; }
    [XmlAttribute(AttributeName = "LoopId")]
    public string LoopId { get; set; }
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }
    [XmlElement(ElementName = "NM1")]
    public NM1 NM1 { get; set; }
    [XmlElement(ElementName = "LM")]
    public LM LM { get; set; }
}

[XmlRoot(ElementName = "NM1")]
public class NM1
{
    [XmlElement(ElementName = "NM101")]
    public string NM101 { get; set; }
    [XmlElement(ElementName = "NM102")]
    public string NM102 { get; set; }
}

[XmlRoot(ElementName = "LM")]
public class LM
{
    [XmlElement(ElementName = "LM01")]
    public string LM01 { get; set; }
    [XmlElement(ElementName = "LM02")]
    public string LM02 { get; set; }
}

[XmlRoot(ElementName = "Type")]
public class Type
{
    [XmlElement(ElementName = "Loop")]
    public List<Loop> Loop { get; set; }
}

Here is the logic to DeSerialize the XML to Object

XmlSerializer serializer = new XmlSerializer(typeof(Type));
string xml = File.ReadAllText("XMLFile3.xml");
using (TextReader reader = new StringReader(xml))
{
    var results = (Type)serializer.Deserialize(reader);
    foreach (var item in results.Loop)
    {
        Console.WriteLine($"{item.LoopId} {item.Name}");
        if (item.PER != null)
        {
            Console.WriteLine($"PER:{Regex.Replace(item.PER.PER01, @"\s+", "")}-{Regex.Replace(item.PER.PER02, @"\s+", "")}-{Regex.Replace(item.PER.PER03, @"\s+", "")}-{Regex.Replace(item.PER.PER04, @"\s+", "")}");
        }

        if (item.NM1 != null)
        {
            Console.WriteLine($"NM1:{Regex.Replace(item.NM1.NM101, @"\s+", "")}-{Regex.Replace(item.NM1.NM102, @"\s+", "")}");
        }

        if (item.LM != null)
        {
            Console.WriteLine($"LM:{Regex.Replace(item.LM.LM01, @"\s+", "")}-{Regex.Replace(item.LM.LM02, @"\s+", "")}");
        }
    }
}

OUTPUT

2100A MEMBER NAME
PER:IP--HP-6235834409
2100C MEMBER MAILING ADDRESS
NM1:31-1
2100G RESPONSIBLE PERSON
PER:IP--HP-6235834409
LM:RP-


问:
CURL not working in Docker Image [Unable to access the host in Docker image]
Docker File

```<code># Start from the latest golang base image
FROM golang:latest

# Add Maintainer Info
LABEL maintainer="Sumit Thakur <sumitthakur@yahoo.com>"

# Set the Current Working Directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the Working Directory inside the container
COPY . .

# Build the Go app
RUN go build -o testapp myapplication.go testapp.go

# Expose port 50051 / for internal comunication

ENV PORT 50051
RUN echo $PORT

EXPOSE ${PORT}

# Command to run the executable
CMD ["./testapp"]
</code>```

Build Docker file with

```<code>docker build -t testapp  -f Dockerfile .
</code>```

that's perfect working

Run Docker file

```<code>docker run -d -p 50051:50051 testapp
</code>```

that's will also working fine

I check with the running container

docker ps
```

<p>this will give me</p>

<pre class="lang-sh prettyprint-override"><code>CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                      NAMES
57cd3c01bcda        testapp           "./testapp"       2 seconds ago       Up 2 seconds        0.0.0.0:50051->50051/tcp   gracious_bhaskara
</code>```

and when i check the network inspect with

docker network inspect bridge
```

<p>this will give me</p>

```[
    {
        "Name": "bridge",
        "Id": "30850a823d3040e7d8eaf804c122ce3d26b35650f6f792cf1f4ce77d66167eeb",
        "Created": "2020-02-19T07:34:24.993299775Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "57cd3c01bcda3fbf7d0bf67136ebbb8afb312c4f6ca70eeee15cda6e10fff4e2": {
                "Name": "gracious_bhaskara",
                "EndpointID": "2a42056609e8140d190f1efde41320138867d3905053e7f381bd91b1f053c251",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]
```

<p>Everthing works fine
Except when i trying to connect the docker host</p>

<pre class="lang-sh prettyprint-override"><code>curl -H "Content-type:application/json" -X GET 'https://localhost:50051/testapp/v1/order'
or
curl -H "Content-type:application/json" -X GET 'https://172.17.0.2:50051/testapp/v1/order'
</code>```

it gives me

Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 0.0.0.0...
* TCP_NODELAY set
* Connected to 0.0.0.0 (127.0.0.1) port 50051 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number
* stopped the pause stream!
* Closing connection 0
curl: (35) error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number
```

<p>Test openssl:</p>

```openssl s_client https://localhost:50051/testapp/v1/order -connect localhost:50051
```

<p>Result:</p>

```CONNECTED(00000005)
4488771180:error:140040E5:SSL routines:CONNECT_CR_SRVR_HELLO:ssl handshake failure:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.200.4/l
ibressl-2.6/ssl/ssl_pkt.c:585:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 0 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1582109828
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
---
```

<p>Application Code</p>

```package main

import (
    "io"
    "net/http"
    "github.com/gorilla/handlers"
)
func main() {
    http.HandleFunc("/testapp/v1/order", testHandler)
    headersOk := handlers.AllowedHeaders([]string{""})
    http.ListenAndServe(":50051", headersOk)
}
func testHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Heyyy!")
}
```

Anyone Help I'm stuck here 1-2 days don't know what to do ?

答:
From the discussion in the comment, the problem seems related to the https handshake.

A simple solution, is to query the service using the following URL:

curl -H "Content-type:application/json" -X GET 'https://localhost:50051/testapp/v1/order' -v -k
```

Using the -k, you are going to ignore the HTTPS validation.

NOTE: i've changed the URL from http to https.

Body:
Docker File

# Start from the latest golang base image
FROM golang:latest

# Add Maintainer Info
LABEL maintainer="Sumit Thakur <sumitthakur@yahoo.com>"

# Set the Current Working Directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the Working Directory inside the container
COPY . .

# Build the Go app
RUN go build -o testapp myapplication.go testapp.go

# Expose port 50051 / for internal comunication

ENV PORT 50051
RUN echo $PORT

EXPOSE ${PORT}

# Command to run the executable
CMD ["./testapp"]

Build Docker file with

docker build -t testapp  -f Dockerfile .

that's perfect working

Run Docker file

docker run -d -p 50051:50051 testapp

that's will also working fine

I check with the running container

docker ps

this will give me

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                      NAMES
57cd3c01bcda        testapp           "./testapp"       2 seconds ago       Up 2 seconds        0.0.0.0:50051->50051/tcp   gracious_bhaskara

and when i check the network inspect with

docker network inspect bridge

this will give me

[
    {
        "Name": "bridge",
        "Id": "30850a823d3040e7d8eaf804c122ce3d26b35650f6f792cf1f4ce77d66167eeb",
        "Created": "2020-02-19T07:34:24.993299775Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "57cd3c01bcda3fbf7d0bf67136ebbb8afb312c4f6ca70eeee15cda6e10fff4e2": {
                "Name": "gracious_bhaskara",
                "EndpointID": "2a42056609e8140d190f1efde41320138867d3905053e7f381bd91b1f053c251",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]

Everthing works fine
Except when i trying to connect the docker host

curl -H "Content-type:application/json" -X GET 'https://localhost:50051/testapp/v1/order'
or
curl -H "Content-type:application/json" -X GET 'https://172.17.0.2:50051/testapp/v1/order'

it gives me

Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 0.0.0.0...
* TCP_NODELAY set
* Connected to 0.0.0.0 (127.0.0.1) port 50051 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number
* stopped the pause stream!
* Closing connection 0
curl: (35) error:1400410B:SSL routines:CONNECT_CR_SRVR_HELLO:wrong version number

Test openssl:

openssl s_client https://localhost:50051/testapp/v1/order -connect localhost:50051

Result:

CONNECTED(00000005)
4488771180:error:140040E5:SSL routines:CONNECT_CR_SRVR_HELLO:ssl handshake failure:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.200.4/l
ibressl-2.6/ssl/ssl_pkt.c:585:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 0 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1582109828
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
---

Application Code

package main

import (
    "io"
    "net/http"
    "github.com/gorilla/handlers"
)
func main() {
    http.HandleFunc("/testapp/v1/order", testHandler)
    headersOk := handlers.AllowedHeaders([]string{""})
    http.ListenAndServe(":50051", headersOk)
}
func testHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Heyyy!")
}

Anyone Help I'm stuck here 1-2 days don't know what to do ?

Body:
From the discussion in the comment, the problem seems related to the https handshake.

A simple solution, is to query the service using the following URL:

curl -H "Content-type:application/json" -X GET 'https://localhost:50051/testapp/v1/order' -v -k

Using the -k, you are going to ignore the HTTPS validation.

NOTE: i've changed the URL from http to https.


问:
JMeter - Exclude response timings of failed transaction from HTML report
By default JMeter will include the response time of failed transactions in the calculation of the HTML report.
In my case, failed transaction will return much faster than successful ones, and are thus lowering down the average response time significantly.

Is there a way to exclude the timings of failed responses from the JMeter HTML report, while still reporting the errors itself?

I tried changing the jmeter.reportgenerator.exporter.html.series_filter parameter to only filter for success samples, as suggested here, but without success

答:
You're looking into the wrong response as the guy doesn't really know JMeter, as per Sample Configuration chapter:

```<code># Indicates which graph series are filtered (regular expression)
# In the below example we filter on Search and Order samples
# Note that the end of the pattern should always include (-success|-failure)?$
# Transactions per second suffixes Transactions with "-success" or "-failure" depending
# on the result
</code>```

so basically jmeter.reportgenerator.exporter.html.series_filter sampler is for filtering sample results depending on their label.

If you want to see only successful transactions response times - the feature is there already since JMeter 3.1: Response Time Percentiles Over Time (successful responses) graph

Body:
You're looking into the wrong response as the guy doesn't really know JMeter, as per Sample Configuration chapter:

# Indicates which graph series are filtered (regular expression)
# In the below example we filter on Search and Order samples
# Note that the end of the pattern should always include (-success|-failure)?$
# Transactions per second suffixes Transactions with "-success" or "-failure" depending
# on the result

so basically jmeter.reportgenerator.exporter.html.series_filter sampler is for filtering sample results depending on their label.

If you want to see only successful transactions response times - the feature is there already since JMeter 3.1: Response Time Percentiles Over Time (successful responses) graph


问:
Most efficient way of adding objects together
I was wondering if there is a quick way of adding attributes in objects together. If I had a 'Person' class like this and I was trying to add the 'age' attribute together from multiple 'Person' objects, then I could override the add function:

```<code> class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __add__(self, other):
        return self.age + other.age
</code>```

This works well for two objects, but if I had a list of 'Person' objects and I was trying to sum all the age attributes using the reduce() fuction for example, then this approach wouldn't work (to my knowledge), as the overriden add method would be trying to sum different types together as we are returning a float from the add function, not a 'Person' object.

I could get the age attribute from each 'Person' object and add it together but I was wondering if there was a more efficient way of handling this.

答:
It does not logically make sense to add two people when what you want to add is their ages. Your problem is because if p1 + p2 is a number, then (p1 + p2) + p3 is a number plus a person, and you only defined how to add a person to a person, not add a person to a number.

But the root cause is that this is not a sensible case for overloading __add__. That only makes sense when the result would be another instance of the same class, not a number. Instead, just get the ages and add those. Note that this is not less efficient than operator overloading; it doesn't involve any attribute lookups that wouldn't have to be done either way.

p1.age + p2.age

# or on a list:
sum(p.age for p in people)
```

"Explicit is better than implicit."

Body:
I was wondering if there is a quick way of adding attributes in objects together. If I had a 'Person' class like this and I was trying to add the 'age' attribute together from multiple 'Person' objects, then I could override the add function:

 class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __add__(self, other):
        return self.age + other.age

This works well for two objects, but if I had a list of 'Person' objects and I was trying to sum all the age attributes using the reduce() fuction for example, then this approach wouldn't work (to my knowledge), as the overriden add method would be trying to sum different types together as we are returning a float from the add function, not a 'Person' object.

I could get the age attribute from each 'Person' object and add it together but I was wondering if there was a more efficient way of handling this.

Body:
It does not logically make sense to add two people when what you want to add is their ages. Your problem is because if p1 + p2 is a number, then (p1 + p2) + p3 is a number plus a person, and you only defined how to add a person to a person, not add a person to a number.

But the root cause is that this is not a sensible case for overloading __add__. That only makes sense when the result would be another instance of the same class, not a number. Instead, just get the ages and add those. Note that this is not less efficient than operator overloading; it doesn't involve any attribute lookups that wouldn't have to be done either way.

p1.age + p2.age

# or on a list:
sum(p.age for p in people)

"Explicit is better than implicit."


问:
Instant crash when trying to convert readline before any input has been made
I'm making a simple method where I'm going to use console input to pick a students number from a list, now for some reason the program crashes before I've pressed enter while reading the line and the VS tells me Input string was not in the correct format.

```<code> var whoisthestudent = Console.ReadLine();
 int who = Convert.ToInt32(whoisthestudent);
</code>```

So here's the part of the program that crashes, these are the first two lines of the method and when it crashes it gives me the format exception. I just can't figure out why it starts converting the readline before I've written anything or pressed enter?

答:
Use int.TryParse to be on the safer side

```<code>Int studentId;
var whoisthestudent = Console.ReadLine();
 If(int.TryParse(whoisthestudent, out studentId)
{
        Console.WriteLine(studentId);
} else
{
        Console.WriteLine("Failed to convert" );
}
</code>```

Body:
I'm making a simple method where I'm going to use console input to pick a students number from a list, now for some reason the program crashes before I've pressed enter while reading the line and the VS tells me Input string was not in the correct format.

 var whoisthestudent = Console.ReadLine();
 int who = Convert.ToInt32(whoisthestudent);

So here's the part of the program that crashes, these are the first two lines of the method and when it crashes it gives me the format exception. I just can't figure out why it starts converting the readline before I've written anything or pressed enter?

Body:
Use int.TryParse to be on the safer side

Int studentId;
var whoisthestudent = Console.ReadLine();
 If(int.TryParse(whoisthestudent, out studentId)
{
        Console.WriteLine(studentId);
} else
{
        Console.WriteLine("Failed to convert" );
}


问:
Axios: chaining multiple API requests
I need to chain a few API requests from the Google Maps API, and I'm trying to do it with Axios.

Here is the first request, which is in componentWillMount()

```<code>axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1)
  .then(response => this.setState({ p1Location: response.data }))  }
</code>```

Here is the second request:

```<code>axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2)
  .then(response => this.setState({ p2Location: response.data }))
</code>```

Then we have a third request, which is dependent on the first two being completed:

```<code>axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + this.state.p1Location.results.place_id + '&destination=place_id:' + this.state.p2Location.results.place_id + '&key=' + 'API-KEY-HIDDEN')
  .then(response => this.setState({ route: response.data }))
</code>```

How can I chain these three calls so that the third happens after the first two?

答:
create array of promise and then use reduce.</p>

```<code>/**
 * Runs promises from array of functions that can return promises
 * in chained manner
 *
 * @param {array} arr - promise arr
 * @return {Object} promise object
 */
function runPromiseInSequence(arr, input) {
  return arr.reduce(
    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
    Promise.resolve(input)
  )
}

// promise function 1
function p1(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 5)
  })
}

// promise function 2
function p2(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 2)
  })
}

// function 3  - will be wrapped in a resolved promise by .then()
function f3(a) {
 return a * 3
}

// promise function 4
function p4(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 4)
  })
}

const promiseArr = [p1, p2, f3, p4]
runPromiseInSequence(promiseArr, 10)
  .then(console.log)   // 1200
</code>```

Title: Axios: chaining multiple API requests

Body:
I need to chain a few API requests from the Google Maps API, and I'm trying to do it with Axios.

Here is the first request, which is in componentWillMount()

axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1)
  .then(response => this.setState({ p1Location: response.data }))  }

Here is the second request:

axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2)
  .then(response => this.setState({ p2Location: response.data }))

Then we have a third request, which is dependent on the first two being completed:

axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + this.state.p1Location.results.place_id + '&destination=place_id:' + this.state.p2Location.results.place_id + '&key=' + 'API-KEY-HIDDEN')
  .then(response => this.setState({ route: response.data }))

How can I chain these three calls so that the third happens after the first two?

Body:
create array of promise and then use reduce.

/**
 * Runs promises from array of functions that can return promises
 * in chained manner
 *
 * @param {array} arr - promise arr
 * @return {Object} promise object
 */
function runPromiseInSequence(arr, input) {
  return arr.reduce(
    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
    Promise.resolve(input)
  )
}

// promise function 1
function p1(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 5)
  })
}

// promise function 2
function p2(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 2)
  })
}

// function 3  - will be wrapped in a resolved promise by .then()
function f3(a) {
 return a * 3
}

// promise function 4
function p4(a) {
  return new Promise((resolve, reject) => {
    resolve(a * 4)
  })
}

const promiseArr = [p1, p2, f3, p4]
runPromiseInSequence(promiseArr, 10)
  .then(console.log)   // 1200


问:
Why is Python printing my file directory has changed, but when I check through file manager, it hasn't changed?
I have a Python script, and I'm using os.chdir. I want to change my python file directory to the path below. My current code is:

```<code>        path = "C:\\Users\\Jalen\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
        os.chdir(path)
</code>```

I'm using os.cwd()after running that and it prints the new path the file is supposed to be in. However, when I look in the new path on file explorer, the python file isn't there. Any help? Sort of new to Python.

答:
os.chdir just change the directory it working on. You should try this:

```<code>path = "C:\\Users\\Jalen\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
itself = open(__file__, 'r').readline()
new = open(path, 'w+')
for line in itself:
    new.write(line)
</code>```

Body:
I have a Python script, and I'm using os.chdir. I want to change my python file directory to the path below. My current code is:

        path = "C:\\Users\\Jalen\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
        os.chdir(path)

I'm using os.cwd()after running that and it prints the new path the file is supposed to be in. However, when I look in the new path on file explorer, the python file isn't there. Any help? Sort of new to Python.

Body:
os.chdir just change the directory it working on. You should try this:

path = "C:\\Users\\Jalen\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
itself = open(__file__, 'r').readline()
new = open(path, 'w+')
for line in itself:
    new.write(line)


问:
C++ CMake compilation error (/usr/bin/ld: cannot find <LIBRARY_NAME>)
*I know there are lots of questions about this, but they simply don't help much when talking about CMake, hence my decision of making the question *

So I was working on CLion which uses CMake in order to import and give parameters to the compiler, and successfully included (imported) an external library (cereal: to serialize classes into json files) located on a folder called "ExternalLibraries" which is on the root of my project folder. It was working just fine, untill I restarted the IDE and tried to ran the code again... It returned a compilation error (I think).

My CMake file looks like this:

```<code>cmake_minimum_required(VERSION 3.3)
project(xMemory)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

include_directories ("${PROJECT_SOURCE_DIR}/ExternalLibraries/cereal-1.1.2/include/")

set(SOURCE_FILES main.cpp xObject.cpp xObject.h)
add_executable(xMemory ${SOURCE_FILES})
target_link_libraries (xMemory cereal)
</code>```

And when I try to run/compile the shell gives me this:

```<code>/home/lunaticsoul/Documents/clion-1.2.4/bin/cmake/bin/cmake --build /home/lunaticsoul/.CLion12/system/cmake/generated/95701c38/95701c38/Debug0 --target xMemory -- -j 4
Scanning dependencies of target xMemory
[ 33%] Building CXX object CMakeFiles/xMemory.dir/xObject.cpp.o
[ 66%] Building CXX object CMakeFiles/xMemory.dir/main.cpp.o
[100%] Linking CXX executable xMemory
/usr/bin/ld: cannot find -lcereal
collect2: error: ld returned 1 exit status
make[3]: *** [xMemory] Error 1
make[2]: *** [CMakeFiles/xMemory.dir/all] Error 2
make[1]: *** [CMakeFiles/xMemory.dir/rule] Error 2
make: *** [xMemory] Error 2
</code>```

I'm not sure about what is happening cause the library seems to actually import into the code (There are no red letters when including cereal) and as I said before, I think it just stopped working.

Can someone tell me if there is something wrong with my CMake file?

PD: Here's a screenshot just in case anyone need it.

PD2: I'm using elementary os: Freya (Ubuntu 14.04)

答:
I'm a bit late to the party, but maybe this will help someone.
I had a very similar issue with googletest:

```<code>dpoliaru@host:~/Documents/test/gtest/build$ make
Scanning dependencies of target s1
[ 50%] Building CXX object CMakeFiles/s1.dir/s1.cpp.o
[100%] Linking CXX executable s1
/usr/bin/ld: cannot find -lgtest
/usr/bin/ld: cannot find -lgmock
/usr/bin/ld: cannot find -lgtest
/usr/bin/ld: cannot find -lgmock
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/s1.dir/build.make:84: s1] Error 1
make[1]: *** [CMakeFiles/Makefile2:73: CMakeFiles/s1.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
dpoliaru@host:~/Documents/test/gtest/build$
</code>```

Here is an approach I used to debug it:

Make sure you can build manually:

compile:

```<code>g++ -c -m64 -I/home/dpoliaru/.local/lib/pkgconfig/../../include s1.cpp
</code>```

and link:

```<code>g++ -L/home/dpoliaru/.local/lib/pkgconfig/../../lib s1.o -o s1 -lgtest -lgmock -lpthread
</code>```

Make sure cmake properly locates libraries during generation stage:

```<code>dpoliaru@host:~/Documents/test/gtest/build$ cmake -L .. -D CMAKE_BUILD_TYPE=Debug
-- The C compiler identification is GNU 9.2.1
-- The CXX compiler identification is GNU 9.2.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1")
-- Checking for module 'gtest'
--   Found gtest, version 1.10.0
-- Checking for module 'gmock'
--   Found gmock, version 1.10.0
-- Configuring done
-- Generating done
-- Build files have been written to: /home/dpoliaru/Documents/test/gtest/build
-- Cache values
CMAKE_BUILD_TYPE:STRING=Debug
CMAKE_INSTALL_PREFIX:PATH=/usr/local
pkgcfg_lib_GMOCK_gmock:FILEPATH=/home/dpoliaru/.local/lib/libgmock.a
pkgcfg_lib_GMOCK_gtest:FILEPATH=/home/dpoliaru/.local/lib/libgtest.a
pkgcfg_lib_GMOCK_pthread:FILEPATH=/usr/lib/x86_64-linux-gnu/libpthread.so
pkgcfg_lib_GTEST_gtest:FILEPATH=/home/dpoliaru/.local/lib/libgtest.a
pkgcfg_lib_GTEST_pthread:FILEPATH=/usr/lib/x86_64-linux-gnu/libpthread.so
dpoliaru@host:~/Documents/test/gtest/build$
</code>```

Finally, rin CMakeLists.txt, I updated linker directory search paths per @mustafagonlu advice using target_link_directories() cmake-commands(7).

target_link_directories(${PROJECT_NAME} PUBLIC ${GTEST_LIBRARY_DIRS} ${GMOCK_LDFLAGS})

And it worked.

Body:
*I know there are lots of questions about this, but they simply don't help much when talking about CMake, hence my decision of making the question *

So I was working on CLion which uses CMake in order to import and give parameters to the compiler, and successfully included (imported) an external library (cereal: to serialize classes into json files) located on a folder called "ExternalLibraries" which is on the root of my project folder. It was working just fine, untill I restarted the IDE and tried to ran the code again... It returned a compilation error (I think).

My CMake file looks like this:

cmake_minimum_required(VERSION 3.3)
project(xMemory)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

include_directories ("${PROJECT_SOURCE_DIR}/ExternalLibraries/cereal-1.1.2/include/")

set(SOURCE_FILES main.cpp xObject.cpp xObject.h)
add_executable(xMemory ${SOURCE_FILES})
target_link_libraries (xMemory cereal)

And when I try to run/compile the shell gives me this:

/home/lunaticsoul/Documents/clion-1.2.4/bin/cmake/bin/cmake --build /home/lunaticsoul/.CLion12/system/cmake/generated/95701c38/95701c38/Debug0 --target xMemory -- -j 4
Scanning dependencies of target xMemory
[ 33%] Building CXX object CMakeFiles/xMemory.dir/xObject.cpp.o
[ 66%] Building CXX object CMakeFiles/xMemory.dir/main.cpp.o
[100%] Linking CXX executable xMemory
/usr/bin/ld: cannot find -lcereal
collect2: error: ld returned 1 exit status
make[3]: *** [xMemory] Error 1
make[2]: *** [CMakeFiles/xMemory.dir/all] Error 2
make[1]: *** [CMakeFiles/xMemory.dir/rule] Error 2
make: *** [xMemory] Error 2

I'm not sure about what is happening cause the library seems to actually import into the code (There are no red letters when including cereal) and as I said before, I think it just stopped working.

Can someone tell me if there is something wrong with my CMake file?

PD: Here's a screenshot just in case anyone need it.

PD2: I'm using elementary os: Freya (Ubuntu 14.04)

Body:
I'm a bit late to the party, but maybe this will help someone.
I had a very similar issue with googletest:

dpoliaru@host:~/Documents/test/gtest/build$ make
Scanning dependencies of target s1
[ 50%] Building CXX object CMakeFiles/s1.dir/s1.cpp.o
[100%] Linking CXX executable s1
/usr/bin/ld: cannot find -lgtest
/usr/bin/ld: cannot find -lgmock
/usr/bin/ld: cannot find -lgtest
/usr/bin/ld: cannot find -lgmock
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/s1.dir/build.make:84: s1] Error 1
make[1]: *** [CMakeFiles/Makefile2:73: CMakeFiles/s1.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
dpoliaru@host:~/Documents/test/gtest/build$

Here is an approach I used to debug it:

Make sure you can build manually:

compile:

g++ -c -m64 -I/home/dpoliaru/.local/lib/pkgconfig/../../include s1.cpp

and link:

g++ -L/home/dpoliaru/.local/lib/pkgconfig/../../lib s1.o -o s1 -lgtest -lgmock -lpthread

Make sure cmake properly locates libraries during generation stage:

dpoliaru@host:~/Documents/test/gtest/build$ cmake -L .. -D CMAKE_BUILD_TYPE=Debug
-- The C compiler identification is GNU 9.2.1
-- The CXX compiler identification is GNU 9.2.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1")
-- Checking for module 'gtest'
--   Found gtest, version 1.10.0
-- Checking for module 'gmock'
--   Found gmock, version 1.10.0
-- Configuring done
-- Generating done
-- Build files have been written to: /home/dpoliaru/Documents/test/gtest/build
-- Cache values
CMAKE_BUILD_TYPE:STRING=Debug
CMAKE_INSTALL_PREFIX:PATH=/usr/local
pkgcfg_lib_GMOCK_gmock:FILEPATH=/home/dpoliaru/.local/lib/libgmock.a
pkgcfg_lib_GMOCK_gtest:FILEPATH=/home/dpoliaru/.local/lib/libgtest.a
pkgcfg_lib_GMOCK_pthread:FILEPATH=/usr/lib/x86_64-linux-gnu/libpthread.so
pkgcfg_lib_GTEST_gtest:FILEPATH=/home/dpoliaru/.local/lib/libgtest.a
pkgcfg_lib_GTEST_pthread:FILEPATH=/usr/lib/x86_64-linux-gnu/libpthread.so
dpoliaru@host:~/Documents/test/gtest/build$

Finally, rin CMakeLists.txt, I updated linker directory search paths per @mustafagonlu advice using target_link_directories() cmake-commands(7).

target_link_directories(${PROJECT_NAME} PUBLIC ${GTEST_LIBRARY_DIRS} ${GMOCK_LDFLAGS})

And it worked.


问:
Run Powershell script to show a form without Powershell screen at the back
I have a powershell script that can be run locally on a Workstation or remotely using PSEXEC tool, that shows a dialog box to console user that the PC is going to be rebooted in X amount of time and timer. The dialog box cannot be closed, only be minimized (this is as per code). However when I run it, it also shows Powershell screen at the back of dialog box and closing it also closes the form.

I tried Powershell switches [-NoLogo], [-NonInteractive], [-WindowStyle Hidden], it doesn't work.

This is the custom-restart script:

```<code>Function Create-GetSchedTime {
Param(
$SchedTime
)
      $script:StartTime = (Get-Date).AddSeconds($TotalTime)
      $RestartDate = ((get-date).AddSeconds($TotalTime)).AddMinutes(-5)
      $RDate = (Get-Date $RestartDate -f 'dd.MM.yyyy') -replace "\.","/"      # 16/03/2016
      $RTime = Get-Date $RestartDate -f 'HH:mm'                                    # 09:31
      #&schtasks /delete /tn "Post Maintenance Restart" /f
      #&schtasks /create /sc once /tn "Post Maintenance Restart" /tr "'C:\Windows\system32\cmd.exe' /c shutdown -r -f -t 300" /SD $RDate /ST $RTime /f
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic") | Out-Null
$Title = "Computer Reboot Notification"
$Message = "Your computer will automatically restart in :"
$Button1Text = "Restart now"
$Button2Text = "Postpone for 1 hour"
$Button3Text = "Postpone for 4 hours"
$Form = $null
$Button1 = $null
$Button2 = $null
$Label = $null
$TextBox = $null
$Result = $null
$timerUpdate = New-Object 'System.Windows.Forms.Timer'
#$TotalTime = 14400 #in seconds
$TotalTime = 60 #in seconds
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate_Tick={
      # Define countdown timer
      [TimeSpan]$span = $script:StartTime - (Get-Date)
      # Update the display
      $hours = "{0:00}" -f $span.Hours
      $mins = "{0:00}" -f $span.Minutes
    $secs = "{0:00}" -f $span.Seconds
    $labelTime.Text = "{0}:{1}:{2}" -f $hours, $mins, $secs
      $timerUpdate.Start()
      if ($span.TotalSeconds -le 0)
      {
            $timerUpdate.Stop()
            &schtasks /delete /tn "Post Maintenance Restart" /f
            shutdown -r -f /t 0
      }
}
$Form_StoreValues_Closing=
      {
            #Store the control values
      }

$Form_Cleanup_FormClosed=
      {
            #Remove all event handlers from the controls
            try
            {
                  $Form.remove_Load($Form_Load)
                  $timerUpdate.remove_Tick($timerUpdate_Tick)
                  #$Form.remove_Load($Form_StateCorrection_Load)
                  $Form.remove_Closing($Form_StoreValues_Closing)
                  $Form.remove_FormClosed($Form_Cleanup_FormClosed)
            }
            catch [Exception]
            { }
      }

# Form
$Form = New-Object -TypeName System.Windows.Forms.Form
$Form.Text = $Title
$Form.Size = New-Object -TypeName System.Drawing.Size(407,205)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $true
$Form.KeyPreview = $true
$Form.ShowInTaskbar = $Formalse
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $Formalse
$Form.MinimizeBox = $true
$Icon = [system.drawing.icon]::ExtractAssociatedIcon("c:\Windows\System32\UserAccountControlSettings.exe")
$Form.Icon = $Icon

# Button One (Reboot/Shutdown Now)
$Button1 = New-Object -TypeName System.Windows.Forms.Button
$Button1.Size = New-Object -TypeName System.Drawing.Size(90,25)
$Button1.Location = New-Object -TypeName System.Drawing.Size(10,135)
$Button1.Text = $Button1Text
$Button1.Font = 'Tahoma, 10pt'
$Button1.Add_Click({
      &schtasks /delete /tn "Post Maintenance Restart" /f
      shutdown -r -f /t 0
      $Form.Close()
})
$Form.Controls.Add($Button1)
# Button Two (Postpone for 1 Hour)
$Button2 = New-Object -TypeName System.Windows.Forms.Button
$Button2.Size = New-Object -TypeName System.Drawing.Size(133,25)
$Button2.Location = New-Object -TypeName System.Drawing.Size(105,135)
$Button2.Text = $Button2Text
$Button2.Font = 'Tahoma, 10pt'
$Button2.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      #$TotalTime = 3600
      $TotalTime = 30
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button2)

# Button Three (Postpone for 4 Hours)
$Button3 = New-Object -TypeName System.Windows.Forms.Button
$Button3.Size = New-Object -TypeName System.Drawing.Size(140,25)
$Button3.Location = New-Object -TypeName System.Drawing.Size(243,135)
$Button3.Text = $Button3Text
$Button3.Font = 'Tahoma, 10pt'
$Button3.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 14400
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button3)
$Button3.Enabled = $False

# Label
$Label = New-Object -TypeName System.Windows.Forms.Label
$Label.Size = New-Object -TypeName System.Drawing.Size(330,25)
$Label.Location = New-Object -TypeName System.Drawing.Size(10,15)
$Label.Text = $Message
$label.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label)

# Label2
$Label2 = New-Object -TypeName System.Windows.Forms.Label
$Label2.Size = New-Object -TypeName System.Drawing.Size(355,30)
$Label2.Location = New-Object -TypeName System.Drawing.Size(10,100)
$Label2.Text = $Message2
$label2.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label2)

# labelTime
$labelTime = New-Object 'System.Windows.Forms.Label'
$labelTime.AutoSize = $True
$labelTime.Font = 'Arial, 26pt, style=Bold'
$labelTime.Location = '120, 60'
$labelTime.Name = 'labelTime'
$labelTime.Size = '43, 15'
$labelTime.TextAlign = 'MiddleCenter'
$labelTime.ForeColor = "Red"
$Form.Controls.Add($labelTime)

#Start the timer
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
# Show
$Form.Add_Shown({$Form.Activate()})
#Clean up the control events
$Form.add_FormClosed($Form_Cleanup_FormClosed)
#Store the control values when form is closing
#$Form.add_Closing($Form_StoreValues_Closing)
$Form.Add_Closing({$_.cancel = $true})
#Show the Form
$Form.ShowDialog() | Out-Null
#$Form.Focused
#return $Form.ShowDialog()

#$Form.Add_Closing({$_.cancel = $false})
#Show the Form
#return $Form.ShowDialog()
</code>```

答:
You need to use .NET for this. Here is a function:

```<code># .Net methods for hiding/showing the console in the background
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'

function Show-Console
{
    $consolePtr = [Console.Window]::GetConsoleWindow()
    $consolePtr = [Console.Window]::GetConsoleWindow()

    # Hide = 0,
    # ShowNormal = 1,
    # ShowMinimized = 2,
    # ShowMaximized = 3,
    # Maximize = 3,
    # ShowNormalNoActivate = 4,
    # Show = 5,
    # Minimize = 6,
    # ShowMinNoActivate = 7,
    # ShowNoActivate = 8,
    # Restore = 9,
    # ShowDefault = 10,
    # ForceMinimized = 11

    [Console.Window]::ShowWindow($consolePtr, 4)
function Hide-Console
{
    $consolePtr = [Console.Window]::GetConsoleWindow()
    #0 hide
    [Console.Window]::ShowWindow($consolePtr, 0)
}
</code>```

Now call it in the Form_Load event.

```<code>$OnFormLoad =
{
    Hide-Console
}
</code>```

To show again use Show-Console.

Attribution: Opening PowerShell Script and hide Command Prompt, but not the GUI

Body:
I have a powershell script that can be run locally on a Workstation or remotely using PSEXEC tool, that shows a dialog box to console user that the PC is going to be rebooted in X amount of time and timer. The dialog box cannot be closed, only be minimized (this is as per code). However when I run it, it also shows Powershell screen at the back of dialog box and closing it also closes the form.

I tried Powershell switches [-NoLogo], [-NonInteractive], [-WindowStyle Hidden], it doesn't work.

This is the custom-restart script:

Function Create-GetSchedTime {
Param(
$SchedTime
)
      $script:StartTime = (Get-Date).AddSeconds($TotalTime)
      $RestartDate = ((get-date).AddSeconds($TotalTime)).AddMinutes(-5)
      $RDate = (Get-Date $RestartDate -f 'dd.MM.yyyy') -replace "\.","/"      # 16/03/2016
      $RTime = Get-Date $RestartDate -f 'HH:mm'                                    # 09:31
      #&schtasks /delete /tn "Post Maintenance Restart" /f
      #&schtasks /create /sc once /tn "Post Maintenance Restart" /tr "'C:\Windows\system32\cmd.exe' /c shutdown -r -f -t 300" /SD $RDate /ST $RTime /f
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic") | Out-Null
$Title = "Computer Reboot Notification"
$Message = "Your computer will automatically restart in :"
$Button1Text = "Restart now"
$Button2Text = "Postpone for 1 hour"
$Button3Text = "Postpone for 4 hours"
$Form = $null
$Button1 = $null
$Button2 = $null
$Label = $null
$TextBox = $null
$Result = $null
$timerUpdate = New-Object 'System.Windows.Forms.Timer'
#$TotalTime = 14400 #in seconds
$TotalTime = 60 #in seconds
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate_Tick={
      # Define countdown timer
      [TimeSpan]$span = $script:StartTime - (Get-Date)
      # Update the display
      $hours = "{0:00}" -f $span.Hours
      $mins = "{0:00}" -f $span.Minutes
    $secs = "{0:00}" -f $span.Seconds
    $labelTime.Text = "{0}:{1}:{2}" -f $hours, $mins, $secs
      $timerUpdate.Start()
      if ($span.TotalSeconds -le 0)
      {
            $timerUpdate.Stop()
            &schtasks /delete /tn "Post Maintenance Restart" /f
            shutdown -r -f /t 0
      }
}
$Form_StoreValues_Closing=
      {
            #Store the control values
      }

$Form_Cleanup_FormClosed=
      {
            #Remove all event handlers from the controls
            try
            {
                  $Form.remove_Load($Form_Load)
                  $timerUpdate.remove_Tick($timerUpdate_Tick)
                  #$Form.remove_Load($Form_StateCorrection_Load)
                  $Form.remove_Closing($Form_StoreValues_Closing)
                  $Form.remove_FormClosed($Form_Cleanup_FormClosed)
            }
            catch [Exception]
            { }
      }

# Form
$Form = New-Object -TypeName System.Windows.Forms.Form
$Form.Text = $Title
$Form.Size = New-Object -TypeName System.Drawing.Size(407,205)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $true
$Form.KeyPreview = $true
$Form.ShowInTaskbar = $Formalse
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $Formalse
$Form.MinimizeBox = $true
$Icon = [system.drawing.icon]::ExtractAssociatedIcon("c:\Windows\System32\UserAccountControlSettings.exe")
$Form.Icon = $Icon

# Button One (Reboot/Shutdown Now)
$Button1 = New-Object -TypeName System.Windows.Forms.Button
$Button1.Size = New-Object -TypeName System.Drawing.Size(90,25)
$Button1.Location = New-Object -TypeName System.Drawing.Size(10,135)
$Button1.Text = $Button1Text
$Button1.Font = 'Tahoma, 10pt'
$Button1.Add_Click({
      &schtasks /delete /tn "Post Maintenance Restart" /f
      shutdown -r -f /t 0
      $Form.Close()
})
$Form.Controls.Add($Button1)
# Button Two (Postpone for 1 Hour)
$Button2 = New-Object -TypeName System.Windows.Forms.Button
$Button2.Size = New-Object -TypeName System.Drawing.Size(133,25)
$Button2.Location = New-Object -TypeName System.Drawing.Size(105,135)
$Button2.Text = $Button2Text
$Button2.Font = 'Tahoma, 10pt'
$Button2.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      #$TotalTime = 3600
      $TotalTime = 30
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button2)

# Button Three (Postpone for 4 Hours)
$Button3 = New-Object -TypeName System.Windows.Forms.Button
$Button3.Size = New-Object -TypeName System.Drawing.Size(140,25)
$Button3.Location = New-Object -TypeName System.Drawing.Size(243,135)
$Button3.Text = $Button3Text
$Button3.Font = 'Tahoma, 10pt'
$Button3.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 14400
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button3)
$Button3.Enabled = $False

# Label
$Label = New-Object -TypeName System.Windows.Forms.Label
$Label.Size = New-Object -TypeName System.Drawing.Size(330,25)
$Label.Location = New-Object -TypeName System.Drawing.Size(10,15)
$Label.Text = $Message
$label.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label)

# Label2
$Label2 = New-Object -TypeName System.Windows.Forms.Label
$Label2.Size = New-Object -TypeName System.Drawing.Size(355,30)
$Label2.Location = New-Object -TypeName System.Drawing.Size(10,100)
$Label2.Text = $Message2
$label2.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label2)

# labelTime
$labelTime = New-Object 'System.Windows.Forms.Label'
$labelTime.AutoSize = $True
$labelTime.Font = 'Arial, 26pt, style=Bold'
$labelTime.Location = '120, 60'
$labelTime.Name = 'labelTime'
$labelTime.Size = '43, 15'
$labelTime.TextAlign = 'MiddleCenter'
$labelTime.ForeColor = "Red"
$Form.Controls.Add($labelTime)

#Start the timer
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
# Show
$Form.Add_Shown({$Form.Activate()})
#Clean up the control events
$Form.add_FormClosed($Form_Cleanup_FormClosed)
#Store the control values when form is closing
#$Form.add_Closing($Form_StoreValues_Closing)
$Form.Add_Closing({$_.cancel = $true})
#Show the Form
$Form.ShowDialog() | Out-Null
#$Form.Focused
#return $Form.ShowDialog()

#$Form.Add_Closing({$_.cancel = $false})
#Show the Form
#return $Form.ShowDialog()

Body:
You need to use .NET for this. Here is a function:

# .Net methods for hiding/showing the console in the background
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'

function Show-Console
{
    $consolePtr = [Console.Window]::GetConsoleWindow()
    $consolePtr = [Console.Window]::GetConsoleWindow()

    # Hide = 0,
    # ShowNormal = 1,
    # ShowMinimized = 2,
    # ShowMaximized = 3,
    # Maximize = 3,
    # ShowNormalNoActivate = 4,
    # Show = 5,
    # Minimize = 6,
    # ShowMinNoActivate = 7,
    # ShowNoActivate = 8,
    # Restore = 9,
    # ShowDefault = 10,
    # ForceMinimized = 11

    [Console.Window]::ShowWindow($consolePtr, 4)
function Hide-Console
{
    $consolePtr = [Console.Window]::GetConsoleWindow()
    #0 hide
    [Console.Window]::ShowWindow($consolePtr, 0)
}

Now call it in the Form_Load event.

$OnFormLoad =
{
    Hide-Console
}

To show again use Show-Console.

Attribution: Opening PowerShell Script and hide Command Prompt, but not the GUI


问:
How to multiply array elements by condition
I have a array and want to multiply the elements greater than 9 by 2 and lesser than or equal to 9 by 3.

```<code>  List<Integer> list = Arrays.asList(3, 6, 9, 12, 15);
  list.stream().map(number -> number * 3).forEach(System.out::println);
</code>```

This one multiplies everything by 3 , where

```<code>list.stream().filter(number -> number>3).map(number -> number * 3).forEach(System.out::println);
</code>```

this one multiplies but also filters.

I want 3 ,6 ,9 multiplied by 3 and 12, 15 multiplied by 2.

Any help is appreciated.

答:
You can do this.
You don't need a filter , you are mapping with a condition.

list.stream()
    .map(number -> number > 9 ? number * 2 : number * 3)
    .forEach(System.out::println);

```

Body:
I have a array and want to multiply the elements greater than 9 by 2 and lesser than or equal to 9 by 3.

  List<Integer> list = Arrays.asList(3, 6, 9, 12, 15);
  list.stream().map(number -> number * 3).forEach(System.out::println);

This one multiplies everything by 3 , where

list.stream().filter(number -> number>3).map(number -> number * 3).forEach(System.out::println);

this one multiplies but also filters.

I want 3 ,6 ,9 multiplied by 3 and 12, 15 multiplied by 2.

Any help is appreciated.