问:
Remove a specific string only if it's in the very end of a code
I'm parsing a html file to extract part of its text to create an epub. The problem is that in the text extracted sometimes the last paragraph is an empty one that I would like to remove. So... how can I remove this blank paragraph (and any additional blank spaces after that) with the condition that there's no additional text later on in any other line of code?

For example:

```<code><p> </p>
<p>“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”</p>
<p>Sed ut perspiciatis unde omnis iste natus error...</p>
<p> </p>
<p>“Lorem ipsum dolor sit amet.”</p>
<p>Omnis iste natus error sit voluptatem.</p>
<p> </p>
</code>```

So, what can I do to remove only this last instance of

 (and any additional blank spaces/newlines after that) from the code above?

I have tried using this negative lookahead

\s*?(?!
) on perl-regex to exclude later paragraphs from the search, but it still finds the previous instances of

 and I only need to remove this paragraph when it's the last one in the file.

Thank you in advance!

EDIT-1:

To be clear, I want this:

```<code><p> </p>
<p>“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”</p>
<p>Sed ut perspiciatis unde omnis iste natus error...</p>
<p> </p>
<p>“Lorem ipsum dolor sit amet.”</p>
<p>Omnis iste natus error sit voluptatem.</p>
<p> </p>
</code>```

to become this:

```<code><p> </p>
<p>“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”</p>
<p>Sed ut perspiciatis unde omnis iste natus error...</p>
<p> </p>
<p>“Lorem ipsum dolor sit amet.”</p>
<p>Omnis iste natus error sit voluptatem.</p>
</code>```

i.e. I want to remove the

 only in the last line (where there's no other text after it), so I want to know which perl-regex search I should use to find only this particular instance of this string so I can replace it with nothing and with that remove it from the code.

EDIT-2.:

Based on a suggestion by ikegami, I used \s*(?>

\s*)(?!
)\s* as the search string to find only the last blank paragraph (

)of the html code to be removed. What really made the difference in his answer seems to have been the use of an atomic grouping (?>...). Without it, I was picking other instances of the same string from other lines of the code that I didn't want. Not sure why (really not an expert on regex), but that's what I got from my tests.

I'm just using some basic find/replace operations of perl-regex in an ebook editor to clean the code, so I'm not sure about how it will behave under other circumstances. Anyway, I appreciate the other attempts of helping me, some of which were even too technical for me to grasp and I hope this answer will help someone in the future with a similar problem. Thank you again!

答:
I wouldn't use regexes at all. As you'll see, that's the complicated approach.

If you want to check make sure there's no
 anywhere after the

\s*

You want to check that none of the the following characters are the start of
.

You need to check that all of the following characters aren't the start of
.

You want:

```<code>s/(?><p> </p>\s*)(?=(?:(?!<p>).)*\z)//s
</code>```

Other changes:

The ? in \s*? makes no sense; you don't want to match the fewest.

(?>...) prevents the pattern from starting to look for
 inside of

\s*. In this particular pattern (but not the one below), it simply acts as an optimization.

If you want to check make sure there's no
 immediately after

\s*

You want:

```<code>s/(?><p> </p>\s*)(?!<p>)//
</code>```

Body:
I'm parsing a html file to extract part of its text to create an epub. The problem is that in the text extracted sometimes the last paragraph is an empty one that I would like to remove. So... how can I remove this blank paragraph (and any additional blank spaces after that) with the condition that there's no additional text later on in any other line of code?

For example:

“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”

Sed ut perspiciatis unde omnis iste natus error...

“Lorem ipsum dolor sit amet.”

Omnis iste natus error sit voluptatem.

So, what can I do to remove only this last instance of

 (and any additional blank spaces/newlines after that) from the code above?

I have tried using this negative lookahead

\s*?(?!
) on perl-regex to exclude later paragraphs from the search, but it still finds the previous instances of

 and I only need to remove this paragraph when it's the last one in the file.

Thank you in advance!

EDIT-1:

To be clear, I want this:

“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”

Sed ut perspiciatis unde omnis iste natus error...

“Lorem ipsum dolor sit amet.”

Omnis iste natus error sit voluptatem.

to become this:

“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”

Sed ut perspiciatis unde omnis iste natus error...

“Lorem ipsum dolor sit amet.”

Omnis iste natus error sit voluptatem.

i.e. I want to remove the

 only in the last line (where there's no other text after it), so I want to know which perl-regex search I should use to find only this particular instance of this string so I can replace it with nothing and with that remove it from the code.

EDIT-2.:

Based on a suggestion by ikegami, I used \s*(?>

\s*)(?!
)\s* as the search string to find only the last blank paragraph (

)of the html code to be removed. What really made the difference in his answer seems to have been the use of an atomic grouping (?>...). Without it, I was picking other instances of the same string from other lines of the code that I didn't want. Not sure why (really not an expert on regex), but that's what I got from my tests.

I'm just using some basic find/replace operations of perl-regex in an ebook editor to clean the code, so I'm not sure about how it will behave under other circumstances. Anyway, I appreciate the other attempts of helping me, some of which were even too technical for me to grasp and I hope this answer will help someone in the future with a similar problem. Thank you again!

Body:
I wouldn't use regexes at all. As you'll see, that's the complicated approach.

If you want to check make sure there's no <p> anywhere after the <p>&nbsp;</p>\s*

You want to check that none of the the following characters are the start of <p>.

You need to check that all of the following characters aren't the start of <p>.

You want:

s/(?><p>&nbsp;</p>\s*)(?=(?:(?!<p>).)*\z)//s

Other changes:

The ? in \s*? makes no sense; you don't want to match the fewest.

(?>...) prevents the pattern from starting to look for <p> inside of <p>&nbsp;</p>\s*. In this particular pattern (but not the one below), it simply acts as an optimization.

If you want to check make sure there's no <p> immediately after <p>&nbsp;</p>\s*

You want:

s/(?><p>&nbsp;</p>\s*)(?!<p>)//


来源: stackexchange

问:
Relaunch app from code inside app iOS swift
I need to relaunch my app when the user completes an in app purchase. Is this possible without any user action.

What I really need is to avoid the navigation controller that is associated with the subscribe link in a table view controller.

Once a user subscribes I can get from the subscribe table view to the main app but the navigation controller tags along covering up all of my navigation items in all of the views in the main app.

答:
There isn't any way to relaunch the app from the springboard. You might just want to refresh the current view. Apple is pretty restrictive. You can also tell the user to force quit the app, but I don't think that is great UX. Good luck! Hope this answers your question.

Cheers,
Theo

ContentLicense: CC BY-SA 3.0


问:
CSS Transition Background Gradient (Hack)
I'm trying to use the background-position/transition hack found here and here to animate the background transition of a panel on hover... I'm not sure what I'm doing wrong but it isn't working for me.

Here's the relevant code I have so far (using Bootstrap v3)

html:

```<code><div class="panel panel-default">
  <div class="panel-body">
    <span class="glyphicon glyphicon-link" aria-hidden="true"></span>
    <strong>Portfolio Name:    </strong>Foo
  </div>
</div>
</code>```

scss:

```<code>.panel,
.panel-default {
  border-radius: 3rem;
  cursor: pointer;
  cursor: hand;
  overflow: hidden;
}

.panel-body {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f4f4f4));
  background-image: -webkit-linear-gradient(#fff, #f4f4f4);
  background-image: -moz-linear-gradient(#fff, #f4f4f4);
  background-image: -o-linear-gradient(#fff, #f4f4f4);
  background-image: linear-gradient(#fff, #f4f4f4);
  -webkit-background-size: auto 200%;
  background-size: auto 200%;
  background-position: 0 100%;
  font-size: medium;
  padding-left: 56px;
  padding-left: 3.5rem;
  -webkit-transition: all 1s linear;
  -moz-transition: all 1s linear;
  -o-transition: all 1s linear;
  transition: all 1s linear;

  .glyphicon-link {
    padding-right: 56px;
    padding-right: 3.5rem;
  }
}

.panel-body:hover {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#093479));
  background-image: -webkit-linear-gradient(#337ab7, #093479);
  background-image: -moz-linear-gradient(#337ab7, #093479);
  background-image: -o-linear-gradient(#337ab7, #093479);
  background-image: linear-gradient(#337ab7, #093479);
  background-position: 0 0;
  color: white;
  padding-left: 88px;
  padding-left: 5.5rem;
}

.panel-body:active {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#1eb759), to(#4f8547));
  background-image: -webkit-linear-gradient(#1eb759, #4f8547);
  background-image: -moz-linear-gradient(#1eb759, #4f8547);
  background-image: -o-linear-gradient(#1eb759, #4f8547);
  background-image: linear-gradient(#1eb759, #4f8547);
}
</code>```

I also set up a jsfiddle here:

答:
You're setting a new background-image on :hover - you just want to adjust the background-position on :hover instead.

.panel,
.panel-default {
  border-radius: 3rem;
  cursor: pointer;
  cursor: hand;
  overflow: hidden;
}

.panel-body {
  background-image: -webkit-linear-gradient(top, #fff 0%, #f4f4f4 25%, #337ab7 75%, #093479 100%);
  background-image: linear-gradient(to bottom, #fff 0%, #f4f4f4 25%, #337ab7 75%, #093479 100%);
  background-size: auto 400%;
  background-position: 0 0;
  font-size: medium;
  padding-left: 56px;
  padding-left: 3.5rem;
  -webkit-transition: all 1s linear;
  transition: all 1s linear;
}
.panel-body .glyphicon-link {
  padding-right: 56px;
  padding-right: 3.5rem;
}

.panel-body:hover {
  background-position: 0 100%;
  color: white;
  padding-left: 88px;
  padding-left: 5.5rem;
}

.panel-body:active {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#1eb759), to(#4f8547));
  background-image: -webkit-linear-gradient(#1eb759, #4f8547);
  background-image: linear-gradient(#1eb759, #4f8547);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

<div class="panel panel-default">
  <div class="panel-body">
    <span class="glyphicon glyphicon-link" aria-hidden="true"></span>
    <strong>Portfolio Name:    </strong>Foo
  </div>
</div></code>```

Body:
I'm trying to use the background-position/transition hack found here and here to animate the background transition of a panel on hover... I'm not sure what I'm doing wrong but it isn't working for me.

Here's the relevant code I have so far (using Bootstrap v3)

html:

    Portfolio Name:    Foo

scss:

.panel,
.panel-default {
  border-radius: 3rem;
  cursor: pointer;
  cursor: hand;
  overflow: hidden;
}

.panel-body {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f4f4f4));
  background-image: -webkit-linear-gradient(#fff, #f4f4f4);
  background-image: -moz-linear-gradient(#fff, #f4f4f4);
  background-image: -o-linear-gradient(#fff, #f4f4f4);
  background-image: linear-gradient(#fff, #f4f4f4);
  -webkit-background-size: auto 200%;
  background-size: auto 200%;
  background-position: 0 100%;
  font-size: medium;
  padding-left: 56px;
  padding-left: 3.5rem;
  -webkit-transition: all 1s linear;
  -moz-transition: all 1s linear;
  -o-transition: all 1s linear;
  transition: all 1s linear;

  .glyphicon-link {
    padding-right: 56px;
    padding-right: 3.5rem;
  }
}

.panel-body:hover {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#093479));
  background-image: -webkit-linear-gradient(#337ab7, #093479);
  background-image: -moz-linear-gradient(#337ab7, #093479);
  background-image: -o-linear-gradient(#337ab7, #093479);
  background-image: linear-gradient(#337ab7, #093479);
  background-position: 0 0;
  color: white;
  padding-left: 88px;
  padding-left: 5.5rem;
}

.panel-body:active {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#1eb759), to(#4f8547));
  background-image: -webkit-linear-gradient(#1eb759, #4f8547);
  background-image: -moz-linear-gradient(#1eb759, #4f8547);
  background-image: -o-linear-gradient(#1eb759, #4f8547);
  background-image: linear-gradient(#1eb759, #4f8547);
}

I also set up a jsfiddle here:

Body:
You're setting a new background-image on :hover - you just want to adjust the background-position on :hover instead.

.panel,
.panel-default {
  border-radius: 3rem;
  cursor: pointer;
  cursor: hand;
  overflow: hidden;
}

.panel-body {
  background-image: -webkit-linear-gradient(top, #fff 0%, #f4f4f4 25%, #337ab7 75%, #093479 100%);
  background-image: linear-gradient(to bottom, #fff 0%, #f4f4f4 25%, #337ab7 75%, #093479 100%);
  background-size: auto 400%;
  background-position: 0 0;
  font-size: medium;
  padding-left: 56px;
  padding-left: 3.5rem;
  -webkit-transition: all 1s linear;
  transition: all 1s linear;
}
.panel-body .glyphicon-link {
  padding-right: 56px;
  padding-right: 3.5rem;
}

.panel-body:hover {
  background-position: 0 100%;
  color: white;
  padding-left: 88px;
  padding-left: 5.5rem;
}

.panel-body:active {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#1eb759), to(#4f8547));
  background-image: -webkit-linear-gradient(#1eb759, #4f8547);
  background-image: linear-gradient(#1eb759, #4f8547);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

<div class="panel panel-default">
  <div class="panel-body">
    <span class="glyphicon glyphicon-link" aria-hidden="true"></span>
    <strong>Portfolio Name: &nbsp;&nbsp;&nbsp;</strong>Foo
  </div>
</div>


问:
Error: $injector:modulerr Module Error p0=task
i have a simple angular code with wont run due to this error;
ive add the angular-router file the server found it but it keeps giving me this error

```<code>Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=task&p1=Error%3A%20…0Uc%20(http%3A%2F%2Flocalhost%3A3000%2Fangular%2Fangular.min.js%3A22%3A332)
    at angular.min.js:7
    at angular.min.js:43
    at p (angular.min.js:8)
    at g (angular.min.js:42)
    at gb (angular.min.js:46)
    at c (angular.min.js:22)
    at Uc (angular.min.js:22)
    at xe (angular.min.js:21)
    at angular.min.js:333
    at HTMLDocument.b (angular.min.js:38)
</code>```

my view code is

```<code><html >
    <head>
        <title>
        </title>
    </head>
    <body ng-app="task" ng-init="first = 1;">
        <h1>Task List</h1>

        <div ng-controller="ctrl">
            <span>Values: {{first}}</span>
            <input type="text" ng-model="first" />
        </div>

        <script src="angular/angular.min.js"></script>
        <script src="bower_components/angular-route/angular-route.js"></script>
         <script src="angular/app.js"></script>
    </body>

</html>
</code>```

my app.js code

```<code>var task = angular.module('myApp', ['ngRoute']);
task.controller('ctrl', function($scope){
    $scope.first = 1;
});
</code>```

please help.

答:
The error message clearly states:

Failed to instantiate module task due to:
  Error: …0Uc (http://localhost:3000/angular/angular.min.js:22:332)

The module name needs to match the name used in the ng-app directive:

```<code><body ng-app="task" ng-init="first = 1;">
</code>```

```<code>//var task = angular.module('myApp', ['ngRoute']);
var task = angular.module('task', ['ngRoute']);
task.controller('ctrl', function($scope){
    $scope.first = 1;
});
</code>```

Body:
i have a simple angular code with wont run due to this error;
ive add the angular-router file the server found it but it keeps giving me this error

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=task&p1=Error%3A%20…0Uc%20(http%3A%2F%2Flocalhost%3A3000%2Fangular%2Fangular.min.js%3A22%3A332)
    at angular.min.js:7
    at angular.min.js:43
    at p (angular.min.js:8)
    at g (angular.min.js:42)
    at gb (angular.min.js:46)
    at c (angular.min.js:22)
    at Uc (angular.min.js:22)
    at xe (angular.min.js:21)
    at angular.min.js:333
    at HTMLDocument.b (angular.min.js:38)

my view code is

        <title>
        </title>

Task List

            Values: {{first}}
            <input type="text" ng-model="first" />

my app.js code

var task = angular.module('myApp', ['ngRoute']);
task.controller('ctrl', function($scope){
    $scope.first = 1;
});

please help.

Body:
The error message clearly states:

Failed to instantiate module task due to:
  Error: …0Uc (http://localhost:3000/angular/angular.min.js:22:332)

The module name needs to match the name used in the ng-app directive:

<body ng-app="task" ng-init="first = 1;">

//var task = angular.module('myApp', ['ngRoute']);
var task = angular.module('task', ['ngRoute']);
task.controller('ctrl', function($scope){
    $scope.first = 1;
});


问:
MySQL Database Insert
I have very strange problem. I want to run mysql query as it is shown down below, but it's not working. Connection to database is successful, INSERT query is ok too, because when I run it directly in phpmyadmin Console it works, but it's not working here in PHP code.

Could you tell me what I'm missing?

```<code>$servername = "localhost";
$username = "admin";
$password = "admin123";
$dbname = "database1";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO last_visit (ip, lastvisit) VALUES ('123', '123')";
</code>```

答:
You need to run your $sql, because now your $sql is only a string, it does nothing.

Add this :

```<code>if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
</code>```

Title: MySQL Database Insert

Body:
I have very strange problem. I want to run mysql query as it is shown down below, but it's not working. Connection to database is successful, INSERT query is ok too, because when I run it directly in phpmyadmin Console it works, but it's not working here in PHP code.

Could you tell me what I'm missing?

$servername = "localhost";
$username = "admin";
$password = "admin123";
$dbname = "database1";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO last_visit (ip, lastvisit) VALUES ('123', '123')";

Body:
You need to run your $sql, because now your $sql is only a string, it does nothing.

Add this :

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}


问:
Sequelize 4.0: Custom instanceMethods for all sequelize models
how do we create custom instance methods to be applied/inherited by all models with sequelize 4.2? In sequelize 3 we used to have an "instanceMethods: {custom1: function (){} }" in the "define" section of a main model which was extended to all other models. How do we achieve the same behaviour with sequelize 4.0?</p>

答:
Instance methods get called independently of the "define" section now. I just got mine to work on V4 by doing something like this:

```<code>const User = sequelize.define('users', {
 name: {type: Sequelize.TEXT}
});
User.prototype.custom1 = function() {
  //function
};
</code>```

I can still call the instance method in any file in which the User model is imported. I hope this helps! This is the doc I used for reference:

Body:
Instance methods get called independently of the "define" section now. I just got mine to work on V4 by doing something like this:

const User = sequelize.define('users', {
 name: {type: Sequelize.TEXT}
});
User.prototype.custom1 = function() {
  //function
};

I can still call the instance method in any file in which the User model is imported. I hope this helps! This is the doc I used for reference:


问:
Testing REST webservices
My organization is working on building RESTful webservices on JBoss appserver. The QA team is used to testing SOAP webservices so far using SoapUI. SoapUI has a new version that has REST capabilities. We're considering using that.

Are there any publicly available RESTful services available on the net for free that someone could test ?

What tools are available(and used) for testing RESTful web services ?

答: you can use the Simple REST Client is an extension for Google Chrome too https://chrome.google.com/webstore/detail/fhjcajmcbmldlhcimfajhfbgofnpcjmb</p>

OwnerDisplayName: anjanb

Title: Testing REST webservices

LastEditorDisplayName: anjanb

ContentLicense: CC BY-SA 2.5


问:
The good way to cascade creation / removing collection in mongoose
Is the right way to make several removal of collection the first or the second one ?

I feel that it is the second one but the first one is more easy to use. Is it possible to use promise to ease the read of the code?

First way:

```<code>beforeEach((done) => {
    //Before each test we empty the database

    //Remove Roles
    Role.remove({}, (err) => {});

    //Remove Users
    User.remove({}, (err) => {});

    // Remove Workouts
    Workout.remove({}, (err) => {});

    // Create user
    Role.create({"name" : "Administrator"},(err, adminRole) => {
        User.create({ firstname : "***", businessId: "1", lastname : "***", email : "***", roles:[adminRole]}, (err) => {
            done();
        });
    });
});`
</code>```

Second way:

```<code>beforeEach((done) => {
    //Before each test we empty the database

    //Remove Roles
    Role.remove({}, (err) => {
        //Remove Users
        User.remove({}, (err) => {
            // Remove Workouts
            Workout.remove({}, (err) => {
                // Create user
                Role.create({"name" : "Administrator"},(err, adminRole) => {
                    User.create({ firstname : "***", businessId: "1", lastname : "***", email : "***", roles:[adminRole]}, (err) => {
                        done();
                    });
                });
            });
        });
    });
});
</code>```

答:
The second option is the safest one, because if an error happens in a operation, the next ones are not executed.

And sure you should use promises. The code becomes way cleaner:

```<code>Role.remove({})
  .then(() => User.remove({})
  .then(() => Workout.remove({})
  .then(() => Role.create({"name" : "Administrator"})
  .then((adminRole) => User.create({ firstname : "***", businessId: "1", lastname : "***", email : "***", roles:[adminRole]})
  .then(() => done())
  .catch((error) => ...);
</code>```

To be able to use promises, you can set the promise of mongoose to be the native one (as long as your node version is >= 6):

```<code>mongoose.Promise = global.Promise;
</code>```

Body:
Is the right way to make several removal of collection the first or the second one ?

I feel that it is the second one but the first one is more easy to use. Is it possible to use promise to ease the read of the code?

First way:

beforeEach((done) => {
    //Before each test we empty the database

    //Remove Roles
    Role.remove({}, (err) => {});

    //Remove Users
    User.remove({}, (err) => {});

    // Remove Workouts
    Workout.remove({}, (err) => {});

    // Create user
    Role.create({"name" : "Administrator"},(err, adminRole) => {
        User.create({ firstname : "***", businessId: "1", lastname : "***", email : "***", roles:[adminRole]}, (err) => {
            done();
        });
    });
});`

Second way:

beforeEach((done) => {
    //Before each test we empty the database

    //Remove Roles
    Role.remove({}, (err) => {
        //Remove Users
        User.remove({}, (err) => {
            // Remove Workouts
            Workout.remove({}, (err) => {
                // Create user
                Role.create({"name" : "Administrator"},(err, adminRole) => {
                    User.create({ firstname : "***", businessId: "1", lastname : "***", email : "***", roles:[adminRole]}, (err) => {
                        done();
                    });
                });
            });
        });
    });
});

Body:
The second option is the safest one, because if an error happens in a operation, the next ones are not executed.

And sure you should use promises. The code becomes way cleaner:

Role.remove({})
  .then(() => User.remove({})
  .then(() => Workout.remove({})
  .then(() => Role.create({"name" : "Administrator"})
  .then((adminRole) => User.create({ firstname : "***", businessId: "1", lastname : "***", email : "***", roles:[adminRole]})
  .then(() => done())
  .catch((error) => ...);

To be able to use promises, you can set the promise of mongoose to be the native one (as long as your node version is >= 6):

mongoose.Promise = global.Promise;


问:
Returning value if it's 0
i have following class

```<code>@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class Order {
    private OrderId orderId;
    private int daysElapsed;
    private List<Item> items;
}
</code>```

Right now, if daysElapsed is 0 it is not included as part of response object. I want it to be there. Is there something provided by jackson which can handle this?

I was thinking to use Integer class and use annotation NON_NULL to exclude it. Is there a better approach to do so?

答:
You're only including NON_DEFAULT values. The default value of an int field is 0. So when daysElapsed is 0, its value is equal to the default value, so is not included in the JSON.

Just remove the @JsonInclude(JsonInclude.Include.NON_DEFAULT) annotation.

Title: Returning value if it's 0

Body:
i have following class

@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class Order {
    private OrderId orderId;
    private int daysElapsed;
    private List<Item> items;
}

Right now, if daysElapsed is 0 it is not included as part of response object. I want it to be there. Is there something provided by jackson which can handle this?

I was thinking to use Integer class and use annotation NON_NULL to exclude it. Is there a better approach to do so?


问:
How can I define a custom pipeline directive?
For example something like: </p>

```<code>pipeline {
   customDirective {
      sh "env"
      ..
   }
}
</code>```

答: This is currently not possible. You can only define custom pipeline steps via a Shared Library and use them within the stage/steps section and in the condition block of the post section. If you need for any reasons more customization you would have to have a look into the Scripted pipeline syntax.  It allows to use most functionality of Groovy and is therefore very flexible.</p>

Body:
For example something like:

pipeline {
   customDirective {
      sh "env"
      ..
   }
}


问:
undefined reference to `forkpty'
So I'm developing my project in Eclipse in Ubuntu 10.04. I have the following lines of code:

```<code>#include <pty.h>

pid_t pid;
int master;

pid = forkpty(&master, NULL, NULL, NULL);
</code>```

But when I try to build it within Eclipse, I get the error:

```<code>undefined reference to 'forkpty'
</code>```

Any idea how to solve this problem?

答:
That's a linking error; you're missing the util library. Do this to build on the command line:

```<code>g++ myprogram.cpp -lutil
</code>```

Eclipse should have project-level settings for listing the libraries to link against.

Title: undefined reference to `forkpty'

Body:
So I'm developing my project in Eclipse in Ubuntu 10.04. I have the following lines of code:

#include <pty.h>

pid_t pid;
int master;

pid = forkpty(&master, NULL, NULL, NULL);

But when I try to build it within Eclipse, I get the error:

undefined reference to 'forkpty'

Any idea how to solve this problem?

Body:
That's a linking error; you're missing the util library. Do this to build on the command line:

g++ myprogram.cpp -lutil

Eclipse should have project-level settings for listing the libraries to link against.


问:
CMake Ninja Git Self Signed Certificate Authority Password Prompts

Short Version:

I am using CMake and Ninja with an external dependency in a git repo that requires a password prompt. (The source code must be secured).

When building using Makefiles I can use the password prompt and everything continues.

With Ninja it locks up at:

```<code>-- Build files have been written to:
/path/to/project/hello_cpp/build/sqlite3-download
[1/9] Creating directories for 'sqlite3-download'
Enter PEM pass phrase:
</code>```

My Question:

How do I get Ninja to allow me to enter the password?

ninja 1.7.2

cmake 3.8.2

git 2.13.2

Long Version

The following are the steps I have taken and the context of the question.

I have created SQLite3 CMake Library as a learning exercise in how to author a CMake library.

I have also created Hello CPP as a learning exercise for building a C++ project cross platform and configuring a project template.

I managed to get external dependencies working via Craig Scott's DownloadProject CMake Module.

```<code>include(DownloadProject)
download_project(PROJ sqlite3
  GIT_REPOSITORY  "https://github.com/dexata/sqlite3-cmake.git"
  GIT_TAG         master
)
add_subdirectory(${sqlite3_SOURCE_DIR} ${sqlite3_BINARY_DIR})
target_link_libraries(helloworld_lib_target sqlite3)
get_property(sqlite3_inc_dir TARGET sqlite3 PROPERTY INCLUDE_DIRECTORIES)
</code>```

I have also authored the following answer to How can I make git accept a self signed certificate?

So I am pretty intimately aware of the security features of self hosted git. We have the current constraint that our only connection is via https to access our git instance. Even if we allowed ssh access we still have the security policy that the private key have a password and thus Ninja still needs to allow interactive prompts.

Like I said above, it works with Makefiles but I am trying to get it working for Ninja.

Your help is appreciated advance.

答:
You can still use ssh with private keys that have passwords. Use something like ssh-agent and ssh-add to only have to enter your password once for the current shell (i.e. before you initiate the build) and then your build won't ask for any passwords.

If you are locked into using https and need to enter a password, you could try adding the various USES_TERMINAL_... options in your call to download_project(). I think USES_TERMINAL_DOWNLOAD and USES_TERMINAL_UPDATE should be all you'd need. These options are documented in the ExternalProject module and download_project() passes through all options it doesn't recognise to the underlying call to ExternalProject_Add(). The documentation states that this gives Ninja access to the terminal, so maybe you will then get the opportunity to enter the password.

Having to enter your password for every build quickly gets tiresome though and it makes automated CI builds pretty hard. I'd strongly recommend you consider the SSH alternative, which typically integrates well with CI systems and is much more convenient for day to day development.

Body:
Short Version:

I am using CMake and Ninja with an external dependency in a git repo that requires a password prompt. (The source code must be secured).

When building using Makefiles I can use the password prompt and everything continues.

With Ninja it locks up at:

-- Build files have been written to:
/path/to/project/hello_cpp/build/sqlite3-download
[1/9] Creating directories for 'sqlite3-download'
Enter PEM pass phrase:

My Question:

How do I get Ninja to allow me to enter the password?

ninja 1.7.2

cmake 3.8.2

git 2.13.2

Long Version

The following are the steps I have taken and the context of the question.

I have created SQLite3 CMake Library as a learning exercise in how to author a CMake library.

I have also created Hello CPP as a learning exercise for building a C++ project cross platform and configuring a project template.

I managed to get external dependencies working via Craig Scott's DownloadProject CMake Module.

include(DownloadProject)
download_project(PROJ sqlite3
  GIT_REPOSITORY  "https://github.com/dexata/sqlite3-cmake.git"
  GIT_TAG         master
)
add_subdirectory(${sqlite3_SOURCE_DIR} ${sqlite3_BINARY_DIR})
target_link_libraries(helloworld_lib_target sqlite3)
get_property(sqlite3_inc_dir TARGET sqlite3 PROPERTY INCLUDE_DIRECTORIES)

I have also authored the following answer to How can I make git accept a self signed certificate?

So I am pretty intimately aware of the security features of self hosted git. We have the current constraint that our only connection is via https to access our git instance. Even if we allowed ssh access we still have the security policy that the private key have a password and thus Ninja still needs to allow interactive prompts.

Like I said above, it works with Makefiles but I am trying to get it working for Ninja.

Your help is appreciated advance.


问:
JAVA reading XML, direct from element
I have program for reading XML file. Recently my supplier changed some part of the source XML file and I have no idea how to read the changed parts.

XML :

```<code><Product>
<Weight>5,000</Weight>
<Color>blue</Color>
<Stock Warehouse_name="London" Availability="5,00"/>
<Stock Warehouse_name="Berlin" Availability="0,00"/>
<Stock Warehouse_name="Sydney" Availability="42,00"/>
</Product>
</code>```

Maybe you see my problem already. Weight and Color are OK, but the Stock is my problem. Instead to give the information between the elements, the information is direct in the element. I'm using the standard method to retrieve the data:

```<code>color = (eElement.getElementsByTagName("Color").item(0).getTextContent());
</code>```

Any suggestion? I'm pretty new to Java, so please explain it to me as simple, as possible.

答:
The values you want to retrieve are called attributes.
You could use getAttribute on Element to retrieve the values of attributes.

Below code should work for the same :

```<code>NodeList stockList = eElement.getElementsByTagName("Stock");
for ( int i = 0; i < stockList.getLength(); i++ )
{
   Node stockNode = stockList.item(i);
   if ( stockNode.getNodeType() == Node.ELEMENT_NODE )
   {
       Element stockElement = (Element)stockNode;
       System.out.println( "Warehouse name : " + stockElement.getAttribute( "Warehouse_name" ) );
       System.out.println( "Availability : " + stockElement.getAttribute( "Availability" ) );
    }
}
</code>```

Title: JAVA reading XML, direct from element

Body:
I have program for reading XML file. Recently my supplier changed some part of the source XML file and I have no idea how to read the changed parts.

XML :

<Product>
<Weight>5,000</Weight>
<Color>blue</Color>
<Stock Warehouse_name="London" Availability="5,00"/>
<Stock Warehouse_name="Berlin" Availability="0,00"/>
<Stock Warehouse_name="Sydney" Availability="42,00"/>
</Product>

Maybe you see my problem already. Weight and Color are OK, but the Stock is my problem. Instead to give the information between the elements, the information is direct in the element. I'm using the standard method to retrieve the data:

color = (eElement.getElementsByTagName("Color").item(0).getTextContent());

Any suggestion? I'm pretty new to Java, so please explain it to me as simple, as possible.

Body:
The values you want to retrieve are called attributes.
You could use getAttribute on Element to retrieve the values of attributes.

Below code should work for the same :

NodeList stockList = eElement.getElementsByTagName("Stock");
for ( int i = 0; i < stockList.getLength(); i++ )
{
   Node stockNode = stockList.item(i);
   if ( stockNode.getNodeType() == Node.ELEMENT_NODE )
   {
       Element stockElement = (Element)stockNode;
       System.out.println( "Warehouse name : " + stockElement.getAttribute( "Warehouse_name" ) );
       System.out.println( "Availability : " + stockElement.getAttribute( "Availability" ) );
    }
}


问:
.php not sending POST to server (GET being sent instead)
Issue I'm having is it appears that GET is being sent with file_get_contents in my execute function below.  For the life of me I cannot figure out why.  I have tested the api server with Postman using POST and it works correctly.

The first function is used to pass in my requests to get sent to the server.  The second function is in my form_handler.php file where it builds the data to send via execute() to the server.

api_handler.php

```<code><?php
function execute($command, $context = NULL)
{
    $url_scheme = "http://";
    if (isset($_SERVER['HTTPS']))
    {
        $url_scheme = "https://";
    }
    $url_host = $_SERVER['HTTP_HOST'];
    $url_api = "/SkedApi/";
    $url = $url_scheme.$url_host.$url_api.$command;

echo $url . "<br/>";
var_dump($context);
var_dump(headers_list());
    $response = file_get_contents($url, false, $context);
var_dump(headers_list());
echo $response;
    if ($response)
    {
        $output = json_decode($response, true);
    }
    else
    {
        $output = "error";
    }
    return $output;
}

?>
</code>```

users_handler.php

```<code>$test = array ('foo' => 'bar', 'bar' => 'baz');
$postdata = http_build_query($test);

echo $postdata;

$opts = array (
    'http' => array (
        'method' => 'POST',
        'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
            . "Content-Length: " . strlen($postdata) . "\r\n",
        'content' => $postdata
        ));

var_dump($opts);

$context = stream_context_create($opts);

print_r($context);
$result = execute("Users", $context);

if ($result)
{
    echo "YES</br>";
}
</code>```

From my apache access files:

```<code>::1 - - [04/Jul/2017:16:02:00 -0400] "POST /SkedApi/Users HTTP/1.0" 301 239
::1 - - [04/Jul/2017:16:02:00 -0400] "GET /SkedApi/Users/ HTTP/1.0" 200 196
::1 - - [04/Jul/2017:16:02:00 -0400] "POST /SkedAvailability/users_handler.php HTTP/1.1" 200 2688
</code>```

Disclaimer: sorry about all the var_dumps;

答:
Well your log is showing a 301 response to a POST request followed by a 200 response to the same URL with a trailing slash appended.

What happens if you change this line of your users_handler.php

```<code>$result = execute("Users", $context);
</code>```

To this?

```<code>$result = execute("Users/", $context);
</code>```

Body:
Issue I'm having is it appears that GET is being sent with file_get_contents in my execute function below.  For the life of me I cannot figure out why.  I have tested the api server with Postman using POST and it works correctly.

The first function is used to pass in my requests to get sent to the server.  The second function is in my form_handler.php file where it builds the data to send via execute() to the server.

api_handler.php

<?php
function execute($command, $context = NULL)
{
    $url_scheme = "http://";
    if (isset($_SERVER['HTTPS']))
    {
        $url_scheme = "https://";
    }
    $url_host = $_SERVER['HTTP_HOST'];
    $url_api = "/SkedApi/";
    $url = $url_scheme.$url_host.$url_api.$command;

echo $url . "
";
var_dump($context);
var_dump(headers_list());
    $response = file_get_contents($url, false, $context);
var_dump(headers_list());
echo $response;
    if ($response)
    {
        $output = json_decode($response, true);
    }
    else
    {
        $output = "error";
    }
    return $output;
}

?>

users_handler.php

$test = array ('foo' => 'bar', 'bar' => 'baz');
$postdata = http_build_query($test);

echo $postdata;

$opts = array (
    'http' => array (
        'method' => 'POST',
        'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
            . "Content-Length: " . strlen($postdata) . "\r\n",
        'content' => $postdata
        ));

var_dump($opts);

$context = stream_context_create($opts);

print_r($context);
$result = execute("Users", $context);

if ($result)
{
    echo "YES
";
}

From my apache access files:

::1 - - [04/Jul/2017:16:02:00 -0400] "POST /SkedApi/Users HTTP/1.0" 301 239
::1 - - [04/Jul/2017:16:02:00 -0400] "GET /SkedApi/Users/ HTTP/1.0" 200 196
::1 - - [04/Jul/2017:16:02:00 -0400] "POST /SkedAvailability/users_handler.php HTTP/1.1" 200 2688

Disclaimer: sorry about all the var_dumps;

Body:
Well your log is showing a 301 response to a POST request followed by a 200 response to the same URL with a trailing slash appended.

What happens if you change this line of your users_handler.php

$result = execute("Users", $context);

To this?

$result = execute("Users/", $context);


问:
What is the meaning and reasoning behind the Open/Closed Principle?
The Open/Closed Principle states that software entities (classes, modules, etc.) should be open for extension, but closed for modification. What does this mean, and why is it an important principle of good object-oriented design?</p>

答:
Software entities should be open for extension but closed for modification

That means any class or module should be written in a way that it can be used as is, can be extended, but neve modified

Bad Example in Javascript

```<code>var juiceTypes = ['Mango','Apple','Lemon'];
function juiceMaker(type){
    if(juiceTypes.indexOf(type)!=-1)
        console.log('Here is your juice, Have a nice day');
    else
        console.log('sorry, Error happned');
}

exports.makeJuice = juiceMaker;
</code>```

Now if you want to add Another Juice type, you have to edit the module itself, By this way, we are breaking OCP .

Good Example in Javascript

```<code>var juiceTypes = [];
function juiceMaker(type){
    if(juiceTypes.indexOf(type)!=-1)
        console.log('Here is your juice, Have a nice day');
    else
        console.log('sorry, Error happned');
}
function addType(typeName){
    if(juiceTypes.indexOf(typeName)==-1)
        juiceTypes.push(typeName);
}
function removeType(typeName){
  let index = juiceTypes.indexOf(typeName)
    if(index!==-1)
        juiceTypes.splice(index,1);
}

exports.makeJuice = juiceMaker;
exports.addType = addType;
exports.removeType = removeType;
</code>```

Now, you can add new juice types from outside the module without editing the same module.

OwnerDisplayName: Phillip Wells

LastEditorDisplayName: quamrana

Body:
Software entities should be open for extension but closed for modification

That means any class or module should be written in a way that it can be used as is, can be extended, but neve modified

Bad Example in Javascript

var juiceTypes = ['Mango','Apple','Lemon'];
function juiceMaker(type){
    if(juiceTypes.indexOf(type)!=-1)
        console.log('Here is your juice, Have a nice day');
    else
        console.log('sorry, Error happned');
}

exports.makeJuice = juiceMaker;

Now if you want to add Another Juice type, you have to edit the module itself, By this way, we are breaking OCP .

Good Example in Javascript

var juiceTypes = [];
function juiceMaker(type){
    if(juiceTypes.indexOf(type)!=-1)
        console.log('Here is your juice, Have a nice day');
    else
        console.log('sorry, Error happned');
}
function addType(typeName){
    if(juiceTypes.indexOf(typeName)==-1)
        juiceTypes.push(typeName);
}
function removeType(typeName){
  let index = juiceTypes.indexOf(typeName)
    if(index!==-1)
        juiceTypes.splice(index,1);
}

exports.makeJuice = juiceMaker;
exports.addType = addType;
exports.removeType = removeType;

Now, you can add new juice types from outside the module without editing the same module.

ContentLicense: CC BY-SA 4.0


问:
three.js canvas, sphere turn or float right
i try out to get the sphere to turn right in a very slow tempo. here is my source code : i have created a new contaier with canvas inside, you can see the code. what i have to include that the sphere turn in a slow tempo? here I'm also i have my git repository on github: see the image inside https://github.com/SpaceG/SpaceSphere. here i have also, found another example, with a sphere: this roundball truns a float very slow in the same point, this is excat waht i need: http://rectangleworld.com/demos/DustySphere/DustySphere.html This turn left i need in my code below]. You can also download my repo or fork it and get fixxed my issue here.

Here is the Html Doc :

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

<style>

        body {
            background-color: #000000;
            margin: 0px;
            overflow: hidden;
        }

        a {
            color:#0078ff;
        }
    </style>

    <script src="../build/three.js"></script>
    <script src="js/renderers/Projector.js"></script>
    <script src="js/renderers/CanvasRenderer.js"></script>

</head>
<body>
</code>```

The Javascript Code to make the Sphere possible:

```<code>        <script>

        var SCREEN_WIDTH = window.innerWidth,
        SCREEN_HEIGHT = window.innerHeight,

        mouseX = 0, mouseY = 0,

        windowHalfX = window.innerWidth / 4,
        windowHalfY = window.innerHeight / 4,

        SEPARATION = 600,
        AMOUNTX = 10,
        AMOUNTY = 10,

        camera, scene, renderer;

        init();
        animate();

        function init() {

            var container, turnAngle, separation = 100, amountX = 50, amountY = 50,
            particles, particle;

            container = document.createElement('div');
            container.setAttribute('class', 'space-id');
            document.body.appendChild(container);

            camera = new THREE.PerspectiveCamera( 275, SCREEN_WIDTH / SCREEN_HEIGHT, 5, 10000000 );
            camera.position.z = 100;

            scene = new THREE.Scene();

            renderer = new THREE.CanvasRenderer();
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
            container.appendChild( renderer.domElement );

            // particles

            var PI2 = Math.PI * 2;
            var material = new THREE.SpriteCanvasMaterial( {

                color: 0xffffff,
                program: function ( context ) {

                    context.beginPath();
                    context.arc( 0, 0, 0.5, 0, PI2, true );
                    context.fill();

                }

            } );

            for ( var i = 0; i < 1000; i ++ ) {

                particle = new THREE.Sprite( material );
                particle.position.x = Math.random() * 2 - 1;
                particle.position.y = Math.random() * 2 - 1;
                particle.position.z = Math.random() * 2 - 1;
                particle.position.normalize();
                particle.position.multiplyScalar( Math.random() * 10 + 450 );
                particle.scale.multiplyScalar( 2 );
                scene.add( particle );

            }

            // lines

            for (var i = 0; i < 300; i++) {

                var geometry = new THREE.Geometry();

                var vertex = new THREE.Vector3( Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1 );
                vertex.normalize();
                vertex.multiplyScalar( 450 );

                geometry.vertices.push( vertex );

                var vertex2 = vertex.clone();
                vertex2.multiplyScalar( Math.random() * 0.3 + 1 );

                geometry.vertices.push( vertex2 );

                var line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0xffffff, opacity: Math.random() } ) );
                scene.add( line );
            }

            document.addEventListener( 'mousemove', onDocumentMouseMove, false );
            document.addEventListener( 'touchstart', onDocumentTouchStart, false );
            document.addEventListener( 'touchmove', onDocumentTouchMove, false );

            //

            window.addEventListener( 'resize', onWindowResize, false );

        }

        function onWindowResize() {

            windowHalfX = window.innerWidth / 4;
            windowHalfY = window.innerHeight / 4;

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );

        }

        //

        function onDocumentMouseMove(event) {

            mouseX = event.clientX - windowHalfX;
            mouseY = event.clientY - windowHalfY;
        }

        function onDocumentTouchStart( event ) {

            if ( event.touches.length > 1 ) {

                event.preventDefault();

                mouseX = event.touches[ 0 ].pageX - windowHalfX;
                mouseY = event.touches[ 0 ].pageY - windowHalfY;

            }

        }

        function onDocumentTouchMove( event ) {

            if ( event.touches.length == 1 ) {

                event.preventDefault();

                mouseX = event.touches[ 0 ].pageX - windowHalfX;
                mouseY = event.touches[ 0 ].pageY - windowHalfY;

            }

        }

        //

        function animate() {

            requestAnimationFrame( animate );

            render();

        }

        function render() {

            camera.position.x += ( mouseX - camera.position.x ) * .05;
            camera.position.y += ( - mouseY + 200 - camera.position.y ) * .05;
            camera.lookAt( scene.position );

            renderer.render( scene, camera );

        }

        </script>

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

Here is an Image about the Goal of the Project, that the round ball turn to left in slow tempo, are some one here give me tips? lets up the Good Work. Thanks lot.

答:
If you just want the ball to spin like it does in the example, you can do the following:

```<code>// Declare these before the call to init();
var group = new THREE.Group();
var rotationSpeed = 0.001; // Increase/decrease to control speed of rotation.
</code>```

And, instead of scene.add(particle);

you do group.add(particle);

then scene.add(group);

The same goes for the lines:

instead of scene.add(line);

do group.add(line); (here you don't need to add to the scene since you're adding to the group that is already in the scene.)

Then the key line that was missing in the render loop:

```<code>group.rotateY(rotationSpeed); // Rotates the ball with speed 'rotationSpeed'
</code>```

Here is a fiddle of what it looks like with these changes:
JSFiddle

Body:
i try out to get the sphere to turn right in a very slow tempo. here is my source code : i have created a new contaier with canvas inside, you can see the code. what i have to include that the sphere turn in a slow tempo? here I'm also i have my git repository on github: see the image inside https://github.com/SpaceG/SpaceSphere. here i have also, found another example, with a sphere: this roundball truns a float very slow in the same point, this is excat waht i need: http://rectangleworld.com/demos/DustySphere/DustySphere.html This turn left i need in my code below]. You can also download my repo or fork it and get fixxed my issue here.

Here is the Html Doc :

<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

The Javascript Code to make the Sphere possible:

Here is an Image about the Goal of the Project, that the round ball turn to left in slow tempo, are some one here give me tips? lets up the Good Work. Thanks lot.

Body:
If you just want the ball to spin like it does in the example, you can do the following:

// Declare these before the call to init();
var group = new THREE.Group();
var rotationSpeed = 0.001; // Increase/decrease to control speed of rotation.

And, instead of scene.add(particle);

you do group.add(particle);

then scene.add(group);

The same goes for the lines:

instead of scene.add(line);

do group.add(line); (here you don't need to add to the scene since you're adding to the group that is already in the scene.)

Then the key line that was missing in the render loop:

group.rotateY(rotationSpeed); // Rotates the ball with speed 'rotationSpeed'

Here is a fiddle of what it looks like with these changes:
JSFiddle


问:
Reducing video size with same format and reducing frame size
This question might be very basic

Is there a way to reduce the frame size/rate of Lossy compressed (WMV, MPEG) format, to get a smaller video, of lesser size, with same format.

Are there any open source or proprietary apis for this?

答:
ffmpeg provides this functionality.  All you need to do is run someting like

```<code>ffmpeg -i <inputfilename> -s 640x480 -b 512k -vcodec mpeg1video -acodec copy <outputfilename>
</code>```

For newer versions of ffmpeg you need to change -b to -b:v:

```<code>ffmpeg -i <inputfilename> -s 640x480 -b:v 512k -vcodec mpeg1video -acodec copy <outputfilename>
</code>```

to convert the input video file to a video with a size of 640 x 480 and a bitrate of 512 kilobits/sec using the MPEG 1 video codec and just copying the original audio stream.  Of course, you can plug in any values you need and play around with the size and bitrate to achieve the quality/size tradeoff you are looking for.  There are also a ton of other options described in the documentation

Run ffmpeg -formats or ffmpeg -codecs for a list of all of the available formats and codecs.  If you don't have to target a specific codec for the final output, you can achieve better compression ratios with minimal quality loss using a state of the art codec like H.264.

Body:
ffmpeg provides this functionality.  All you need to do is run someting like

ffmpeg -i <inputfilename> -s 640x480 -b 512k -vcodec mpeg1video -acodec copy <outputfilename>

For newer versions of ffmpeg you need to change -b to -b:v:

ffmpeg -i <inputfilename> -s 640x480 -b:v 512k -vcodec mpeg1video -acodec copy <outputfilename>

to convert the input video file to a video with a size of 640 x 480 and a bitrate of 512 kilobits/sec using the MPEG 1 video codec and just copying the original audio stream.  Of course, you can plug in any values you need and play around with the size and bitrate to achieve the quality/size tradeoff you are looking for.  There are also a ton of other options described in the documentation

Run ffmpeg -formats or ffmpeg -codecs for a list of all of the available formats and codecs.  If you don't have to target a specific codec for the final output, you can achieve better compression ratios with minimal quality loss using a state of the art codec like H.264.


问:
How do I import members of one GitLab group into another
Does somebody know how I can import all members of one group into another in GitLab, rather than doing it manually one by one?</p>

答:
I was looking for a solution to Assign all Gitlab users to one particular group.

Here's the solution:

Create this file:

/opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/finder_import.rake

With this content:

```<code>namespace :gitlab do   namespace :finder do

desc "GitLab | Add all users to group Colaboradores (admin users are added as owners)"
task importall: :environment  do |t, args|
  user_ids = User.where(admin: false).pluck(:id)
  admin_ids = User.where(admin: true).pluck(:id)
  groups = Group.where(name: "Colaboradores")

  puts "Importing #{user_ids.size} users into #{groups.size} groups"
  puts "Importing #{admin_ids.size} admins into #{groups.size} groups"
  groups.each do |group|
    puts "Importing into #{group.name}"
    group.add_users(user_ids, GroupMember::DEVELOPER)
    group.add_users(admin_ids, GroupMember::OWNER)
  end
end
</code>```

end end

Run this command:

gitlab-rake gitlab:finder:importall

Body:
I was looking for a solution to Assign all Gitlab users to one particular group.

Here's the solution:

Create this file:

/opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/finder_import.rake

With this content:

namespace :gitlab do   namespace :finder do

desc "GitLab | Add all users to group Colaboradores (admin users are added as owners)"
task importall: :environment  do |t, args|
  user_ids = User.where(admin: false).pluck(:id)
  admin_ids = User.where(admin: true).pluck(:id)
  groups = Group.where(name: "Colaboradores")

  puts "Importing #{user_ids.size} users into #{groups.size} groups"
  puts "Importing #{admin_ids.size} admins into #{groups.size} groups"
  groups.each do |group|
    puts "Importing into #{group.name}"
    group.add_users(user_ids, GroupMember::DEVELOPER)
    group.add_users(admin_ids, GroupMember::OWNER)
  end
end

end end

Run this command:

gitlab-rake gitlab:finder:importall


问:
Implementation of the majority merge algorithm for finding a super-sequence from sub-sequences?
I've got a small set of sequences of unique values that I want to combine into a single super-sequence where the relative order of each value is maintained, to the extent possible.  For instance (quotes around strings ignored for simplicity):

```<code>list1 = [Mary, Bob, Sue, Roger]
list2 = [Bob, Alice, Sue, Dave]
list3 = [Mary, Bob, Larry, Sue, Roger]

superSequence = [Mary, Bob, Alice, Larry, Sue, Roger, Dave]
</code>```

The goal is to generate an object from which the original lists can be recreated, such as:

```<code>obj = {
    Mary: [1, 3],
    Bob: [1, 3],
    Alice: [2],
    Larry: [3],
    Sue: [1, 2, 3],
    Roger: [1, 3],
    Dave: [2]
}
</code>```

Ignoring for the moment that object key order isn't guaranteed in all cases, one could iterate over these keys and use the indices in each associated array to regenerate the original lists.  Because the super-sequence is represented as a JS object, the values in it must be unique.

Clearly, not every set of sequences can be combined in this way:

```<code>list1 = [Mary, Bob, Sue]
list2 = [Bob, Mary, Sue]

superSequence = [Mary, Bob, Sue] OR
superSequence = [Bob, Mary, Sue]
</code>```

Picking one or the other should be fine in most cases, with bonus points for an algorithm that can highlight where the order was indeterminate.

In researching this, I seem to have stumbled upon an NP-hard problem that's well-studied in compression, bioinformatics, and other fields.  There's something called a majority merge algorithm that seems to be a reasonably decent approximation for this problem, but my ability to translate academic paper pseudo-code into something usable has atrophied over the years.  So I was hoping to find an actual implementation in JS, or C, or Python or something that doesn't rely on magic libraries.

答:
Building on the simpleCombine() function from aduss I came up with a solution that seems to work pretty well.  It doesn't currently flag that duplicate items in the result are getting deleted, but that could be implemented with some additional logic in the final filter() call.

function combineLists(...lists)
{
    var superSequence = lists.slice(1).reduce((list1, list2) => {
        var result = [];

            // we need to make a copy of list2 since we mutate it in the loop below
        list2 = [].concat(list2);

        list1.forEach(item => {
            var overlapIndex = list2.indexOf(item);

            if (overlapIndex > -1) {
                    // add 1 to overlapIndex so we also splice out the matching item
                result = result.concat(list2.splice(0, overlapIndex + 1));
            } else {
                result.push(item);
            }
        });

            // anything remaining in list2 is by definition not in list1, so add
            // those items to the result
        return result.concat(list2);
    }, lists[0]);

        // look back at the list up to the current item and then filter it out if
        // there's a duplicate found.  this keeps the first instance of each item.
    return superSequence.filter((item, i, list) => list.slice(0, i).indexOf(item) == -1);
}

var list1 = ["Mary", "Bob", "Sue", "Roger"],
    list2 = ["Bob", "Alice", "Jimmy", "Chuck", "Sue", "Dave"],
    list3 = ["Mary", "Bob", "Larry", "Sue", "Roger"];

console.log(combineLists(list1, list2, list3).join(" "));```

Body:
I've got a small set of sequences of unique values that I want to combine into a single super-sequence where the relative order of each value is maintained, to the extent possible.  For instance (quotes around strings ignored for simplicity):

list1 = [Mary, Bob, Sue, Roger]
list2 = [Bob, Alice, Sue, Dave]
list3 = [Mary, Bob, Larry, Sue, Roger]

superSequence = [Mary, Bob, Alice, Larry, Sue, Roger, Dave]

The goal is to generate an object from which the original lists can be recreated, such as:

obj = {
    Mary: [1, 3],
    Bob: [1, 3],
    Alice: [2],
    Larry: [3],
    Sue: [1, 2, 3],
    Roger: [1, 3],
    Dave: [2]
}

Ignoring for the moment that object key order isn't guaranteed in all cases, one could iterate over these keys and use the indices in each associated array to regenerate the original lists.  Because the super-sequence is represented as a JS object, the values in it must be unique.

Clearly, not every set of sequences can be combined in this way:

list1 = [Mary, Bob, Sue]
list2 = [Bob, Mary, Sue]

superSequence = [Mary, Bob, Sue] OR
superSequence = [Bob, Mary, Sue]

Picking one or the other should be fine in most cases, with bonus points for an algorithm that can highlight where the order was indeterminate.

In researching this, I seem to have stumbled upon an NP-hard problem that's well-studied in compression, bioinformatics, and other fields.  There's something called a majority merge algorithm that seems to be a reasonably decent approximation for this problem, but my ability to translate academic paper pseudo-code into something usable has atrophied over the years.  So I was hoping to find an actual implementation in JS, or C, or Python or something that doesn't rely on magic libraries.


问:
Why this form doesn't work? Javascript: number values in options from select input
I have this form that should show an error message if the value of Start time is higher than the one from End time, but if I select start at 8:00am and end at 4:00am it doesn't show an the error message, unless i put left zeros to numbers 1 to 9 (01, 02, 03, 04, 05, 06, 07, 08, 09), is like 1-9 without zeros were recognized as higher numbers than 10 - 48, why is that?

This work:

```<code><script>
function execute_onclick()
{
    var result;

    if (document.forms[0].endtime.value >  document.forms[0].starttime.value)
    {
        result = "CORRECT";
    }
    else
    {
        result = "ERROR";
    }

    alert(result);

    return false;
}
</script>
<option value=01 >12:00 am</option>
<option value=02 >12:30 am</option>
<option value=03 >1:00 am</option>
<option value=04 >1:30 am</option>
<option value=05 >2:00 am</option>
<option value=06 >2:30 am</option>
<option value=07 >3:00 am</option>
<option value=08 >3:30 am</option>
<option value=09 >4:00 am</option>
<option value=10 >4:30 am</option>
</code>```

This doesnt work:

```<code><script>
function execute_onclick()
{
    var result;

    if (document.forms[0].endtime.value >  document.forms[0].starttime.value)
    {
        result = "CORRECT";
    }
    else
    {
        result = "ERROR";
    }

    alert(result);

    return false;
}
</script>
<option value=1 >12:00 am</option>
<option value=2 >12:30 am</option>
<option value=3 >1:00 am</option>
<option value=4 >1:30 am</option>
<option value=5 >2:00 am</option>
<option value=6 >2:30 am</option>
<option value=7 >3:00 am</option>
<option value=8 >3:30 am</option>
<option value=9 >4:00 am</option>
<option value=10 >4:30 am</option>
</code>```

答:
Try parsing on the fly with + operator.

```<code>if (+document.forms[0].endtime.value > +document.forms[0].starttime.value)
</code>```

Body:
I have this form that should show an error message if the value of Start time is higher than the one from End time, but if I select start at 8:00am and end at 4:00am it doesn't show an the error message, unless i put left zeros to numbers 1 to 9 (01, 02, 03, 04, 05, 06, 07, 08, 09), is like 1-9 without zeros were recognized as higher numbers than 10 - 48, why is that?

This work:

<option value=01 >12:00 am</option>
<option value=02 >12:30 am</option>
<option value=03 >1:00 am</option>
<option value=04 >1:30 am</option>
<option value=05 >2:00 am</option>
<option value=06 >2:30 am</option>
<option value=07 >3:00 am</option>
<option value=08 >3:30 am</option>
<option value=09 >4:00 am</option>
<option value=10 >4:30 am</option>

This doesnt work:

<option value=1 >12:00 am</option>
<option value=2 >12:30 am</option>
<option value=3 >1:00 am</option>
<option value=4 >1:30 am</option>
<option value=5 >2:00 am</option>
<option value=6 >2:30 am</option>
<option value=7 >3:00 am</option>
<option value=8 >3:30 am</option>
<option value=9 >4:00 am</option>
<option value=10 >4:30 am</option>

Body:
Try parsing on the fly with + operator.

if (+document.forms[0].endtime.value > +document.forms[0].starttime.value)


问:
Is there any way to tell NHibernate to exclude a specific table from a Schema Export?
I am using NHibernate's SchemaExport to create my database schema. I have 1 legacy ref table that cannot be recreated with the Schema Export because it is already in use with other apps that use the same DB. Is there any way to map this table but tell NHibernate to skip it when running the SchemaExport?</p>

答: Try using SchemaUpdate() instead? it should see the table already exists and not issue a CREATE statement</p>

OwnerDisplayName: Mark Struzinski

OwnerDisplayName: defeated


问:
Content Slider stop and start in accordion
I have code below for a Pure CSS content slider in an accordion I have created. Is it possible to start and stop the Content Slider when the accordion is opened and closed? Currently the Content Slider keeps running even if the accordion is closed. Is this possible with Pure CSS? If not would this be possible with Vanilla JavaScript (no JQuery). Anything helps, cheers.

.wrapper {
  max-width: 960px;
  margin: 0 auto;
}

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  overflow: hidden;
}

.bold {
  font-weight:bold;
  color: #005bab;
  }

.top {
  margin-top:-20px;
  text-align: center;
  font-size:13px;
}

.input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

.label {
  position: relative;
  text-align: center;
  display: block;
  padding: 0 0 0 1em;
  color: #005bab;
  background: #e2ecf6;
  font-size: 14px;
  font-family: Verdana;
  font-weight: bold;
  line-height: 6;
  cursor: pointer;
}

.label:hover {
  background-color: #d2e2ef;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  padding: 0px;
  -webkit-transition: max-height .5s;
  -o-transition: max-height .5s;
  transition: max-height .5s;
  padding-left: 35px;
  background: #dce7f2;
}

.tab-content .container {
  padding: 1em;
  margin: 0;
  opacity: 0;
  transform: scale(0.75);
  -webkit-transition: transform 0.75s, opacity .75s;
  -o-transition: transform 0.75s, opacity .75s;
  transition: transform 0.75s, opacity .75s;
  background: #f4f8fc;
}

/* :checked */

.input:checked~.tab-content {
  max-height: 35em;
}

.input:checked~.tab-content .container {
  transform: scale(1);
  opacity: 1;
}

/* Icon */

.label::after {
  position: absolute;
  left: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

.input[type=checkbox]+.label::after {
  content: "+";
}

.input[type=radio]+.label::after {
  content: "";
}

.input[type=checkbox]:checked+.label::after {
  transform: rotate(315deg);
}

.input[type=radio]:checked+.label::after {
  transform: rotateX(180deg);
}

.bottombar {
  content: "";
  display: block;
  height: 1em;
  width: 100%;
  background-color: #00688B;
}

/* all position:absolute removed */
#scroller {
overflow:hidden;
}

#scroller .innerScrollArea {

}

#scroller ul {
  padding: 0;
  position: relative;
  display:flex;/* UPDATE */
}

#scroller li {
  padding: 0;
  list-style-type: none;
}
.circle {
  width: 130px;
  height: 130px;
  position: relative;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  border-radius: 50%;
  background-color:transparent;
  border-style:solid;
  border-width:5px;
  border-color:#006850;
}

.circle-text {
  color: #1f497d;
  font-family:Verdana;
  font-size: 12px;
  text-align: center;
  width: 200px;
  top: 45px;
  margin-left:-35px;
  bottom: 0;
  position: absolute;
  z-index: 99;
}

.circleinv{
  width: 130px;
  height: 130px;
  position: relative;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  border-radius: 50%;
  background-color:transparent;
  border-style:solid;
  border-width:5px;
  border-color:transparent;
}

.arrow {
  width:145px;
  height:45px;
}

.arrowinv {
  visibility:hidden;
  width:145px;
  height:50px;
}

.flipimage {
  width:145px;
  height:45px;
  -moz-transform: scaleY(-1);
    -webkit-transform: scaleY(-1);
    -o-transform: scaleY(-1);
    transform: scaleY(-1);
    -ms-filter: fliph; /*IE*/
    filter: fliph; /*IE*/
}

/* UPDATE  for animation */
.ul {
  animation: slidli 90s infinite linear;
}
.ul:hover {
  animation-play-state:paused;
}
@keyframes slidli {
  100% {
    transform:translatex(-733.5%);/* this is to be update to the content with to see every element slide once untill copies/clone comes back at same spot */
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top">
   <p>
      <span style="font-family: verdana;"><strong>Click the "</strong><span class="ms-rteThemeForeColor-5-0"><strong>+</strong></span><strong>" to expand and the "</strong><span class="ms-rteThemeForeColor-5-0"><strong>x</strong></span><strong>" to collapse</strong></span></p>
</div>
<div class="wrapper">

  <div class="tab">
    <input name="tabs" class="input" id="tab-one" type="checkbox"/>
         <label class="label" for="tab-one">Content Slider</label>
         <div class="tab-content">
            <div class="container">

                      <div class="everything">
  <div id="scroller" style="width: 400px; height: 255px; margin: 0 auto;">
    <div class="innerScrollArea">
      <ul class="ul">
        <li>
          <br style="line-height:49px;"/>
          <div class="circle">
            <div class="circle-text">
              HR Connect<br/>Service<br/>Representative
            </div>
          </div>
          <img class="flipimage" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
        </li>
        <li>
          <img class="arrow" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
          <div class="circle">
            <div class="circle-text">
              Employee<br/>Relations<br/>Specialist
            </div>
          </div>
        </li>
        <li>
          <br style="line-height:49px;"/>
          <div class="circle">
            <div class="circle-text">
              Employee<br/>Relations<br/>Manager
            </div>
          </div>
          <img class="flipimage" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
        </li>
        <li>
<img class="arrowinv" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
          <div class="circle">
            <div class="circle-text">
              Director, Employee<br/>Relations &<br/>Well-Being
            </div>
          </div>
        </li>
                <li>
          <div class="circleinv">
          </div>
        </li>
        <li>
          <div class="circleinv">
          </div>
        </li>

        <!--Dupes-->

                <li>
          <br style="line-height:49px;"/>
          <div class="circle">
            <div class="circle-text">
              HR Connect<br/>Service<br/>Representative
            </div>
          </div>
          <img class="flipimage" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
        </li>
        <li>
          <img class="arrow" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
          <div class="circle">
            <div class="circle-text">
              Employee<br/>Relations<br/>Specialist
            </div>
          </div>
        </li>
        <li>
          <br style="line-height:49px;"/>
          <div class="circle">
            <div class="circle-text">
              Employee<br/>Relations<br/>Manager
            </div>
          </div>
          <img class="flipimage" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
        </li>
        <li>
<img class="arrowinv" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
          <div class="circle">
            <div class="circle-text">
              Director, Employee<br/>Relations &<br/>Well-Being
            </div>
          </div>
        </li>
                <li>
          <div class="circleinv">
          </div>
        </li>
        <li>
          <div class="circleinv">
          </div>
        </li>

        <!--Dupe 2-->

                <li>
          <br style="line-height:49px;"/>
          <div class="circle">
            <div class="circle-text">
              HR Connect<br/>Service<br/>Representative
            </div>
          </div>
          <img class="flipimage" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
        </li>
        <li>
          <img class="arrow" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
          <div class="circle">
            <div class="circle-text">
              Employee<br/>Relations<br/>Specialist
            </div>
          </div>
        </li>
        <li>
          <br style="line-height:49px;"/>
          <div class="circle">
            <div class="circle-text">
              Employee<br/>Relations<br/>Manager
            </div>
          </div>
          <img class="flipimage" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
        </li>
        <li>
<img class="arrowinv" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
          <div class="circle">
            <div class="circle-text">
              Director, Employee<br/>Relations &<br/>Well-Being
            </div>
          </div>
        </li>
                <li>
          <div class="circleinv">
          </div>
        </li>
        <li>
          <div class="circleinv">
          </div>
        </li>

        <!--Dupe 3-->

                <li>
          <br style="line-height:49px;"/>
          <div class="circle">
            <div class="circle-text">
              HR Connect<br/>Service<br/>Representative
            </div>
          </div>
          <img class="flipimage" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
        </li>
        <li>
          <img class="arrow" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
          <div class="circle">
            <div class="circle-text">
              Employee<br/>Relations<br/>Specialist
            </div>
          </div>
        </li>
        <li>
          <br style="line-height:49px;"/>
          <div class="circle">
            <div class="circle-text">
              Employee<br/>Relations<br/>Manager
            </div>
          </div>
          <img class="flipimage" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
        </li>
        <li>
<img class="arrowinv" src="http://res.cloudinary.com/djxai1v1e/image/upload/v1499184462/testarrow_yhblyv.png">
          <div class="circle">
            <div class="circle-text">
              Director, Employee<br/>Relations &<br/>Well-Being
            </div>
          </div>
        </li>
                <li>
          <div class="circleinv">
          </div>
        </li>
        <li>
          <div class="circleinv">
          </div>
        </li>

      </ul>
    </div>
  </div>
</div>

            </div>
         </div>
  </div>

  <div class="bottombar"></div>

</div></code>```

答:
I would normally advise that you do this kind of stuff with JS but if you want to avoid it here's a working (albeit verbose) solution:

replace

```<code>.ul:hover {
  animation-play-state:paused;
}
</code>```

with

```<code>.input:checked~.tab-content .container .ul:hover {
  animation-play-state:paused;
}

.tab-content .container .ul{
  animation-play-state:paused;
}
.input:checked~.tab-content .container .ul {
  animation-play-state:running;
}
</code>```

Here's a pen showing the solution.
https://codepen.io/anon/pen/zzaKow

Body:
I have code below for a Pure CSS content slider in an accordion I have created. Is it possible to start and stop the Content Slider when the accordion is opened and closed? Currently the Content Slider keeps running even if the accordion is closed. Is this possible with Pure CSS? If not would this be possible with Vanilla JavaScript (no JQuery). Anything helps, cheers.

.wrapper {
  max-width: 960px;
  margin: 0 auto;
}

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  overflow: hidden;
}

.bold {
  font-weight:bold;
  color: #005bab;
  }

.top {
  margin-top:-20px;
  text-align: center;
  font-size:13px;
}

.input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

.label {
  position: relative;
  text-align: center;
  display: block;
  padding: 0 0 0 1em;
  color: #005bab;
  background: #e2ecf6;
  font-size: 14px;
  font-family: Verdana;
  font-weight: bold;
  line-height: 6;
  cursor: pointer;
}

.label:hover {
  background-color: #d2e2ef;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  padding: 0px;
  -webkit-transition: max-height .5s;
  -o-transition: max-height .5s;
  transition: max-height .5s;
  padding-left: 35px;
  background: #dce7f2;
}

.tab-content .container {
  padding: 1em;
  margin: 0;
  opacity: 0;
  transform: scale(0.75);
  -webkit-transition: transform 0.75s, opacity .75s;
  -o-transition: transform 0.75s, opacity .75s;
  transition: transform 0.75s, opacity .75s;
  background: #f4f8fc;
}

/* :checked */

.input:checked~.tab-content {
  max-height: 35em;
}

.input:checked~.tab-content .container {
  transform: scale(1);
  opacity: 1;
}

/* Icon */

.label::after {
  position: absolute;
  left: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

.input[type=checkbox]+.label::after {
  content: "+";
}

.input[type=radio]+.label::after {
  content: "";
}

.input[type=checkbox]:checked+.label::after {
  transform: rotate(315deg);
}

.input[type=radio]:checked+.label::after {
  transform: rotateX(180deg);
}

.bottombar {
  content: "";
  display: block;
  height: 1em;
  width: 100%;
  background-color: #00688B;
}

/* all position:absolute removed */
#scroller {
overflow:hidden;
}

#scroller .innerScrollArea {

}

#scroller ul {
  padding: 0;
  position: relative;
  display:flex;/* UPDATE */
}

#scroller li {
  padding: 0;
  list-style-type: none;
}
.circle {
  width: 130px;
  height: 130px;
  position: relative;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  border-radius: 50%;
  background-color:transparent;
  border-style:solid;
  border-width:5px;
  border-color:#006850;
}

.circle-text {
  color: #1f497d;
  font-family:Verdana;
  font-size: 12px;
  text-align: center;
  width: 200px;
  top: 45px;
  margin-left:-35px;
  bottom: 0;
  position: absolute;
  z-index: 99;
}

.circleinv{
  width: 130px;
  height: 130px;
  position: relative;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  border-radius: 50%;
  background-color:transparent;
  border-style:solid;
  border-width:5px;
  border-color:transparent;
}

.arrow {
  width:145px;
  height:45px;
}

.arrowinv {
  visibility:hidden;
  width:145px;
  height:50px;
}

.flipimage {
  width:145px;
  height:45px;
  -moz-transform: scaleY(-1);
    -webkit-transform: scaleY(-1);
    -o-transform: scaleY(-1);
    transform: scaleY(-1);
    -ms-filter: fliph; /*IE*/
    filter: fliph; /*IE*/
}

/* UPDATE  for animation */
.ul {
  animation: slidli 90s infinite linear;
}
.ul:hover {
  animation-play-state:paused;
}
@keyframes slidli {
  100% {
    transform:translatex(-733.5%);/* this is to be update to the content with to see every element slide once untill copies/clone comes back at same spot */
  }
}

      Click the "+" to expand and the "x" to collapse

    <input name="tabs" class="input" id="tab-one" type="checkbox"/>
         Content Slider

              HR Connect
Service
Representative

              Employee
Relations
Specialist

              Employee
Relations
Manager

              Director, Employee
Relations &
Well-Being

              HR Connect
Service
Representative

              Employee
Relations
Specialist

              Employee
Relations
Manager

              Director, Employee
Relations &
Well-Being

              HR Connect
Service
Representative

              Employee
Relations
Specialist

              Employee
Relations
Manager

              Director, Employee
Relations &
Well-Being

              HR Connect
Service
Representative

              Employee
Relations
Specialist

              Employee
Relations
Manager

              Director, Employee
Relations &
Well-Being

Body:
I would normally advise that you do this kind of stuff with JS but if you want to avoid it here's a working (albeit verbose) solution:

replace

.ul:hover {
  animation-play-state:paused;
}

with

.input:checked~.tab-content .container .ul:hover {
  animation-play-state:paused;
}

.tab-content .container .ul{
  animation-play-state:paused;
}
.input:checked~.tab-content .container .ul {
  animation-play-state:running;
}

Here's a pen showing the solution.
https://codepen.io/anon/pen/zzaKow


问:
How to print a DIV in ElectronJS
i'm trying to convert my web into an app made in ElectronJS

in my web i print a div with a barcode. this works pretty fine, but in electronjs i can't reach this.

originally i'd use this function

```<code>$scope.printDiv = function (divName) {
    var printContents = document.getElementById(divName).innerHTML;
    var popupWin = window.open('', '_blank', 'width=500,height=500');
    popupWin.document.open();
    popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="styles/main.css"  type=\"text/css\" media=\"print\" /></head><body onload="window.print()">' + printContents + '</body></html>');
    popupWin.document.close();
}
</code>```

with electronjs

i don't know how to pass the object to print.

also i'm trying to generate a PDF from content that i can load. but the PDF's are corrupted

```<code>var windowPrint = require('electron').remote.BrowserWindow;
    var fs = require('fs');
    var newWindow = new windowPrint({width: 800, height: 600, show: false});
    console.log(newWindow);
    newWindow.loadURL('http://github.com');
    newWindow.show();
    newWindow.webContents.print({silent: true, printBackground: true});
    newWindow.webContents.printToPDF({printSelectionOnly : true, printBackground: true}, function (error, data) {
        if (error) {
            throw error;
        }
        console.log(error);
        console.log(data);
        fs.writeFile('print.pdf', function (data, error) {
            if (error) {
                throw error;
            }
            console.log(error);
            console.log(data);
        });
    });
</code>```

there's a simple way to print a DIV with electronjs?

thank you for reading.

答:
Thank you, works for printing with print() as well

```<code>ipcMain.on('print', (event, content) => {
    workerWindow.webContents.send('print', content);
});

ipcMain.on('readyToPrint', (event) => {
    workerWindow.webContents.print({});
});
</code>```

(events are renamed accordingly)

Title: How to print a DIV in ElectronJS

Body:
i'm trying to convert my web into an app made in ElectronJS

in my web i print a div with a barcode. this works pretty fine, but in electronjs i can't reach this.

originally i'd use this function

$scope.printDiv = function (divName) {
    var printContents = document.getElementById(divName).innerHTML;
    var popupWin = window.open('', '_blank', 'width=500,height=500');
    popupWin.document.open();
    popupWin.document.write('<link rel="stylesheet" type="text/css" href="styles/main.css"  type=\"text/css\" media=\"print\" />' + printContents + '');
    popupWin.document.close();
}

with electronjs

i don't know how to pass the object to print.

also i'm trying to generate a PDF from content that i can load. but the PDF's are corrupted

var windowPrint = require('electron').remote.BrowserWindow;
    var fs = require('fs');
    var newWindow = new windowPrint({width: 800, height: 600, show: false});
    console.log(newWindow);
    newWindow.loadURL('http://github.com');
    newWindow.show();
    newWindow.webContents.print({silent: true, printBackground: true});
    newWindow.webContents.printToPDF({printSelectionOnly : true, printBackground: true}, function (error, data) {
        if (error) {
            throw error;
        }
        console.log(error);
        console.log(data);
        fs.writeFile('print.pdf', function (data, error) {
            if (error) {
                throw error;
            }
            console.log(error);
            console.log(data);
        });
    });

there's a simple way to print a DIV with electronjs?

thank you for reading.

Body:
Thank you, works for printing with print() as well

ipcMain.on('print', (event, content) => {
    workerWindow.webContents.send('print', content);
});

ipcMain.on('readyToPrint', (event) => {
    workerWindow.webContents.print({});
});

(events are renamed accordingly)


问:
PrimeNg change p-column width with template
I get following error when trying to set dynamic column width
ERROR Error: Cannot find a differ supporting object '{width: '180px', 'text-align': 'center'}'

Employee List

```
</div>
</div>
</p>

<p>userColumns defined as</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> this.userColumns = [
    {
      'field': 'userId',
      'title': 'User Id',
      'sort': 'true',
      'template': '',
      'myStyle' : ''
    },
    { 'field': 'jobTitleName', 'title': 'Job title', 'sort': 'true','myStyle': ''},
    { 'field': 'lastName',  'title': 'Last name','sort': 'true', 'myStyle': ''},
    { 'field': 'preferredFullName',  'title': 'First name','sort': 'true', 'myStyle': ''},
    { 'field': 'dateOfJoining',  'title': 'Date of Joining','sort': 'true',
      'myStyle': '{width: \'180px\', \'text-align\': \'center\'}'
    }</code>```

答:
Try changing the definition of your styling and add a single quote around "width"
like this:</p>

```<code> this.userColumns = [
    {
      'field': 'userId',
      'title': 'User Id',
      'sort': 'true',
      'template': '',
      'myStyle' : ''
    },
    { 'field': 'jobTitleName', 'title': 'Job title', 'sort': 'true','myStyle': ''},
    { 'field': 'lastName',  'title': 'Last name','sort': 'true', 'myStyle': ''},
    { 'field': 'preferredFullName',  'title': 'First name','sort': 'true', 'myStyle': ''},
    { 'field': 'dateOfJoining',  'title': 'Date of Joining','sort': 'true',
      'myStyle': '{\'width\': \'180px\', \'text-align\': \'center\'}'
    }
</code>```

Body:
I get following error when trying to set dynamic column width
ERROR Error: Cannot find a differ supporting object '{width: '180px', 'text-align': 'center'}'

Employee List

userColumns defined as

 this.userColumns = [
    {
      'field': 'userId',
      'title': 'User Id',
      'sort': 'true',
      'template': '',
      'myStyle' : ''
    },
    { 'field': 'jobTitleName', 'title': 'Job title', 'sort': 'true','myStyle': ''},
    { 'field': 'lastName',  'title': 'Last name','sort': 'true', 'myStyle': ''},
    { 'field': 'preferredFullName',  'title': 'First name','sort': 'true', 'myStyle': ''},
    { 'field': 'dateOfJoining',  'title': 'Date of Joining','sort': 'true',
      'myStyle': '{width: \'180px\', \'text-align\': \'center\'}'
    }

Body:
Try changing the definition of your styling and add a single quote around "width"
like this:

 this.userColumns = [
    {
      'field': 'userId',
      'title': 'User Id',
      'sort': 'true',
      'template': '',
      'myStyle' : ''
    },
    { 'field': 'jobTitleName', 'title': 'Job title', 'sort': 'true','myStyle': ''},
    { 'field': 'lastName',  'title': 'Last name','sort': 'true', 'myStyle': ''},
    { 'field': 'preferredFullName',  'title': 'First name','sort': 'true', 'myStyle': ''},
    { 'field': 'dateOfJoining',  'title': 'Date of Joining','sort': 'true',
      'myStyle': '{\'width\': \'180px\', \'text-align\': \'center\'}'
    }


问:
Why this setState is not a function in ComponenDidMount?
I am trying to fetch ordered data from Firebase and set it to state highscoreArray but it gives error "undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores })')</p>

```<code>    componentDidMount() {
    const reference = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function (child) {
            sortedHighscores.push({
                "username": child.val().username,
                "score": child.val().highscore
            });
        });
        sortedHighscores = sortedHighscores.reverse();
        console.log("sortedh", sortedHighscores); // fetch success
        this.setState({highscoreArray: sortedHighscores}); // gives error
    });
}
</code>```

答:
Inside the function callback the this has a different context. Either use an arrow function, or store a reference outside:

Arrow:

```<code>reference.orderByChild("highscore").limitToLast(3).on("value", (snapshot) => { ... });
</code>```

Body:
I am trying to fetch ordered data from Firebase and set it to state highscoreArray but it gives error "undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores })')

    componentDidMount() {
    const reference = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function (child) {
            sortedHighscores.push({
                "username": child.val().username,
                "score": child.val().highscore
            });
        });
        sortedHighscores = sortedHighscores.reverse();
        console.log("sortedh", sortedHighscores); // fetch success
        this.setState({highscoreArray: sortedHighscores}); // gives error
    });
}

Body:
Inside the function callback the this has a different context. Either use an arrow function, or store a reference outside:

Arrow:

reference.orderByChild("highscore").limitToLast(3).on("value", (snapshot) => { ... });


问:
In "SemVer.org" what does mean "It MAY include patch level changes" in item 7?
In http://semver.org/spec/v2.0.0.html we have a "formal description" about how to manage software versioning in a way to create a standard and avoid some dependencies management problems. In the item-spec-7 we have as follows:

Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. It MUST be incremented if any public API functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.

1) What does the bold sentences exactly mean?

1.1) Means that I could choose any value for the patch that I want? But I could not just change the patch level from the current value?

Item 1.1 makes senses for me, but the sentences order confused me. After all, the Minor value had just been incremented and the patch was reset to 0(zero).

Did I get it right?

Thanks in advance!

答:
 It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.

Means that if you are on 1.1.0, then you want to release a bunch of patch level changes, you may bump to 1.2.0
If you were at 1.1.23 and want to release a next minor, then you must reset the patch, 1.2.0