问:
how to make a carousel in the center and fit 3/4 of the page
im working with HTML and right now i just added a carousel item to my html project, my question is how can you display the carousel in the middle of the page since it appears at the left side.

www.littlebossworld.com

答:
this shows the example

This Code Help for you

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <style>
        .corosolstylelog {
            margin: 0 auto;
        }

        .carousel-inner > .item > img,
        .carousel-inner > .item > a > img {
            margin: 0 auto;
        }
    </style>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/bootstrap.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var hight = $(window).height();
            var hightforcourosol = ($(window).height() / 4) * 3;
            var width = ($(window).width() / 2);

            $('.carousel-inner img').css("height", hightforcourosol);
            $('.carousel-inner a img').css("height", hightforcourosol);
            $('.carousel-inner img').css("width", width);
            $('.carousel-inner a img').css("width", width);
        })

    </script>
</head>
<body>
    <div class="col-lg-2">
        Left Side
    </div>
    <div class="col-lg-8 corosolstylelog">

        <div id="myCarousel" class="carousel slide" data-ride="carousel">
            <!-- Indicators -->
            <ol class="carousel-indicators">
                <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                <li data-target="#myCarousel" data-slide-to="1"></li>
                <li data-target="#myCarousel" data-slide-to="2"></li>
                <li data-target="#myCarousel" data-slide-to="3"></li>
            </ol>
            <!-- Wrapper for slides -->
            <div class="carousel-inner" role="listbox">

                <div class="item active">
                    <img src="Image/Carousel/a.jpg" alt="Chania">

                    <div class="carousel-caption">
                        <h3>Chania</h3>
                        <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
                    </div>
                </div>
                <div class="item">
                    <img src="Image/Carousel/b.jpg" alt="Chania">
                    <div class="carousel-caption">
                        <h3>Chania</h3>
                        <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
                    </div>
                </div>
                <div class="item">
                    <img src="Image/Carousel/c.jpg" alt="Flower">
                    <div class="carousel-caption">
                        <h3>Flowers</h3>
                        <p>Beatiful flowers in Kolymbari, Crete.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-2">
       Right Side
    </div>
</body>
</html>
</code>```

Body:
this shows the example

This Code Help for you

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <style>
        .corosolstylelog {
            margin: 0 auto;
        }

        .carousel-inner > .item > img,
        .carousel-inner > .item > a > img {
            margin: 0 auto;
        }
    </style>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/bootstrap.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var hight = $(window).height();
            var hightforcourosol = ($(window).height() / 4) * 3;
            var width = ($(window).width() / 2);

            $('.carousel-inner img').css("height", hightforcourosol);
            $('.carousel-inner a img').css("height", hightforcourosol);
            $('.carousel-inner img').css("width", width);
            $('.carousel-inner a img').css("width", width);
        })

    </script>
</head>
<body>
    <div class="col-lg-2">
        Left Side
    </div>
    <div class="col-lg-8 corosolstylelog">

        <div id="myCarousel" class="carousel slide" data-ride="carousel">
            <!-- Indicators -->
            <ol class="carousel-indicators">
                <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                <li data-target="#myCarousel" data-slide-to="1"></li>
                <li data-target="#myCarousel" data-slide-to="2"></li>
                <li data-target="#myCarousel" data-slide-to="3"></li>
            </ol>
            <!-- Wrapper for slides -->
            <div class="carousel-inner" role="listbox">

                <div class="item active">
                    <img src="Image/Carousel/a.jpg" alt="Chania">

                    <div class="carousel-caption">
                        <h3>Chania</h3>
                        <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
                    </div>
                </div>
                <div class="item">
                    <img src="Image/Carousel/b.jpg" alt="Chania">
                    <div class="carousel-caption">
                        <h3>Chania</h3>
                        <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
                    </div>
                </div>
                <div class="item">
                    <img src="Image/Carousel/c.jpg" alt="Flower">
                    <div class="carousel-caption">
                        <h3>Flowers</h3>
                        <p>Beatiful flowers in Kolymbari, Crete.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-2">
       Right Side
    </div>
</body>
</html>


来源: stackexchange

问:
WordPress 404 and page redirection is totally wrong
I have a page, site.com/case - which works 100%, except... all the links try to go to URL www.site.com/case/actual_page

Also I made a new page, "aboutus", and the only way to access it is via site.com/case/aboutus.

So I seem to somehow put all sites behind site.com/case, which is quite wrong. I would love to get rid of the /case/ part.

So I would just have www.site.com and then sub pages such as www.site.com/case and site.com/aboutus, etc..

My .htaccess is:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

Also I have page.php:

```<code><?php /* Template Name: CustomPageT1 */ ?>

<?php
 get_header();?>

<?php
    while ( have_posts() ) : the_post();
        the_content();
    endwhile;
?>
<?php get_footer(); ?>
</code>```

And function.php, which is just empty file at this point.

Permalinks are set to Post name.

It also seems "aboutus" page directs all the links to site.com/case/aboutus/page_name, when it should just go to site.com/page_name.

Links in "aboutus" page are all written as href="page_name.php". Why is it directing like this?!

答:
So, it turns out you can't use relative links in WordPress...

I changed all my hrefs from href="pagename.php" to href="../pagename.php".

And this is working perfectly.

ContentLicense: CC BY-SA 3.0

Body:
I have a page, site.com/case - which works 100%, except... all the links try to go to URL www.site.com/case/actual_page

Also I made a new page, "aboutus", and the only way to access it is via site.com/case/aboutus.

So I seem to somehow put all sites behind site.com/case, which is quite wrong. I would love to get rid of the /case/ part.

So I would just have www.site.com and then sub pages such as www.site.com/case and site.com/aboutus, etc..

My .htaccess is:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Also I have page.php:

<?php /* Template Name: CustomPageT1 */ ?>

<?php
 get_header();?>

<?php
    while ( have_posts() ) : the_post();
        the_content();
    endwhile;
?>
<?php get_footer(); ?>

And function.php, which is just empty file at this point.

Permalinks are set to Post name.

It also seems "aboutus" page directs all the links to site.com/case/aboutus/page_name, when it should just go to site.com/page_name.

Links in "aboutus" page are all written as href="page_name.php". Why is it directing like this?!


问:
How to stop Django caching view results
I am new to Django framework.

I am using :

```<code> python==2.7_win32
    Django==1.11.3
    djangorestframework==3.6.3
</code>```

I am creating an API which do not involve any database.

Flow of data is :

User Request in JSON

Invoking method in Django's views.py

This method calls my local package that is not part of django and gets result

Return this result in the Response

Problem is :
It works perfectly in the first request but on the next request it gives previous result only.

I found that django caches the Queryset and we can force to read new data by adding all() method.

But my code do not involve any Database or Model. So I think QuerySet will also not created.But still my results are getting cached somehow. how can I stop it?

Here is my view :

```<code>@api_view(['POST'])
@never_cache
def filter_details(request):

    data = {}
    data['data'] = {}
    result_array = []
    error = None

    try:
        attr1 = request.data.get("attr1")
        attr2 = request.data.get("attr2")
        local_package_obj = local_package.ClassName(attr1)
        result_array = local_package_obj.get_some_data_as_array(attr2)
    except Exception as e:
        error = str(e)

    data['data']['important'] = result_array
    data['error'] = error

    return Response(data)
</code>```

Even after applying different values for att1 and attr2 I am getting same results.
I have checked local package. I works properly. The problem is in caching only.

答:
I works properly. The problem is in caching only.

No it doesn't work properly.
If you face some caching issues, you probably have a scope issue somewhere and you're not aware of it.

For example, if you have something like this in your module:

```<code># This is a file
queryset = SomeModel.objects.all()

def my_function():
    return list(queryset)  # list() will force the QS evaluation
</code>```

If you call my_function() it'll will return a list of instances. Add or remove some instances and you won't see a change.

The reason is queryset is evaluated once and will stay evaluated.

if you change the code as:

```<code>def my_function():
    return list(queryset.all())
</code>```

you'll see the list change. This is because .all() will return a new queryset which means it is not evaluated.

Most of the time, I prefer to be explicit and create the queryset directly from the function:

```<code>def my_function():
    return list(SomeModel.objects.all())
</code>```

Title: How to stop Django caching view results

Body:
I am new to Django framework.

I am using :

 python==2.7_win32
    Django==1.11.3
    djangorestframework==3.6.3

I am creating an API which do not involve any database.

Flow of data is :

User Request in JSON

Invoking method in Django's views.py

This method calls my local package that is not part of django and gets result

Return this result in the Response

Problem is :
It works perfectly in the first request but on the next request it gives previous result only.

I found that django caches the Queryset and we can force to read new data by adding all() method.

But my code do not involve any Database or Model. So I think QuerySet will also not created.But still my results are getting cached somehow. how can I stop it?

Here is my view :

@api_view(['POST'])
@never_cache
def filter_details(request):

    data = {}
    data['data'] = {}
    result_array = []
    error = None

    try:
        attr1 = request.data.get("attr1")
        attr2 = request.data.get("attr2")
        local_package_obj = local_package.ClassName(attr1)
        result_array = local_package_obj.get_some_data_as_array(attr2)
    except Exception as e:
        error = str(e)

    data['data']['important'] = result_array
    data['error'] = error

    return Response(data)

Even after applying different values for att1 and attr2 I am getting same results.
I have checked local package. I works properly. The problem is in caching only.

Body:
I works properly. The problem is in caching only.

No it doesn't work properly.
If you face some caching issues, you probably have a scope issue somewhere and you're not aware of it.

For example, if you have something like this in your module:

# This is a file
queryset = SomeModel.objects.all()

def my_function():
    return list(queryset)  # list() will force the QS evaluation

If you call my_function() it'll will return a list of instances. Add or remove some instances and you won't see a change.

The reason is queryset is evaluated once and will stay evaluated.

if you change the code as:

def my_function():
    return list(queryset.all())

you'll see the list change. This is because .all() will return a new queryset which means it is not evaluated.

Most of the time, I prefer to be explicit and create the queryset directly from the function:

def my_function():
    return list(SomeModel.objects.all())


问:
How do I get from google-services.json to GoogleServices-info.plist?
I am building for iOS in Unity using the Firebase Unity plugin and getting an error that says that there is no GoogleServices-info.plist found in my project and so it fails to build for iOS. According to the Firebase docs, you're supposed to download the plist file from the Dasboard but of course when you go there you find they only offer you a .json file download for iOS projects.

What am I missing? How do I get a .plist file? Is it supposed to generate?

答:
On firebase, if you create an iOS app for your project, the file it offers to download is actually a .plist file.

On the overview of your project it shows your app, you should have the android and the iOS one there:

Then you click on the options for your iOS app

Click on "Settings"

Then from here:

Click on "GoogleService-Info.plist"

Can you check your project has an iOS app?


问:
Pass data from a component to a modal dialog in angular 4
I have an angular 4 application and I have 2 components a timeline and a modal dialog. When I double click on the timeline I want to open the modal dialog with the datas passed into the double click function.

So, in the timeline.component.ts, I have :

```<code>        Timeline.prototype.onTaskDoubleClick = function(task){
            console.log("Double click on task" + task.id);
            console.log(task);
            $('#addProjectForm').click();
        }
</code>```

How can I do to pass the object 'task' from this function to the modal component ?

答:
Use @Input and @Output for the flow.

Create a component container, and two other containers timeline and modal

inject both timeline and modal in the container component.

Now on click in Timeline component use the following

```<code>clickEmitter = new EventEmitter<task: any>()

doubleClick(task: any) {
  this.clickEmitter.emit(task);
}
</code>```

Now bind this output to the container component as follows

```<code><timeline  (clickEmitter)="clickHandler($event)"></timeline>
<modal [task]="modalInput"></modal>
</code>```

Now the task container can get this from the conatiner as follows.

In Container Component

```<code>modalInput: any;

clickHandler(task) {
  this.modalInput = task;
}
</code>```

Now, this can be recieved by Modal component as follows,

```<code>@Input
task
</code>```

Body:
I have an angular 4 application and I have 2 components a timeline and a modal dialog. When I double click on the timeline I want to open the modal dialog with the datas passed into the double click function.

So, in the timeline.component.ts, I have :

        Timeline.prototype.onTaskDoubleClick = function(task){
            console.log("Double click on task" + task.id);
            console.log(task);
            $('#addProjectForm').click();
        }

How can I do to pass the object 'task' from this function to the modal component ?

Body:
Use @Input and @Output for the flow.

Create a component container, and two other containers timeline and modal

inject both timeline and modal in the container component.

Now on click in Timeline component use the following

clickEmitter = new EventEmitter<task: any>()

doubleClick(task: any) {
  this.clickEmitter.emit(task);
}

Now bind this output to the container component as follows

<timeline  (clickEmitter)="clickHandler($event)"></timeline>
<modal [task]="modalInput"></modal>

Now the task container can get this from the conatiner as follows.

In Container Component

modalInput: any;

clickHandler(task) {
  this.modalInput = task;
}

Now, this can be recieved by Modal component as follows,

@Input
task


问:
Find/parse server-side <?abc?>-like tags in html document
I guess I need some regex help. I want to find all tags like <?abc?> so that I can replace it with whatever the results are for the code ran inside. I just need help regexing the tag/code string, not parsing the code inside :p.

<?abc print 'test' ?> would result in test

Edit:  Not specifically but in general, matching (<?[chars] (code group) ?>)

答:
```<code>exp = new Regex(@"<\?abc print'(.+)' \?>");
str = exp.Replace(str, "$1")
</code>```

Something like this should do the trick.  Change the regexes how you see fit

ContentLicense: CC BY-SA 2.5

Body:
exp = new Regex(@"<\?abc print'(.+)' \?>");
str = exp.Replace(str, "$1")

Something like this should do the trick.  Change the regexes how you see fit


问:
Auto layout constraints not working properly swift 3.0
Kinda new to this whole auto layout constraints part. My app is closing up on a beta and i'm having trouble getting the constraints right. In the picture below i have succesfully managed to add the following constraints to each object

Horizontally in container

All objects has been pinned top - bottom - left - right to there nearest object.

As you can see in the picture this behaviour results in fine layout for Iphone 6 and larger but when running on a Iphone 5 simulator or Iphone 4 preview, the layout is bad.

What can i do to achieve the same layout behaviour on smaller devices, so that my labels and img does not crop??

Thank you, in advance!

答: For each label, keep the horizontal center constraint, but remove the leading and trailing (left and right) constraints. The label will then automatically resize to fit the content's width.</p>


问:
Passing column name to parameter
I have a table with ticketID, clientmachineName and UserName columns.
i need to write a stored procedure where i have to pass each column name as parameter and value also as parameter.

It should write output query as

```<code>select * from table where @cloumn=@value.
</code>```

can anyone help please..

答:
you will need dynamic SQL like:</p>

```<code>DECLARE @myquery varchar(1000) = 'select * from table where ' + @column + '=''' + @value + ''''
EXEC @myquery
</code>```

Title: Passing column name to parameter

Body:
I have a table with ticketID, clientmachineName and UserName columns.
i need to write a stored procedure where i have to pass each column name as parameter and value also as parameter.

It should write output query as

select * from table where @cloumn=@value.

can anyone help please..

Body:
you will need dynamic SQL like:

DECLARE @myquery varchar(1000) = 'select * from table where ' + @column + '=''' + @value + ''''
EXEC @myquery


问:
SSL in Play Framework causes 'General SSLEngine prob.' (nginx)
I have a server structure of 2 servers: One is the main server with the content and the other is a Scala server with Play running, doing the user management including social login (fb, tw, g+). Both server use the same wildcard SSL cert.

I recently switched on the main server from Apache to nginx and for some reason, the Scala server complains about the SSL mismatch (which has never been a problem before under Apache).

When I try to login, I get the following error from Play:

```<code>[error] s.c.ProviderController - Unable to log user in. An exception was thrown
java.net.ConnectException: General SSLEngine problem to https://www.example.com/login/corsValid
    at com.ning.http.client.providers.netty.NettyConnectListener.operationComplete(NettyConnectListener.java:103) ~[async-http-client.jar:na]
    at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:427) ~[netty.jar:na]
    at org.jboss.netty.channel.DefaultChannelFuture.notifyListeners(DefaultChannelFuture.java:413) ~[netty.jar:na]
    at org.jboss.netty.channel.DefaultChannelFuture.setFailure(DefaultChannelFuture.java:380) ~[netty.jar:na]
    at org.jboss.netty.handler.ssl.SslHandler.setHandshakeFailure(SslHandler.java:1417) ~[netty.jar:na]
    at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1293) ~[netty.jar:na]
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1290) ~[na:1.7.0_51]
    at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:513) ~[na:1.7.0_51]
    at sun.security.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:793) ~[na:1.7.0_51]
    at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:761) ~[na:1.7.0_51]
    at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:624) ~[na:1.7.0_51]
    at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1225) ~[netty.jar:na]
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[na:1.7.0_51]
    at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1694) ~[na:1.7.0_51]
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:278) ~[na:1.7.0_51]
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270) ~[na:1.7.0_51]
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341) ~[na:1.7.0_51]
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153) ~[na:1.7.0_51]
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385) ~[na:1.7.0_51]
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) ~[na:1.7.0_51]
    at sun.security.validator.Validator.validate(Validator.java:260) ~[na:1.7.0_51]
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326) ~[na:1.7.0_51]
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:283) ~[na:1.7.0_51]
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:138) ~[na:1.7.0_51]
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196) ~[na:1.7.0_51]
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268) ~[na:1.7.0_51]
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380) ~[na:1.7.0_51]
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) ~[na:1.7.0_51]
    at sun.security.validator.Validator.validate(Validator.java:260) ~[na:1.7.0_51]
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326) ~[na:1.7.0_51]
</code>```

I traced down the problem and found out that the application.conf needs to have correct parameters for the SSL certs being used. I created a JKS and P12 cert and included it in the conf file, but I still get this error. (Maybe wrong path? Tried that as well...)

```<code>ws.ssl {
  trustManager = {
    stores = [
      { path: "ssl.jks" }
    ]
  }
}
</code>```

However, when I add ws.acceptAnyCertificate=true instead everything is fine, but this is clearly a security vulnerability and nothing I wanna do.

Why is installing an SSL cert such a pain in Play?

Thanks

答:
I think Play mainly an application framework, not a web server.

Our play apps always communicate unsecured with Nginx web server (in DMZ), SSL/TLS communication terminated with Nginx. With this design, you can load balance if your Play app is stateless.

Then if you want, forward everything in custom http headers from Nginx to backend (eg. client certification) for validation.

```<code>proxy_set_header APP-Cert-Verified $ssl_client_verify;
proxy_set_header APP-Client-Cert $ssl_client_cert;
proxy_set_header APP-Client-Cert-DN $ssl_client_s_dn;
</code>```

You can find this in the official documentation as well:
https://www.playframework.com/documentation/2.5.x/HTTPServer#Set-up-with-nginx.

Bonus: if certification expires you can change certs in nginx more easily, than restart your Play app.

Body:
I have a server structure of 2 servers: One is the main server with the content and the other is a Scala server with Play running, doing the user management including social login (fb, tw, g+). Both server use the same wildcard SSL cert.

I recently switched on the main server from Apache to nginx and for some reason, the Scala server complains about the SSL mismatch (which has never been a problem before under Apache).

When I try to login, I get the following error from Play:

[error] s.c.ProviderController - Unable to log user in. An exception was thrown
java.net.ConnectException: General SSLEngine problem to https://www.example.com/login/corsValid
    at com.ning.http.client.providers.netty.NettyConnectListener.operationComplete(NettyConnectListener.java:103) ~[async-http-client.jar:na]
    at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:427) ~[netty.jar:na]
    at org.jboss.netty.channel.DefaultChannelFuture.notifyListeners(DefaultChannelFuture.java:413) ~[netty.jar:na]
    at org.jboss.netty.channel.DefaultChannelFuture.setFailure(DefaultChannelFuture.java:380) ~[netty.jar:na]
    at org.jboss.netty.handler.ssl.SslHandler.setHandshakeFailure(SslHandler.java:1417) ~[netty.jar:na]
    at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1293) ~[netty.jar:na]
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1290) ~[na:1.7.0_51]
    at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:513) ~[na:1.7.0_51]
    at sun.security.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:793) ~[na:1.7.0_51]
    at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:761) ~[na:1.7.0_51]
    at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:624) ~[na:1.7.0_51]
    at org.jboss.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1225) ~[netty.jar:na]
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[na:1.7.0_51]
    at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1694) ~[na:1.7.0_51]
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:278) ~[na:1.7.0_51]
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270) ~[na:1.7.0_51]
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341) ~[na:1.7.0_51]
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153) ~[na:1.7.0_51]
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385) ~[na:1.7.0_51]
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) ~[na:1.7.0_51]
    at sun.security.validator.Validator.validate(Validator.java:260) ~[na:1.7.0_51]
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326) ~[na:1.7.0_51]
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:283) ~[na:1.7.0_51]
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:138) ~[na:1.7.0_51]
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196) ~[na:1.7.0_51]
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268) ~[na:1.7.0_51]
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380) ~[na:1.7.0_51]
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) ~[na:1.7.0_51]
    at sun.security.validator.Validator.validate(Validator.java:260) ~[na:1.7.0_51]
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326) ~[na:1.7.0_51]

I traced down the problem and found out that the application.conf needs to have correct parameters for the SSL certs being used. I created a JKS and P12 cert and included it in the conf file, but I still get this error. (Maybe wrong path? Tried that as well...)

ws.ssl {
  trustManager = {
    stores = [
      { path: "ssl.jks" }
    ]
  }
}

However, when I add ws.acceptAnyCertificate=true instead everything is fine, but this is clearly a security vulnerability and nothing I wanna do.

Why is installing an SSL cert such a pain in Play?

Thanks

Body:
I think Play mainly an application framework, not a web server.

Our play apps always communicate unsecured with Nginx web server (in DMZ), SSL/TLS communication terminated with Nginx. With this design, you can load balance if your Play app is stateless.

Then if you want, forward everything in custom http headers from Nginx to backend (eg. client certification) for validation.

proxy_set_header APP-Cert-Verified $ssl_client_verify;
proxy_set_header APP-Client-Cert $ssl_client_cert;
proxy_set_header APP-Client-Cert-DN $ssl_client_s_dn;

You can find this in the official documentation as well:
https://www.playframework.com/documentation/2.5.x/HTTPServer#Set-up-with-nginx.

Bonus: if certification expires you can change certs in nginx more easily, than restart your Play app.


问:
Why is an empty loop invalid in shell script?
I wanted to make my shell script wait infinitely and thought the below code would do it.

```<code>#!/bin/bash
while true
do
done
</code>```

However, the above script reports syntax error.

./Infinite_Loop.sh: line 4: syntax error near unexpected token `done'

./Infinite_Loop.sh: line 4: `done'

Unlike programming languages, why does shell script expect at least one statement in loops?

答:
Another option is just to set a NOP(no op) which is basically, do nothing.

In bash, the equivalent for a NOP is :.

```<code>while true; do
  :
done
</code>```

Body:
I wanted to make my shell script wait infinitely and thought the below code would do it.

#!/bin/bash
while true
do
done

However, the above script reports syntax error.

./Infinite_Loop.sh: line 4: syntax error near unexpected token `done'

./Infinite_Loop.sh: line 4: `done'

Unlike programming languages, why does shell script expect at least one statement in loops?

Body:
Another option is just to set a NOP(no op) which is basically, do nothing.

In bash, the equivalent for a NOP is :.

while true; do
  :
done


问:
Elasticsearch aggregations for faceted search excluding some fields
I have shop which use elasticsearch 2.4 for faceted search.
But at the moment the existing filters (product attributes) are taken from mysql. I want to do this using elasticsearch aggregations.
But I got the problem: I do not need to aggregate all the attributes.

What a have:

Part of Mapping:

```<code>...
'is_active' => [
    'type' => 'long',
    'index' => 'not_analyzed',
],
'category_id' => [
    'type' => 'long',
    'index' => 'not_analyzed',
],
'attrs' => [
    'properties' => [
        'attr_name' => ['type' => 'string', 'index'     => 'not_analyzed'],
        'value' => [
            'type' => 'string',
            'index' => 'analyzed',
            'analyzer' => 'attrs_analizer',
        ],
    ]
],
...
</code>```

Exemple of data:

```<code>{
    "id": 1,
    "is_active": "1",
    "category_id": 189,
    ...
    "price": "48.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "TP-Link"
      },
      {
        "attr_name": "Model",
        "value": "TL-1"
      },
      {
        "attr_name": "Other",
        "value": "<div>Some text of 'Other' property<br><img src......><ul><li>......</ul></div>"
      }
    ]
  },
  {
    "id": 2,
    "is_active": "1",
    "category_id": 242,
    ...
    "price": "12.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "Lenovo"
      },
      {
        "attr_name": "Model",
        "value": "B570"
      },
      {
        "attr_name": "OS",
        "value": "Linux"
      },
      {
        "attr_name": "Other",
        "value": "<div>Some text of 'Other' property<br><img src......><ul><li>......</ul></div>"
      }
    ]
  },
  {
    "id": 3,
    "is_active": "1",
    "category_id": 242,
    ...
    "price": "24.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "Asus"
      },
      {
        "attr_name": "Model",
        "value": "QZ85"
      },
      {
        "attr_name": "OS",
        "value": "Windows"
      },
      {
        "attr_name": "Other",
        "value": "<div>Some text of 'Other' property<br><img src......><ul><li>......</ul></div>"
      }
    ]
  }
</code>```

Attributes such as "Model" and "Other" are not used when filtering products, they are only displayed on the product page. On the other attributes (Brand, OS, and others ...) I want to receive aggregations.

When I try to aggregate the attrs.value field, of course I get aggregations for all data (including the large "Other" fields, in which there can be a lot of HTML).

```<code>"aggs": {
    "facet_value": {
      "terms": {
        "field": "attrs.value",
        "size": 0
      }
    }
  }
</code>```

How to exclude "attrs.attr_name": ["Model", "Other"]?

Change the mapping is a bad solution for me, but if it is inevitable, tell me how to do it? I guess I'll need to make "attrs" nested?

UPD:

I want to receive:
 1. All the attributes that the products have in a certain category, except for those that I indicate in the settings of the my system (in this example I will exclude "Model" and "Other").
 2. Number of products near each value.

It should look like this:

For category "Laptops":

Brand:

Lenovo (18)

Asus (19)

.....

OS:

Windows (19)

Linux (5)

...

For "computer monitors":

Brand:

Samsung (18)

LG (19)

.....

Resolution:

1360x768 (19)

1920x1080 (22)

....

It's Terms Aggregation , I use this for the number of products for each category. And I try it for attrs.value, but I do not know how to exclude "attrs.value", which refer to "attrs.attr_name": "Model" & "attrs.attr_name": "Other".

UPD2:

In my case if map attrs as nested type, the weight of the index increases by 30%.
from 2700Mi to 3510Mi.
If there is no other option, I'll have to put up with it.

答:
you have to map first attrs as nested type and use nested aggregations.

```<code>PUT no_play
{
  "mappings": {
    "document_type" : {
      "properties": {
        "is_active" : {
          "type": "long"
        },
        "category_id" : {
          "type": "long"
        },
        "attrs" : {
          "type": "nested",
          "properties": {
            "attr_name" : {
              "type" : "keyword"
            },
            "value" : {
              "type" : "keyword"
            }
          }
        }
      }
    }
  }
}

POST no_play/document_type
  {
    "id": 3,
    "is_active": "1",
    "category_id": 242,
    "price": "24.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "Asus"
      },
      {
        "attr_name": "Model",
        "value": "QZ85"
      },
      {
        "attr_name": "OS",
        "value": "<div>Some text of 'Other' property<br><img src......><ul><li>......</ul></div>"
      },
      {
        "attr_name": "Other",
        "value": "<div>Some text of 'Other' property<br><img src......><ul><li>......</ul></div>"
      }
    ]
  }
</code>```

Since you didn't mention how you want to aggregate.

Case 1) If you want to count the attrs as individual. This metric gives you count of term occurrences.

```<code>POST no_play/_search
{
  "size": 0,
  "aggs": {
    "nested_aggregation_value": {
      "nested": {
        "path": "attrs"
      },
      "aggs": {
        "value_term": {
          "terms": {
            "field": "attrs.value",
            "size": 10
          }
        }
      }
    }
  }
}

POST no_play/_search
    {
      "size": 0,
      "aggs": {
        "nested_aggregation_value": {
          "nested": {
            "path": "attrs"
          },
          "aggs": {
            "value_term": {
              "terms": {
                "field": "attrs.value",
                "size": 10
              },
              "aggs": {
                "reverse_back_to_roots": {
                  "reverse_nested": {
                  }
                }
              }
            }
          }
        }
      }
    }
</code>```

Now to get count of root document with attrs value you will need to hook a reverse nested aggregation to move the aggregator a level up to the level of root document.

Think of the following document.

```<code>{
    "id": 3,
    "is_active": "1",
    "category_id": 242,
    "price": "24.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "Asus"
      },
      {
        "attr_name": "Model",
        "value": "QZ85"
      },
      {
        "attr_name": "OS",
        "value": "repeated value"
      },
      {
        "attr_name": "Other",
        "value": "repeated value"
      }
    ]
  }
</code>```

For first query the value count for 'repeated value' will be 2 and for second query it will be 1

Note

here is how you can do filtering to exclude

```<code>POST no_play/_search
{
    "size": 0,
    "aggs": {
        "nested_aggregation_value": {
            "nested": {
                "path": "attrs"
            },
            "aggs": {
                "filtered_results": {
                    "filter": {
                        "bool": {
                            "must_not": [{
                                "terms": {
                                    "attrs.attr_name": ["Model", "Brand"]
                                }
                            }]
                        }
                    },
                    "aggs": {
                        "value_term": {
                            "terms": {
                                "field": "attrs.value",
                                "size": 10
                            }
                        }
                    }
                }
            }
        }
    }
}

POST no_play/_search
 {
    "size": 0,
    "aggs": {
        "nested_aggregation_value": {
            "nested": {
                "path": "attrs"
            },
            "aggs": {
                "filtered_results": {
                    "filter": {
                        "bool": {
                            "must_not": [{
                                "terms": {
                                    "attrs.attr_name": ["Model", "Brand"]
                                }
                            }]
                        }
                    },
                    "aggs": {
                        "value_term": {
                            "terms": {
                                "field": "attrs.value",
                                "size": 10
                            },
                            "aggs": {
                                "reverse_back_to_roots": {
                                    "reverse_nested": {}
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 }
</code>```

Thanks

Body:
I have shop which use elasticsearch 2.4 for faceted search.
But at the moment the existing filters (product attributes) are taken from mysql. I want to do this using elasticsearch aggregations.
But I got the problem: I do not need to aggregate all the attributes.

What a have:

Part of Mapping:

...
'is_active' => [
    'type' => 'long',
    'index' => 'not_analyzed',
],
'category_id' => [
    'type' => 'long',
    'index' => 'not_analyzed',
],
'attrs' => [
    'properties' => [
        'attr_name' => ['type' => 'string', 'index'     => 'not_analyzed'],
        'value' => [
            'type' => 'string',
            'index' => 'analyzed',
            'analyzer' => 'attrs_analizer',
        ],
    ]
],
...

Exemple of data:

{
    "id": 1,
    "is_active": "1",
    "category_id": 189,
    ...
    "price": "48.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "TP-Link"
      },
      {
        "attr_name": "Model",
        "value": "TL-1"
      },
      {
        "attr_name": "Other",
        "value": "
Some text of 'Other' property

......

"
      }
    ]
  },
  {
    "id": 2,
    "is_active": "1",
    "category_id": 242,
    ...
    "price": "12.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "Lenovo"
      },
      {
        "attr_name": "Model",
        "value": "B570"
      },
      {
        "attr_name": "OS",
        "value": "Linux"
      },
      {
        "attr_name": "Other",
        "value": "
Some text of 'Other' property

......

"
      }
    ]
  },
  {
    "id": 3,
    "is_active": "1",
    "category_id": 242,
    ...
    "price": "24.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "Asus"
      },
      {
        "attr_name": "Model",
        "value": "QZ85"
      },
      {
        "attr_name": "OS",
        "value": "Windows"
      },
      {
        "attr_name": "Other",
        "value": "
Some text of 'Other' property

......

"
      }
    ]
  }

Attributes such as "Model" and "Other" are not used when filtering products, they are only displayed on the product page. On the other attributes (Brand, OS, and others ...) I want to receive aggregations.

When I try to aggregate the attrs.value field, of course I get aggregations for all data (including the large "Other" fields, in which there can be a lot of HTML).

"aggs": {
    "facet_value": {
      "terms": {
        "field": "attrs.value",
        "size": 0
      }
    }
  }

How to exclude "attrs.attr_name": ["Model", "Other"]?

Change the mapping is a bad solution for me, but if it is inevitable, tell me how to do it? I guess I'll need to make "attrs" nested?

UPD:

I want to receive:
 1. All the attributes that the products have in a certain category, except for those that I indicate in the settings of the my system (in this example I will exclude "Model" and "Other").
 2. Number of products near each value.

It should look like this:

For category "Laptops":

Brand:

Lenovo (18)

Asus (19)

.....

OS:

Windows (19)

Linux (5)

...

For "computer monitors":

Brand:

Samsung (18)

LG (19)

.....

Resolution:

1360x768 (19)

1920x1080 (22)

....

It's Terms Aggregation , I use this for the number of products for each category. And I try it for attrs.value, but I do not know how to exclude "attrs.value", which refer to "attrs.attr_name": "Model" & "attrs.attr_name": "Other".

UPD2:

In my case if map attrs as nested type, the weight of the index increases by 30%.
from 2700Mi to 3510Mi.
If there is no other option, I'll have to put up with it.

Body:
you have to map first attrs as nested type and use nested aggregations.

PUT no_play
{
  "mappings": {
    "document_type" : {
      "properties": {
        "is_active" : {
          "type": "long"
        },
        "category_id" : {
          "type": "long"
        },
        "attrs" : {
          "type": "nested",
          "properties": {
            "attr_name" : {
              "type" : "keyword"
            },
            "value" : {
              "type" : "keyword"
            }
          }
        }
      }
    }
  }
}

POST no_play/document_type
  {
    "id": 3,
    "is_active": "1",
    "category_id": 242,
    "price": "24.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "Asus"
      },
      {
        "attr_name": "Model",
        "value": "QZ85"
      },
      {
        "attr_name": "OS",
        "value": "<div>Some text of 'Other' property<br><img src......><ul><li>......</ul></div>"
      },
      {
        "attr_name": "Other",
        "value": "<div>Some text of 'Other' property<br><img src......><ul><li>......</ul></div>"
      }
    ]
  }

Since you didn't mention how you want to aggregate.

Case 1) If you want to count the attrs as individual. This metric gives you count of term occurrences.

POST no_play/_search
{
  "size": 0,
  "aggs": {
    "nested_aggregation_value": {
      "nested": {
        "path": "attrs"
      },
      "aggs": {
        "value_term": {
          "terms": {
            "field": "attrs.value",
            "size": 10
          }
        }
      }
    }
  }
}

POST no_play/_search
    {
      "size": 0,
      "aggs": {
        "nested_aggregation_value": {
          "nested": {
            "path": "attrs"
          },
          "aggs": {
            "value_term": {
              "terms": {
                "field": "attrs.value",
                "size": 10
              },
              "aggs": {
                "reverse_back_to_roots": {
                  "reverse_nested": {
                  }
                }
              }
            }
          }
        }
      }
    }

Now to get count of root document with attrs value you will need to hook a reverse nested aggregation to move the aggregator a level up to the level of root document.

Think of the following document.

{
    "id": 3,
    "is_active": "1",
    "category_id": 242,
    "price": "24.00",
    "attrs": [
      {
        "attr_name": "Brand",
        "value": "Asus"
      },
      {
        "attr_name": "Model",
        "value": "QZ85"
      },
      {
        "attr_name": "OS",
        "value": "repeated value"
      },
      {
        "attr_name": "Other",
        "value": "repeated value"
      }
    ]
  }

For first query the value count for 'repeated value' will be 2 and for second query it will be 1

Note

here is how you can do filtering to exclude

POST no_play/_search
{
    "size": 0,
    "aggs": {
        "nested_aggregation_value": {
            "nested": {
                "path": "attrs"
            },
            "aggs": {
                "filtered_results": {
                    "filter": {
                        "bool": {
                            "must_not": [{
                                "terms": {
                                    "attrs.attr_name": ["Model", "Brand"]
                                }
                            }]
                        }
                    },
                    "aggs": {
                        "value_term": {
                            "terms": {
                                "field": "attrs.value",
                                "size": 10
                            }
                        }
                    }
                }
            }
        }
    }
}

POST no_play/_search
 {
    "size": 0,
    "aggs": {
        "nested_aggregation_value": {
            "nested": {
                "path": "attrs"
            },
            "aggs": {
                "filtered_results": {
                    "filter": {
                        "bool": {
                            "must_not": [{
                                "terms": {
                                    "attrs.attr_name": ["Model", "Brand"]
                                }
                            }]
                        }
                    },
                    "aggs": {
                        "value_term": {
                            "terms": {
                                "field": "attrs.value",
                                "size": 10
                            },
                            "aggs": {
                                "reverse_back_to_roots": {
                                    "reverse_nested": {}
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 }

Thanks


Title: How to convert values of a matrix into percentage without changing the format in R

Body:
I have a matrix which is res

 > res
                     [,1]         [,2]       [,3]       [,4]       [,5]
        [1,]  0.025431667  0.024636307 0.02812685 0.02733088 0.02807624
        [2,] -0.005383589  0.000000000 0.02807624 0.02258878 0.02322090
        [3,] -0.002674251 -0.002674251 0.05502400 0.00000000 0.01385476
        [4,]  0.055024000  0.061028259 0.05932779 0.05956794 0.05839394
        [5,]  0.059327790  0.059567938 0.05839394 0.06048811 0.05944368

I want to have the results as percentage and keep the data structure unchanged.

When I try something like percent(res) from scales I get a vector instead of a matrix

> percent(res)
 [1] "2.54%"  "-0.54%" "-0.27%" "5.50%"  "5.93%"  "2.46%"  "0.00%"  "-0.27%"
 [9] "6.10%"  "5.96%"  "2.81%"  "2.81%"  "5.50%"  "5.93%"  "5.84%"  "2.73%"
[17] "2.26%"  "0.00%"  "5.96%"  "6.05%"  "2.81%"  "2.32%"  "1.39%"  "5.84%"
[25] "5.94%"

Any suggestions?

Body:
the function percent of formmattable package work fine with matrix :

library(formattable)
    percent(res)

and this is the result :

     X..1.  X..2.  X..3. X..4. X..5.
[1,] 2.54%  2.46%  2.81% 2.73% 2.81%
[2,] -0.54% 0.00%  2.81% 2.26% 2.32%
[3,] -0.27% -0.27% 5.50% 0.00% 1.39%
[4,] 5.50%  6.10%  5.93% 5.96% 5.84%
[5,] 5.93%  5.96%  5.84% 6.05% 5.94%


问:
How can I make private static field of the static class thread safe?
I have a static class which has a private Dictionary. I have written public methods to add and remove objects to it. Now I want to ensure that when I remove one of the items from dictionary, noone else is using it.

How can I achieve this?

答:
Do you mean you want to ensure that no-one else is using the dictionary, or no-one else is using the value which was in the dictionary?

You can solve the first using locking... but you can't really do the second. Someone could fetch a reference to the object from the dictionary and store that reference for as long as they like. There may be a solution if the value is an interface type - you could delegate all calls through an extra "wrapper" class, and invalidate that wrapper class. I can go into more details if you want, but I'm hoping you're really just interested in the first type of safety :)

That can be achieved like this:

```<code>private static readonly object mutex = new object();

// Or whatever
private static readonly Dictionary<string, string> map =
    new Dictionary<string, string>();

public static void AddEntry(string key, string value)
{
    lock (mutex)
    {
        map[key] = value;
    }
}

public static string GetValue(string key, string value)
{
    lock (mutex)
    {
        return map[key];
    }
}
</code>```

Obviously you'll want to tweak how you're using the dictionary.

If you're using .NET 4, another alternative would be to use ConcurrentDictionary which is already thread-safe.

Body:
Do you mean you want to ensure that no-one else is using the dictionary, or no-one else is using the value which was in the dictionary?

You can solve the first using locking... but you can't really do the second. Someone could fetch a reference to the object from the dictionary and store that reference for as long as they like. There may be a solution if the value is an interface type - you could delegate all calls through an extra "wrapper" class, and invalidate that wrapper class. I can go into more details if you want, but I'm hoping you're really just interested in the first type of safety :)

That can be achieved like this:

private static readonly object mutex = new object();

// Or whatever
private static readonly Dictionary<string, string> map =
    new Dictionary<string, string>();

public static void AddEntry(string key, string value)
{
    lock (mutex)
    {
        map[key] = value;
    }
}

public static string GetValue(string key, string value)
{
    lock (mutex)
    {
        return map[key];
    }
}

Obviously you'll want to tweak how you're using the dictionary.

If you're using .NET 4, another alternative would be to use ConcurrentDictionary which is already thread-safe.


答:
I wanted to make my shell script wait infinitely

If your system supports it use:

sleep infinity
```

<p>If your system doesn't support it, use <code>sleep</code> with a large interval:</p>

<pre class="lang-sh prettyprint-override"><code>while :; do sleep 86400; done
</code>```

Note:

Using while : in place of while true may/will remove an unnecessary fork, depending on how true is implemented (built into the shell, or as a stand alone application).

You are trying to implement a busy loop, do not do this.

A busy loop will:

Use 100% CPU for no useful purpose

Prevent other tasks from getting CPU time

Reduce the perceived performance of the whole system

Use more power than necessary, especially so on systems that support dynamic frequency scaling

Why is an empty loop invalid in shell script?

Because it is... The format for a while loop in bash is as follows:

while list-1; do list-2; done
```

<p>If you don't provide <code>list-2</code>, then you don't have a correctly formatted <code>while</code> loop.</p>

<p>As pointed out by others, use a noop (<code>:</code>) or <em>anything</em> else to satisfy <code>list-2</code>.</p>

<p><code>:</code> is documented as follows:</p>

<pre class="lang-none prettyprint-override"><code>: [arguments]
    No effect; the command does nothing beyond expanding arguments and performing any
    specified redirections.  A zero exit code is returned.
</code>```

Body:
I wanted to make my shell script wait infinitely

If your system supports it use:

sleep infinity

If your system doesn't support it, use sleep with a large interval:

while :; do sleep 86400; done

Note:

Using while : in place of while true may/will remove an unnecessary fork, depending on how true is implemented (built into the shell, or as a stand alone application).

You are trying to implement a busy loop, do not do this.

A busy loop will:

Use 100% CPU for no useful purpose

Prevent other tasks from getting CPU time

Reduce the perceived performance of the whole system

Use more power than necessary, especially so on systems that support dynamic frequency scaling

Why is an empty loop invalid in shell script?

Because it is... The format for a while loop in bash is as follows:

while list-1; do list-2; done

If you don't provide list-2, then you don't have a correctly formatted while loop.

As pointed out by others, use a noop (:) or anything else to satisfy list-2.

: is documented as follows:

: [arguments]
    No effect; the command does nothing beyond expanding arguments and performing any
    specified redirections.  A zero exit code is returned.


问:
Conflict between div scrollbar and browser scrollbar
I have a div and I want to attach a scrollbar to it to keep the menu fixed (Tab1 here).

BODY
{
 font-size:0.8em;
    MARGIN: 0px 0px 0px 10px;
 COLOR: #000;
    FONT-FAMILY: Tahoma, Verdana, Arial, Helvetica, sans-serif;
    BACKGROUND-COLOR: #ffffff;
 background: url(null) fixed #ffffff;
}

H1
{
    MARGIN-TOP: 20px;
    FONT-WEIGHT: bold;
    FONT-SIZE: 16px;
    MARGIN-BOTTOM: 10px;
 COLOR: #A1006B;
    TEXT-ALIGN: left;
    FONT-VARIANT: normal
}

#tabs-1 {
font-size: 14px;}
.ui-widget-header{
background:#ffff;
}

#tabs-2 {
overflow-y:scroll;
height:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><title>Test</title>

<link rel="stylesheet" type="text/css" href="../style/test.css" />

 <div id="tabs-1">
<ul>
<li>Tab 1</li>
</ul>

<div id="tabs-2">

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

</div></code>```

Here's my CSS for the div scrollbar :

#tabs-2 { overflow-y:scroll; height:100%; }
```

When i'm using a fixed height value (like 400px), it works but I have a lot of pages with the same div but different height so this value will not works for every div.

I want to get rid of the browser scrollbar and only use a div scrollbar.

Is there any way to make a scrollbar that adapt dynamically for any div height?

答:
I mean to say like this:

body{
   font-size:0.8em;
   margin: 0px 0px 0px 10px;
   padding: 0px;
   color: #000;
   font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
   background-color: #ffffff;
   background: url(null) fixed #ffffff;
 }

h1{
  font-weight: bold;
  margin: 0px;
  font-size: 16px;
  color: #a1006b;
  text-align: left;
  font-variant: normal;
}

#tabs-1 {
  position: fixed;
  z-index:1;
  background-color: #fff;
  width: 100%;
}

.ui-widget-header{
  background:#ffffff;
}

#tabs-2 {
  position: relative;
  top: 60px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Test</title>
</head>
<body>

      <div id="tabs-1">
     <ul>
        <li>Tab 1</li>
     </ul>
     </div>

     <div id="tabs-2">
     <h1>Test</h1>
     <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
     <ul>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
     </ul></p>

     <h1>Test</h1>
     <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
     <ul>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
    </ul></p>

    <h1>Test</h1>
    <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
    <ul>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       </ul></p>

       <h1>Test</h1>
       <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
       <ul>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
      </ul></p>

      <h1>Test</h1>
      <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
      <ul>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
     </ul></p>

     <h1>Test</h1>
     <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
     <ul>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
     </ul></p>

     <h1>Test</h1>
     <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
     <ul>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
    </ul></p>
    </div>

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

Body:
I have a div and I want to attach a scrollbar to it to keep the menu fixed (Tab1 here).

BODY
{
 font-size:0.8em;
    MARGIN: 0px 0px 0px 10px;
 COLOR: #000;
    FONT-FAMILY: Tahoma, Verdana, Arial, Helvetica, sans-serif;
    BACKGROUND-COLOR: #ffffff;
 background: url(null) fixed #ffffff;
}

H1
{
    MARGIN-TOP: 20px;
    FONT-WEIGHT: bold;
    FONT-SIZE: 16px;
    MARGIN-BOTTOM: 10px;
 COLOR: #A1006B;
    TEXT-ALIGN: left;
    FONT-VARIANT: normal
}

#tabs-1 {
font-size: 14px;}
.ui-widget-header{
background:#ffff;
}

#tabs-2 {
overflow-y:scroll;
height:100%;
}

<title>Test</title>

<link rel="stylesheet" type="text/css" href="../style/test.css" />

Tab 1

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Here's my CSS for the div scrollbar :

#tabs-2 { overflow-y:scroll; height:100%; }

When i'm using a fixed height value (like 400px), it works but I have a lot of pages with the same div but different height so this value will not works for every div.

I want to get rid of the browser scrollbar and only use a div scrollbar.

Is there any way to make a scrollbar that adapt dynamically for any div height?

Body:
I mean to say like this:

body{
   font-size:0.8em;
   margin: 0px 0px 0px 10px;
   padding: 0px;
   color: #000;
   font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
   background-color: #ffffff;
   background: url(null) fixed #ffffff;
 }

h1{
  font-weight: bold;
  margin: 0px;
  font-size: 16px;
  color: #a1006b;
  text-align: left;
  font-variant: normal;
}

#tabs-1 {
  position: fixed;
  z-index:1;
  background-color: #fff;
  width: 100%;
}

.ui-widget-header{
  background:#ffffff;
}

#tabs-2 {
  position: relative;
  top: 60px;
}

<html>
<head>
<title>Test</title>
</head>
<body>

      <div id="tabs-1">
     <ul>
        <li><a href="#tabs-2">Tab 1</a></li>
     </ul>
     </div>

     <div id="tabs-2">
     <h1>Test</h1>
     <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
     <ul>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
     </ul></p>

     <h1>Test</h1>
     <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
     <ul>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
    </ul></p>

    <h1>Test</h1>
    <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
    <ul>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
       </ul></p>

       <h1>Test</h1>
       <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
       <ul>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
          <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
      </ul></p>

      <h1>Test</h1>
      <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
      <ul>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
         <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
     </ul></p>

     <h1>Test</h1>
     <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
     <ul>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
     </ul></p>

     <h1>Test</h1>
     <p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
     <ul>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
        <li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
    </ul></p>
    </div>

</body>
</html>


问:
get latest record from table using postgresql
I have table employee as below,

```<code>id|name1|number
--|-----|------
01|test |100
02|test1|101
03|test2|102
</code>```

I am using jpa with eclipselink implementation and database is postgresql.
Here my requirement is I want to get latest record using select query. Can anyone suggest the query to get latest record always.
Thanks,

答:
You must add updatedDate field in the entity class.

So I'll like to know if is there a SIMPLE way around my problem, meaning having @PrePersist or @PreUpdate or even other workaround to set the lastModified field still using session

Entity Class:

```<code>@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "number")
    private Long number;

    @Column(name = "updated_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updatedAt;

    // getter setter

    @PreUpdate
    public void setChangeDate() {
       this.updatedAt = new Date();
    }

}
</code>```

You can use JPA query. This exam:

```<code>String query = "SELECT emp FROM Employee emp order by updatedAt desc limit 1 ";
</code>```

Body:
I have table employee as below,

id|name1|number
--|-----|------
01|test |100
02|test1|101
03|test2|102

I am using jpa with eclipselink implementation and database is postgresql.
Here my requirement is I want to get latest record using select query. Can anyone suggest the query to get latest record always.
Thanks,

Body:
You must add updatedDate field in the entity class.

So I'll like to know if is there a SIMPLE way around my problem, meaning having @PrePersist or @PreUpdate or even other workaround to set the lastModified field still using session

Entity Class:

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "number")
    private Long number;

    @Column(name = "updated_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updatedAt;

    // getter setter

    @PreUpdate
    public void setChangeDate() {
       this.updatedAt = new Date();
    }

}

You can use JPA query. This exam:

String query = "SELECT emp FROM Employee emp order by updatedAt desc limit 1 ";


问:
How to populate documents with unlimited nested levels using mongoose
I'm designing a web application that manages organizational structure for parent and child companies. There are two types of companies: 1- Main company, 2 -Subsidiary company.The company can belong only to one company but can have a few child companies. My mongoose Schema looks like this:

```<code>var companySchema = new mongoose.Schema({
    companyName: {
        type: String,
        required: true
    },
    estimatedAnnualEarnings: {
        type: Number,
        required: true
    },
    companyChildren: [{type: mongoose.Schema.Types.ObjectId, ref: 'Company'}],
    companyType: {type: String, enum: ['Main', 'Subsidiary']}
})

module.exports = mongoose.model('Company', companySchema);
</code>```

I store all my companies in one collection and each company has an array with references to its child companies. Then I want to display all companies as a tree(on client side). I want query all Main companies that populates their children and children populate their children and so on,with unlimited nesting level. How can I do that? Or maybe you know better approach. Also I need ability to view,add,edit,delete any company.

Now I have this:

```<code>router.get('/companies', function(req, res) {
    Company.find({companyType: 'Main'}).populate({path: 'companyChildren'}).exec(function(err, list) {
        if(err) {
            console.log(err);
        } else {
            res.send(list);
        }
    })
});
</code>```

But it populates only one nested level.
I appreciate any help

答:
You can do this in latest Mongoose releases. No plugins required:

```<code>const async = require('async'),
      mongoose = require('mongoose'),
      Schema = mongoose.Schema;

const uri = 'mongodb://localhost/test',
      options = { use: MongoClient };

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

function autoPopulateSubs(next) {
  this.populate('subs');
  next();
}

const companySchema = new Schema({
  name: String,
  subs: [{ type: Schema.Types.ObjectId, ref: 'Company' }]
});

companySchema
  .pre('findOne', autoPopulateSubs)
  .pre('find', autoPopulateSubs);

const Company = mongoose.model('Company', companySchema);

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

async.series(
  [
    (callback) => mongoose.connect(uri,options,callback),

    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    (callback) =>
      async.waterfall(
        [5,4,3,2,1].map( name =>
          ( name === 5 ) ?
            (callback) => Company.create({ name },callback) :
            (child,callback) =>
              Company.create({ name, subs: [child] },callback)
        ),
        callback
      ),

    (callback) =>
      Company.findOne({ name: 1 })
        .exec((err,company) => {
          if (err) callback(err);
          log(company);
          callback();
        })

  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
)
</code>```

Or a more modern Promise version with async/await:

```<code>const mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.set('debug',true);
mongoose.Promise = global.Promise;
const uri = 'mongodb://localhost/test',
      options = { useMongoClient: true };

const companySchema = new Schema({
  name: String,
  subs: [{ type: Schema.Types.ObjectId, ref: 'Company' }]
});

function autoPopulateSubs(next) {
  this.populate('subs');
  next();
}

companySchema
  .pre('findOne', autoPopulateSubs)
  .pre('find', autoPopulateSubs);

const Company = mongoose.model('Company', companySchema);

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

(async function() {

  try {
    const conn = await mongoose.connect(uri,options);

    // Clean data
    await Promise.all(
      Object.keys(conn.models).map(m => conn.models[m].remove({}))
    );

    // Create data
    await [5,4,3,2,1].reduce((acc,name) =>
      (name === 5) ? acc.then( () => Company.create({ name }) )
        : acc.then( child => Company.create({ name, subs: [child] }) ),
      Promise.resolve()
    );

    // Fetch and populate
    let company = await Company.findOne({ name: 1 });
    log(company);

  } catch(e) {
    console.error(e);
  } finally {
    mongoose.disconnect();
  }

})()
</code>```

Produces:

```<code>{
  "_id": "595f7a773b80d3114d236a8b",
  "name": "1",
  "__v": 0,
  "subs": [
    {
      "_id": "595f7a773b80d3114d236a8a",
      "name": "2",
      "__v": 0,
      "subs": [
        {
          "_id": "595f7a773b80d3114d236a89",
          "name": "3",
          "__v": 0,
          "subs": [
            {
              "_id": "595f7a773b80d3114d236a88",
              "name": "4",
              "__v": 0,
              "subs": [
                {
                  "_id": "595f7a773b80d3114d236a87",
                  "name": "5",
                  "__v": 0,
                  "subs": []
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}
</code>```

Note that the async parts are not actually required at all and are just here for setting up the data for demonstration. It's the .pre() hooks that allow this to actually happen as we "chain" each .populate() which actually calls either .find() or .findOne() under the hood to another .populate() call.

So this:

```<code>function autoPopulateSubs(next) {
  this.populate('subs');
  next();
}
</code>```

Is the part being invoked that is actually doing the work.

All done with "middleware hooks".

Data State

To make it clear, this is the data in the collection which is set up. It's just references pointing to each subsidiary in plain flat documents:

```<code>{
        "_id" : ObjectId("595f7a773b80d3114d236a87"),
        "name" : "5",
        "subs" : [ ],
        "__v" : 0
}
{
        "_id" : ObjectId("595f7a773b80d3114d236a88"),
        "name" : "4",
        "subs" : [
                ObjectId("595f7a773b80d3114d236a87")
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("595f7a773b80d3114d236a89"),
        "name" : "3",
        "subs" : [
                ObjectId("595f7a773b80d3114d236a88")
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("595f7a773b80d3114d236a8a"),
        "name" : "2",
        "subs" : [
                ObjectId("595f7a773b80d3114d236a89")
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("595f7a773b80d3114d236a8b"),
        "name" : "1",
        "subs" : [
                ObjectId("595f7a773b80d3114d236a8a")
        ],
        "__v" : 0
}
</code>```

Body:
I'm designing a web application that manages organizational structure for parent and child companies. There are two types of companies: 1- Main company, 2 -Subsidiary company.The company can belong only to one company but can have a few child companies. My mongoose Schema looks like this:

var companySchema = new mongoose.Schema({
    companyName: {
        type: String,
        required: true
    },
    estimatedAnnualEarnings: {
        type: Number,
        required: true
    },
    companyChildren: [{type: mongoose.Schema.Types.ObjectId, ref: 'Company'}],
    companyType: {type: String, enum: ['Main', 'Subsidiary']}
})

module.exports = mongoose.model('Company', companySchema);

I store all my companies in one collection and each company has an array with references to its child companies. Then I want to display all companies as a tree(on client side). I want query all Main companies that populates their children and children populate their children and so on,with unlimited nesting level. How can I do that? Or maybe you know better approach. Also I need ability to view,add,edit,delete any company.

Now I have this:

router.get('/companies', function(req, res) {
    Company.find({companyType: 'Main'}).populate({path: 'companyChildren'}).exec(function(err, list) {
        if(err) {
            console.log(err);
        } else {
            res.send(list);
        }
    })
});

But it populates only one nested level.
I appreciate any help

Body:
You can do this in latest Mongoose releases. No plugins required:

const async = require('async'),
      mongoose = require('mongoose'),
      Schema = mongoose.Schema;

const uri = 'mongodb://localhost/test',
      options = { use: MongoClient };

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

function autoPopulateSubs(next) {
  this.populate('subs');
  next();
}

const companySchema = new Schema({
  name: String,
  subs: [{ type: Schema.Types.ObjectId, ref: 'Company' }]
});

companySchema
  .pre('findOne', autoPopulateSubs)
  .pre('find', autoPopulateSubs);

const Company = mongoose.model('Company', companySchema);

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

async.series(
  [
    (callback) => mongoose.connect(uri,options,callback),

    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    (callback) =>
      async.waterfall(
        [5,4,3,2,1].map( name =>
          ( name === 5 ) ?
            (callback) => Company.create({ name },callback) :
            (child,callback) =>
              Company.create({ name, subs: [child] },callback)
        ),
        callback
      ),

    (callback) =>
      Company.findOne({ name: 1 })
        .exec((err,company) => {
          if (err) callback(err);
          log(company);
          callback();
        })

  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
)

Or a more modern Promise version with async/await:

const mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.set('debug',true);
mongoose.Promise = global.Promise;
const uri = 'mongodb://localhost/test',
      options = { useMongoClient: true };

const companySchema = new Schema({
  name: String,
  subs: [{ type: Schema.Types.ObjectId, ref: 'Company' }]
});

function autoPopulateSubs(next) {
  this.populate('subs');
  next();
}

companySchema
  .pre('findOne', autoPopulateSubs)
  .pre('find', autoPopulateSubs);

const Company = mongoose.model('Company', companySchema);

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

(async function() {

  try {
    const conn = await mongoose.connect(uri,options);

    // Clean data
    await Promise.all(
      Object.keys(conn.models).map(m => conn.models[m].remove({}))
    );

    // Create data
    await [5,4,3,2,1].reduce((acc,name) =>
      (name === 5) ? acc.then( () => Company.create({ name }) )
        : acc.then( child => Company.create({ name, subs: [child] }) ),
      Promise.resolve()
    );

    // Fetch and populate
    let company = await Company.findOne({ name: 1 });
    log(company);

  } catch(e) {
    console.error(e);
  } finally {
    mongoose.disconnect();
  }

})()

Produces:

{
  "_id": "595f7a773b80d3114d236a8b",
  "name": "1",
  "__v": 0,
  "subs": [
    {
      "_id": "595f7a773b80d3114d236a8a",
      "name": "2",
      "__v": 0,
      "subs": [
        {
          "_id": "595f7a773b80d3114d236a89",
          "name": "3",
          "__v": 0,
          "subs": [
            {
              "_id": "595f7a773b80d3114d236a88",
              "name": "4",
              "__v": 0,
              "subs": [
                {
                  "_id": "595f7a773b80d3114d236a87",
                  "name": "5",
                  "__v": 0,
                  "subs": []
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

Note that the async parts are not actually required at all and are just here for setting up the data for demonstration. It's the .pre() hooks that allow this to actually happen as we "chain" each .populate() which actually calls either .find() or .findOne() under the hood to another .populate() call.

So this:

function autoPopulateSubs(next) {
  this.populate('subs');
  next();
}

Is the part being invoked that is actually doing the work.

All done with "middleware hooks".

Data State

To make it clear, this is the data in the collection which is set up. It's just references pointing to each subsidiary in plain flat documents:

{
        "_id" : ObjectId("595f7a773b80d3114d236a87"),
        "name" : "5",
        "subs" : [ ],
        "__v" : 0
}
{
        "_id" : ObjectId("595f7a773b80d3114d236a88"),
        "name" : "4",
        "subs" : [
                ObjectId("595f7a773b80d3114d236a87")
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("595f7a773b80d3114d236a89"),
        "name" : "3",
        "subs" : [
                ObjectId("595f7a773b80d3114d236a88")
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("595f7a773b80d3114d236a8a"),
        "name" : "2",
        "subs" : [
                ObjectId("595f7a773b80d3114d236a89")
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("595f7a773b80d3114d236a8b"),
        "name" : "1",
        "subs" : [
                ObjectId("595f7a773b80d3114d236a8a")
        ],
        "__v" : 0
}


问:
Access helpers from mailer?
I have trying to access helper methods from a rails 3 mailer in order to access the current user for the session.

I put the helper :application in my mailer class, which seems to work, except the methods defined therein are not available to my mailer (i get undefined errors). Does anyone know how this is supposed to work?

Here's my class:

```<code>class CommentMailer < ActionMailer::Base
  default :from => "Andre Fournier <andre@gfournier.com>"

  helper :application
end
</code>```

Thanks,
Sean

答:
None of the *_path helpers are accessible by default inside of an email. It is necessary instead to use the *_url form of the wanted helper. So, for instance, instead of using user_path(@user) it is necessary to use user_url(@user).
See at Action Mailer basics.

Title: Access helpers from mailer?

Body:
I have trying to access helper methods from a rails 3 mailer in order to access the current user for the session.

I put the helper :application in my mailer class, which seems to work, except the methods defined therein are not available to my mailer (i get undefined errors). Does anyone know how this is supposed to work?

Here's my class:

class CommentMailer < ActionMailer::Base
  default :from => "Andre Fournier <andre@gfournier.com>"

  helper :application
end

Thanks,
Sean


问:
how to convert device model uboot driver to use it for older version uboot like uboot 2010
I am trying to use freescale dspi driver ,but its only available in recent ubooot releases and hence having a device model ,but i want to use it for uboot 2010 ,so how can convert a device model driver to use it.

Regards
Raghav

答: Really, it's not feasible to move all of the driver-model infrastructure back to something that old.  You're better off moving your board up to the modern version of U-Boot.</p>


问:
End loop with counter and condition
In Python I can implement a loop with step counter and a stop condition as a classical case of for loop :

```<code>for i in range(50):
    result = fun(i)
    print(i, result)
    if result == 0:
        break
</code>```

where fun(x) is some arbitrary function from integers to integers.

I always in doubts if that is the best way to code it (Pythonically, and in terms of readability and efficiency) or is it better to run it as a while loop:

```<code>i = 0
result = 1
while result != 0 and i < 50:
    result = fun(i)
    print(i, result)
    i += 1
</code>```

which approach is better? In particular - I'm concerned about the usage of break statement which doesn't feel right.

答:
Looking purely at the bytecode, While-loop got 30 lines and the for-loop got 26 lines.

In the end, don't really think it matters that much but I personally prefer the for-loop version as it's easier to read.

http://mergely.com/9P1cfnTr/

Code I used:

```<code>def fun(i):
    i = i + 1
    return i

def test1():
    i = 0
    result = 1
    while result != 0 and i < 50:
        result = fun(i)
        print(i, result)
        i += 1

def test2():
    for i in range(50):
        result = fun(i)
        print(i, result)
        if result == 0:
            break
</code>```

Title: End loop with counter and condition

Body:
In Python I can implement a loop with step counter and a stop condition as a classical case of for loop :

for i in range(50):
    result = fun(i)
    print(i, result)
    if result == 0:
        break

where fun(x) is some arbitrary function from integers to integers.

I always in doubts if that is the best way to code it (Pythonically, and in terms of readability and efficiency) or is it better to run it as a while loop:

i = 0
result = 1
while result != 0 and i < 50:
    result = fun(i)
    print(i, result)
    i += 1

which approach is better? In particular - I'm concerned about the usage of break statement which doesn't feel right.

Body:
Looking purely at the bytecode, While-loop got 30 lines and the for-loop got 26 lines.

In the end, don't really think it matters that much but I personally prefer the for-loop version as it's easier to read.

http://mergely.com/9P1cfnTr/

Code I used:

def fun(i):
    i = i + 1
    return i

def test1():
    i = 0
    result = 1
    while result != 0 and i < 50:
        result = fun(i)
        print(i, result)
        i += 1

def test2():
    for i in range(50):
        result = fun(i)
        print(i, result)
        if result == 0:
            break


问:
How to get frame of stream video link with Glide
in my android TV application, at start i want to show a frame of my each stream links. my current solution is using LoaderManager and the problem of this technique is to it's too slow(application crashed).

```<code>FFmpegMediaMetadataRetriever to load and set video stream link.
this.retriever = new FFmpegMediaMetadataRetriever();
Bitmap bitmap = null;
retriever.setDataSource(this.mSelectedStream.getStreamUrl());
bitmap = retriever.getFrameAtTime();
drawable = new BitmapDrawable(bitmap);
retriever.release();
</code>```

i found this thread that explain that glide can used to load image from video links.

```<code>BitmapPool bitmapPool = Glide.get(getApplicationContext()).getBitmapPool();
                int microSecond = 6000000;// 6th second as an example
                VideoBitmapDecoder videoBitmapDecoder = new VideoBitmapDecoder(microSecond);
                FileDescriptorBitmapDecoder fileDescriptorBitmapDecoder = new FileDescriptorBitmapDecoder(videoBitmapDecoder, bitmapPool, DecodeFormat.PREFER_ARGB_8888);
                Glide.with(getApplicationContext())
                        .load(yourUri)
                        .asBitmap()
                        .override(50,50)// Example
                        .videoDecoder(fileDescriptorBitmapDecoder)
                        .into(yourImageView);
</code>```

but when i used above code i get "cannot access from outside of package" error for VideoBitmapDecoder.

exmaple link = "http://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8"

any idea?
thanks

答:
I've used this snippet to get thumb nail out of video frames. Try it</p>

```<code> Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(media_url,
                MediaStore.Images.Thumbnails.MINI_KIND);
        BitmapDrawable BD = new BitmapDrawable(thumbnail);
        videoView.setBackgroundDrawable(BD);
</code>```

Body:
in my android TV application, at start i want to show a frame of my each stream links. my current solution is using LoaderManager and the problem of this technique is to it's too slow(application crashed).

FFmpegMediaMetadataRetriever to load and set video stream link.
this.retriever = new FFmpegMediaMetadataRetriever();
Bitmap bitmap = null;
retriever.setDataSource(this.mSelectedStream.getStreamUrl());
bitmap = retriever.getFrameAtTime();
drawable = new BitmapDrawable(bitmap);
retriever.release();

i found this thread that explain that glide can used to load image from video links.

BitmapPool bitmapPool = Glide.get(getApplicationContext()).getBitmapPool();
                int microSecond = 6000000;// 6th second as an example
                VideoBitmapDecoder videoBitmapDecoder = new VideoBitmapDecoder(microSecond);
                FileDescriptorBitmapDecoder fileDescriptorBitmapDecoder = new FileDescriptorBitmapDecoder(videoBitmapDecoder, bitmapPool, DecodeFormat.PREFER_ARGB_8888);
                Glide.with(getApplicationContext())
                        .load(yourUri)
                        .asBitmap()
                        .override(50,50)// Example
                        .videoDecoder(fileDescriptorBitmapDecoder)
                        .into(yourImageView);

but when i used above code i get "cannot access from outside of package" error for VideoBitmapDecoder.

exmaple link = "http://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8"

any idea?
thanks

Body:
I've used this snippet to get thumb nail out of video frames. Try it

 Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(media_url,
                MediaStore.Images.Thumbnails.MINI_KIND);
        BitmapDrawable BD = new BitmapDrawable(thumbnail);
        videoView.setBackgroundDrawable(BD);