问:
Calculate how often specific daytime is contained in time range
I have a time range starting with a start date and end date represented in milliseconds since 1970:

```<code>long start;
long end;
</code>```

And I want to know if and how often a specific daytime is contained in this range. So let's say the daytime is 09.00 am DST - how often is it contained in the range.

Is there an easy and elegant way to calculate this in Java?

答:
java.time

The modern approach uses the java.time classes.

Convert your count-from-epoch numbers. An Instant is a point on the timeline in UTC with a resolution of nanoseconds.

```<code>Instant startInstant = Instant.ofEpochMilli( startLong ) ;
Instant stopInstant = Instant.ofEpochMilli( stopLong ) ;
</code>```

Adjust into your desired time zone.

Always use true time zone names structured as continent/region.

```<code>ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdtStart = instantStart.atZone( z ) ;
ZonedDateTime zdtStop = instantStop.atZone( z ) ;
</code>```

Represent your target time-of-day.

```<code>LocalTime lt = LocalTime.of( 9 , 0 ) ;
</code>```

Get a ZonedDateTime with your starting date and your target time.

```<code>ZonedDateTime zdtStartAtTargetTime = ZonedDateTime.of( zdtStart.toLocalDate() , lt , z ) ;
</code>```

Compare that to your interval’s start to see if you should count this starting date.

Do the same process for the last day.

The count the days between the start of the second day and first moment of the last day.

```<code>long days = ChronoUnit.DAYS.between( start , stop ) ;
</code>```

If they count, add your first day, and your last day.

Compare to the

Body:
I have a time range starting with a start date and end date represented in milliseconds since 1970:

long start;
long end;

And I want to know if and how often a specific daytime is contained in this range. So let's say the daytime is 09.00 am DST - how often is it contained in the range.

Is there an easy and elegant way to calculate this in Java?

Body:
java.time

The modern approach uses the java.time classes.

Convert your count-from-epoch numbers. An Instant is a point on the timeline in UTC with a resolution of nanoseconds.

Instant startInstant = Instant.ofEpochMilli( startLong ) ;
Instant stopInstant = Instant.ofEpochMilli( stopLong ) ;

Adjust into your desired time zone.

Always use true time zone names structured as continent/region.

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdtStart = instantStart.atZone( z ) ;
ZonedDateTime zdtStop = instantStop.atZone( z ) ;

Represent your target time-of-day.

LocalTime lt = LocalTime.of( 9 , 0 ) ;

Get a ZonedDateTime with your starting date and your target time.

ZonedDateTime zdtStartAtTargetTime = ZonedDateTime.of( zdtStart.toLocalDate() , lt , z ) ;

Compare that to your interval’s start to see if you should count this starting date.

Do the same process for the last day.

The count the days between the start of the second day and first moment of the last day.

long days = ChronoUnit.DAYS.between( start , stop ) ;

If they count, add your first day, and your last day.

Compare to the


来源: stackexchange

问:
JQuery | Revealing a block of text on click. Need div to be above img, z-index does not work
I have a vertical line of images of planets. What I am trying to do is when the row, defined by a div tag, is clicked upon a block of text will appear. I have it somewhat working. Currently it will recognize I am clicking in the div, but only if I'm not on top of the img tag. However, I've set the z-index lower than the div.

What I have so far:

HTML

```<code><article id="planets" class="article articleTwo">
    <div id="sun" class="off" onclick="planetClick()">
         <img src="images/sun.png" alt="The Sun"/>
    </div>
    <div id="mercury" class="off" onclick="planetClick()">
         <img src="images/mercury.png" alt="Mercury"/>
    </div>
    <div id="venus" class="off" onclick="planetClick()">
        <img src="images/venus.png" alt="Venus"/>
    </div>
    <div id="earth" class="off" onclick="planetClick()">
        <img src="images/earth.png" alt="Earth"/>
    </div>
    <div id="mars" class="off" onclick="planetClick()">
        <img src="images/mars.png" alt="Mars"/>
    </div>
    <div id="jupiter" class="off" onclick="planetClick()">
        <img src="images/jupiter.png" alt="Jupiter"/>
    </div>
    <div id="saturn" class="off" onclick="planetClick()">
        <img src="images/saturn.png" alt="Saturn"/>
    </div>
    <div id="uranus" class="off" onclick="planetClick()">
        <img src="images/uranus.png" alt="Uranus"/>
    </div>
    <div id="neptune" class="off" onclick="planetClick()">
        <img src="images/neptune.png" alt="Neptune"/>
    </div>
</article>
</code>```

CSS

```<code>article.articleTwo img {
    clear: right;
    float: right;
    border-left: 2px solid #000000;
    z-index: -2;
}

article.articleTwo div {
    overflow: auto;
}

.off {
    background-color: black;
    transition: background-color .4s ease;
}

.hover {
    background-color: transparent;
    transition: background-color .4s ease;
}
</code>```

JavaScript

```<code>function planetClick() {
    if ($(event.target).not("img").hasClass("hover")) {
        $(event.target).not("img").removeClass("hover");
        $(event.target).not("img").addClass("off");
    }
    else {
     $(event.target).not("img").addClass("hover");
        $(event.target).not("img").removeClass("off");
    };
};
</code>```

答:
It is hard to understand the problem since the code is hard to test. But the z-index won't work since the img is inside the div so they are on a different layer. I only can imagine that the div is maybe smaller then the image inside. You could try to change overflow auto to hidden.

```<code>article.articleTwo div {
    overflow: hidden;
}
</code>```

I would also change my setup a little bit. Since your element can only be "hover" or "off" and they all start with "off" i don't think you need it.

```<code><article id="planets" class="article articleTwo">
    <div id="sun">
         <img src="images/sun.png" alt="The Sun"/>
    </div>
    <div id="mercury">
         <img src="images/mercury.png" alt="Mercury"/>
    </div>
    <div id="venus">
        <img src="images/venus.png" alt="Venus"/>
    </div>
    <div id="earth">
        <img src="images/earth.png" alt="Earth"/>
    </div>
    <div id="mars">
        <img src="images/mars.png" alt="Mars"/>
    </div>
    <div id="jupiter">
        <img src="images/jupiter.png" alt="Jupiter"/>
    </div>
    <div id="saturn">
        <img src="images/saturn.png" alt="Saturn"/>
    </div>
    <div id="uranus">
        <img src="images/uranus.png" alt="Uranus"/>
    </div>
    <div id="neptune">
        <img src="images/neptune.png" alt="Neptune"/>
    </div>
</article>
</code>```

CSS

```<code>article.articleTwo img {
    clear: right;
    float: right;
    border-left: 2px solid #000000;
    z-index: -2;
}

article.articleTwo div {
    overflow: hidden;
    background-color: black;
    transition: background-color .4s ease;
}

article.articleTwo div.hover {
    background-color: transparent;
}
</code>```

JS

```<code>$(".articleTwo > div").click(function(){$(this).toggleClass("hover");});
</code>```

I think this will do the same but looks a bit more easy.

ContentLicense: CC BY-SA 3.0

Body:
I have a vertical line of images of planets. What I am trying to do is when the row, defined by a div tag, is clicked upon a block of text will appear. I have it somewhat working. Currently it will recognize I am clicking in the div, but only if I'm not on top of the img tag. However, I've set the z-index lower than the div.

What I have so far:

HTML

CSS

article.articleTwo img {
    clear: right;
    float: right;
    border-left: 2px solid #000000;
    z-index: -2;
}

article.articleTwo div {
    overflow: auto;
}

.off {
    background-color: black;
    transition: background-color .4s ease;
}

.hover {
    background-color: transparent;
    transition: background-color .4s ease;
}

JavaScript

function planetClick() {
    if ($(event.target).not("img").hasClass("hover")) {
        $(event.target).not("img").removeClass("hover");
        $(event.target).not("img").addClass("off");
    }
    else {
     $(event.target).not("img").addClass("hover");
        $(event.target).not("img").removeClass("off");
    };
};

Body:
It is hard to understand the problem since the code is hard to test. But the z-index won't work since the img is inside the div so they are on a different layer. I only can imagine that the div is maybe smaller then the image inside. You could try to change overflow auto to hidden.

article.articleTwo div {
    overflow: hidden;
}

I would also change my setup a little bit. Since your element can only be "hover" or "off" and they all start with "off" i don't think you need it.

<article id="planets" class="article articleTwo">
    <div id="sun">
         <img src="images/sun.png" alt="The Sun"/>
    </div>
    <div id="mercury">
         <img src="images/mercury.png" alt="Mercury"/>
    </div>
    <div id="venus">
        <img src="images/venus.png" alt="Venus"/>
    </div>
    <div id="earth">
        <img src="images/earth.png" alt="Earth"/>
    </div>
    <div id="mars">
        <img src="images/mars.png" alt="Mars"/>
    </div>
    <div id="jupiter">
        <img src="images/jupiter.png" alt="Jupiter"/>
    </div>
    <div id="saturn">
        <img src="images/saturn.png" alt="Saturn"/>
    </div>
    <div id="uranus">
        <img src="images/uranus.png" alt="Uranus"/>
    </div>
    <div id="neptune">
        <img src="images/neptune.png" alt="Neptune"/>
    </div>
</article>

CSS

article.articleTwo img {
    clear: right;
    float: right;
    border-left: 2px solid #000000;
    z-index: -2;
}

article.articleTwo div {
    overflow: hidden;
    background-color: black;
    transition: background-color .4s ease;
}

article.articleTwo div.hover {
    background-color: transparent;
}

JS

$(".articleTwo > div").click(function(){$(this).toggleClass("hover");});

I think this will do the same but looks a bit more easy.


问:
Apple Enterprise app signing
How long the enterprise-signed ipa can be install on iOS devices?
A company which have enterprise developer account signed my app and charge me an amount. They said that this app can be installed on devices forever. Is this true or the app has a limited time for installing?</p>

答:
Actually, it is some kind of forever.
Since every time users open the app, it will check the signed file.
While the company‘s enterprise developer account is valid, your app can be installed. If the sign certificate revoked by the Apple, your app can't be installed anymore.</p>

Title: Apple Enterprise app signing


问:
Squeak Smalltalk -"Print specific integers" Error message, how to improve and why?
what I want is:
From integers 1 to 130, I want to print some specific integers already given in an array.
They are: 2 32 44 67 89 111 123 which are stored in small-to-big order.

Here's my codes:

```<code>|a n myArray|

myArray := #(2 32 44 67 89 111 123).

n := 1.
a := myArray at: n.

1 to: 130 do: [:i|
        i = a
        ifTrue: [
                Transcript show: i; cr.
                n := n + 1.
                a := myArray at: n.
                ].
        ].
</code>```

The output is very good except for an Error Message.

By my current level, I have no idea why that Error Message appears.

Q1: Why  Error Message appears ?

Q2: How can I improve that?

Update:

I found another way to solve this issue:

```<code>|myArray|

myArray := #(2 32 44 67 89 111 123).

n := 1.
a := myArray at: n.

1 to: 130 do: [:i|
    i = a
    ifTrue: [
        Transcript show: i; cr.
        n := n +1.

        n = 8
        ifTrue: [n := n - 1].

         a := myArray at: n.
        ].
    ].
</code>```

Looks ugly though.

Updated again:

```<code>|a n myArray|

myArray := #(2 32 44 67 89 111 123).

n := 1.
a := myArray at: n.

1 to: 130 do: [:i|
        i = a
        ifTrue: [
                Transcript show: i; cr.
                n := n + 1.

                (n = 8) ifTrue:  [^'Found it!'].

                a := myArray at: n.
                ].
        ].
</code>```

答:
If you click on the debug button, you will gain access to a debugger that may help you understand what is going on.

The list in the window you are showing is the stack of execution. The snippet that you are trying to execute is marked as UndefinedObject>>DoIt. Click on it, and you'll see where your code stopped - while executing:

```<code>myArray at: n
</code>```

In the debugger there are inspectors, you'll see that n = 8 if you click on n, then if you inspect myArray, you'll see that it has only 7 elements. You are thus trying to access to myArray with a subscript (an index) which is out of the Array bounds, as the error message tells...

From the debugger, you can restart the method and execute it step by step. But since it will fail at loop 123, it might be boring... You can also modify the code from within the debugger, for example use myArray := #(2 4 5). acceopt, and restart execution step by step to see if you can understand why the algorithm fails.

My suggestion is to try to think differently. You already have an Array containing the values you want to print (myArray). So if you manage to tell myArray to do what you want more directly, maybe by writing something like myArray do: [:element | ...]

Body:
what I want is:
From integers 1 to 130, I want to print some specific integers already given in an array.
They are: 2 32 44 67 89 111 123 which are stored in small-to-big order.

Here's my codes:

|a n myArray|

myArray := #(2 32 44 67 89 111 123).

n := 1.
a := myArray at: n.

1 to: 130 do: [:i|
        i = a
        ifTrue: [
                Transcript show: i; cr.
                n := n + 1.
                a := myArray at: n.
                ].
        ].

The output is very good except for an Error Message.

By my current level, I have no idea why that Error Message appears.

Q1: Why  Error Message appears ?

Q2: How can I improve that?

Update:

I found another way to solve this issue:

|myArray|

myArray := #(2 32 44 67 89 111 123).

n := 1.
a := myArray at: n.

1 to: 130 do: [:i|
    i = a
    ifTrue: [
        Transcript show: i; cr.
        n := n +1.

        n = 8
        ifTrue: [n := n - 1].

         a := myArray at: n.
        ].
    ].

Looks ugly though.

Updated again:

|a n myArray|

myArray := #(2 32 44 67 89 111 123).

n := 1.
a := myArray at: n.

1 to: 130 do: [:i|
        i = a
        ifTrue: [
                Transcript show: i; cr.
                n := n + 1.

                (n = 8) ifTrue:  [^'Found it!'].

                a := myArray at: n.
                ].
        ].

Body:
If you click on the debug button, you will gain access to a debugger that may help you understand what is going on.

The list in the window you are showing is the stack of execution. The snippet that you are trying to execute is marked as UndefinedObject>>DoIt. Click on it, and you'll see where your code stopped - while executing:

myArray at: n

In the debugger there are inspectors, you'll see that n = 8 if you click on n, then if you inspect myArray, you'll see that it has only 7 elements. You are thus trying to access to myArray with a subscript (an index) which is out of the Array bounds, as the error message tells...

From the debugger, you can restart the method and execute it step by step. But since it will fail at loop 123, it might be boring... You can also modify the code from within the debugger, for example use myArray := #(2 4 5). acceopt, and restart execution step by step to see if you can understand why the algorithm fails.

My suggestion is to try to think differently. You already have an Array containing the values you want to print (myArray). So if you manage to tell myArray to do what you want more directly, maybe by writing something like myArray do: [:element | ...]


问:
Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error
I am trying to run the following code in android

```<code>URLConnection l_connection = null;
// Create connection
uzip=new UnZipData(mContext);
l_url = new URL(serverurl);

if ("https".equals(l_url.getProtocol())) {
    System.out.println("<<<<<<<<<<<<< Before TLS >>>>>>>>>>>>");
    sslcontext = SSLContext.getInstance("TLS");
    System.out.println("<<<<<<<<<<<<< After TLS >>>>>>>>>>>>");
    sslcontext.init(null,
            new TrustManager[] { new CustomTrustManager()},
            new java.security.SecureRandom());
    HttpsURLConnection
            .setDefaultHostnameVerifier(new CustomHostnameVerifier());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext
            .getSocketFactory());

    l_connection = (HttpsURLConnection) l_url.openConnection();
    ((HttpsURLConnection) l_connection).setRequestMethod("POST");
} else {
    l_connection = (HttpURLConnection) l_url.openConnection();
    ((HttpURLConnection) l_connection).setRequestMethod("POST");
}
/*System.setProperty("http.agent", "Android_Phone");*/

l_connection.setConnectTimeout(10000);
l_connection.setRequestProperty("Content-Language", "en-US");
l_connection.setUseCaches(false);
l_connection.setDoInput(true);
l_connection.setDoOutput(true);
System.out.println("<<<<<<<<<<<<< Before Connection >>>>>>>>>>>>");
l_connection.connect();
</code>```

On l_connection.connect(), it is giving this SSLhandshakeException. Sometimes it works, but most of the time it gives the exception. It is only happening on Android 4.0 emulator. I tested it on Android 4.4 and 5.0, it works fine. What could be the cause?

Stack trace:

04-28 15:51:13.143: W/System.err(2915): javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x870c918: Failure in SSL library, usually a protocol error
04-28 15:51:13.143: W/System.err(2915): error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:658 0xb7c393a1:0x00000000)
04-28 15:51:13.143: W/System.err(2915):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:460)
04-28 15:51:13.143: W/System.err(2915):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:257)
04-28 15:51:13.143: W/System.err(2915):     at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:210)
04-28 15:51:13.143: W/System.err(2915):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:477)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:441)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164)
04-28 15:51:13.153: W/System.err(2915):     at com.ofss.fcdb.mobile.android.rms.helpers.NetworkConnector.getConnection(NetworkConnector.java:170)
04-28 15:51:13.153: W/System.err(2915):     at com.ofss.fcdb.mobile.android.rms.util.InitiateRMS$2.run(InitiateRMS.java:221)
04-28 15:51:13.153: W/System.err(2915):     at java.lang.Thread.run(Thread.java:856)
04-28 15:51:13.153: W/System.err(2915): Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x870c918: Failure in SSL library, usually a protocol error
04-28 15:51:13.153: W/System.err(2915): error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:658 0xb7c393a1:0x00000000)
04-28 15:51:13.153: W/System.err(2915):     at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
04-28 15:51:13.153: W/System.err(2915):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:410)
04-28 15:51:13.153: W/System.err(2915):     ... 11 more
04-28 16:42:44.139: W/ResourceType(3140): No package identifier when getting value for resource number 0x00000000
```

答:
I solved problem by this :
NoSSLv3SocketFactory.java

```<code>import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class NoSSLv3SocketFactory extends SSLSocketFactory {
    private final SSLSocketFactory delegate;

    public NoSSLv3SocketFactory() {
        this.delegate = HttpsURLConnection.getDefaultSSLSocketFactory();
    }

    public NoSSLv3SocketFactory(SSLSocketFactory delegate) {
        this.delegate = delegate;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    private Socket makeSocketSafe(Socket socket) {
        if (socket instanceof SSLSocket) {
            socket = new NoSSLv3SSLSocket((SSLSocket) socket);
        }
        return socket;
    }

    @Override
    public Socket createSocket(Socket s, String host, int port,
            boolean autoClose) throws IOException {
        return makeSocketSafe(delegate.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException {
        return makeSocketSafe(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost,
            int localPort) throws IOException {
        return makeSocketSafe(delegate.createSocket(host, port, localHost,
                localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return makeSocketSafe(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port,
            InetAddress localAddress, int localPort) throws IOException {
        return makeSocketSafe(delegate.createSocket(address, port,
                localAddress, localPort));
    }

    private class NoSSLv3SSLSocket extends DelegateSSLSocket {

        private NoSSLv3SSLSocket(SSLSocket delegate) {
            super(delegate);

        }

        @Override
        public void setEnabledProtocols(String[] protocols) {
            if (protocols != null && protocols.length == 1
                    && "SSLv3".equals(protocols[0])) {

                List<String> enabledProtocols = new ArrayList<String>(
                        Arrays.asList(delegate.getEnabledProtocols()));
                if (enabledProtocols.size() > 1) {
                    enabledProtocols.remove("SSLv3");
                    System.out.println("Removed SSLv3 from enabled protocols");
                } else {
                    System.out.println("SSL stuck with protocol available for "
                            + String.valueOf(enabledProtocols));
                }
                protocols = enabledProtocols
                        .toArray(new String[enabledProtocols.size()]);
            }

//          super.setEnabledProtocols(protocols);
            super.setEnabledProtocols(new String[]{"TLSv1.2"});
        }
    }

    public class DelegateSSLSocket extends SSLSocket {

        protected final SSLSocket delegate;

        DelegateSSLSocket(SSLSocket delegate) {
            this.delegate = delegate;
        }

        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }

        @Override
        public String[] getEnabledCipherSuites() {
            return delegate.getEnabledCipherSuites();
        }

        @Override
        public void setEnabledCipherSuites(String[] suites) {
            delegate.setEnabledCipherSuites(suites);
        }

        @Override
        public String[] getSupportedProtocols() {
            return delegate.getSupportedProtocols();
        }

        @Override
        public String[] getEnabledProtocols() {
            return delegate.getEnabledProtocols();
        }

        @Override
        public void setEnabledProtocols(String[] protocols) {
            delegate.setEnabledProtocols(protocols);
        }

        @Override
        public SSLSession getSession() {
            return delegate.getSession();
        }

        @Override
        public void addHandshakeCompletedListener(
                HandshakeCompletedListener listener) {
            delegate.addHandshakeCompletedListener(listener);
        }

        @Override
        public void removeHandshakeCompletedListener(
                HandshakeCompletedListener listener) {
            delegate.removeHandshakeCompletedListener(listener);
        }

        @Override
        public void startHandshake() throws IOException {
            delegate.startHandshake();
        }

        @Override
        public void setUseClientMode(boolean mode) {
            delegate.setUseClientMode(mode);
        }

        @Override
        public boolean getUseClientMode() {
            return delegate.getUseClientMode();
        }

        @Override
        public void setNeedClientAuth(boolean need) {
            delegate.setNeedClientAuth(need);
        }

        @Override
        public void setWantClientAuth(boolean want) {
            delegate.setWantClientAuth(want);
        }

        @Override
        public boolean getNeedClientAuth() {
            return delegate.getNeedClientAuth();
        }

        @Override
        public boolean getWantClientAuth() {
            return delegate.getWantClientAuth();
        }

        @Override
        public void setEnableSessionCreation(boolean flag) {
            delegate.setEnableSessionCreation(flag);
        }

        @Override
        public boolean getEnableSessionCreation() {
            return delegate.getEnableSessionCreation();
        }

        @Override
        public void bind(SocketAddress localAddr) throws IOException {
            delegate.bind(localAddr);
        }

        @Override
        public synchronized void close() throws IOException {
            delegate.close();
        }

        @Override
        public void connect(SocketAddress remoteAddr) throws IOException {
            delegate.connect(remoteAddr);
        }

        @Override
        public void connect(SocketAddress remoteAddr, int timeout)
                throws IOException {
            delegate.connect(remoteAddr, timeout);
        }

        @Override
        public SocketChannel getChannel() {
            return delegate.getChannel();
        }

        @Override
        public InetAddress getInetAddress() {
            return delegate.getInetAddress();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return delegate.getInputStream();
        }

        @Override
        public boolean getKeepAlive() throws SocketException {
            return delegate.getKeepAlive();
        }

        @Override
        public InetAddress getLocalAddress() {
            return delegate.getLocalAddress();
        }

        @Override
        public int getLocalPort() {
            return delegate.getLocalPort();
        }

        @Override
        public SocketAddress getLocalSocketAddress() {
            return delegate.getLocalSocketAddress();
        }

        @Override
        public boolean getOOBInline() throws SocketException {
            return delegate.getOOBInline();
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            return delegate.getOutputStream();
        }

        @Override
        public int getPort() {
            return delegate.getPort();
        }

        @Override
        public synchronized int getReceiveBufferSize() throws SocketException {
            return delegate.getReceiveBufferSize();
        }

        @Override
        public SocketAddress getRemoteSocketAddress() {
            return delegate.getRemoteSocketAddress();
        }

        @Override
        public boolean getReuseAddress() throws SocketException {
            return delegate.getReuseAddress();
        }

        @Override
        public synchronized int getSendBufferSize() throws SocketException {
            return delegate.getSendBufferSize();
        }

        @Override
        public int getSoLinger() throws SocketException {
            return delegate.getSoLinger();
        }

        @Override
        public synchronized int getSoTimeout() throws SocketException {
            return delegate.getSoTimeout();
        }

        @Override
        public boolean getTcpNoDelay() throws SocketException {
            return delegate.getTcpNoDelay();
        }

        @Override
        public int getTrafficClass() throws SocketException {
            return delegate.getTrafficClass();
        }

        @Override
        public boolean isBound() {
            return delegate.isBound();
        }

        @Override
        public boolean isClosed() {
            return delegate.isClosed();
        }

        @Override
        public boolean isConnected() {
            return delegate.isConnected();
        }

        @Override
        public boolean isInputShutdown() {
            return delegate.isInputShutdown();
        }

        @Override
        public boolean isOutputShutdown() {
            return delegate.isOutputShutdown();
        }

        @Override
        public void sendUrgentData(int value) throws IOException {
            delegate.sendUrgentData(value);
        }

        @Override
        public void setKeepAlive(boolean keepAlive) throws SocketException {
            delegate.setKeepAlive(keepAlive);
        }

        @Override
        public void setOOBInline(boolean oobinline) throws SocketException {
            delegate.setOOBInline(oobinline);
        }

        @Override
        public void setPerformancePreferences(int connectionTime, int latency,
                int bandwidth) {
            delegate.setPerformancePreferences(connectionTime, latency,
                    bandwidth);
        }

        @Override
        public synchronized void setReceiveBufferSize(int size)
                throws SocketException {
            delegate.setReceiveBufferSize(size);
        }

        @Override
        public void setReuseAddress(boolean reuse) throws SocketException {
            delegate.setReuseAddress(reuse);
        }

        @Override
        public synchronized void setSendBufferSize(int size)
                throws SocketException {
            delegate.setSendBufferSize(size);
        }

        @Override
        public void setSoLinger(boolean on, int timeout) throws SocketException {
            delegate.setSoLinger(on, timeout);
        }

        @Override
        public synchronized void setSoTimeout(int timeout)
                throws SocketException {
            delegate.setSoTimeout(timeout);
        }

        @Override
        public void setTcpNoDelay(boolean on) throws SocketException {
            delegate.setTcpNoDelay(on);
        }

        @Override
        public void setTrafficClass(int value) throws SocketException {
            delegate.setTrafficClass(value);
        }

        @Override
        public void shutdownInput() throws IOException {
            delegate.shutdownInput();
        }

        @Override
        public void shutdownOutput() throws IOException {
            delegate.shutdownOutput();
        }

        @Override
        public String toString() {
            return delegate.toString();
        }

        @Override
        public boolean equals(Object o) {
            return delegate.equals(o);
        }
    }
}
</code>```

Main class :

```<code>URL url = new URL("https://www.example.com/test.png");
URLConnection l_connection = null;
SSLContext sslcontext = SSLContext.getInstance("TLSv1.2");
sslcontext.init(null, null, null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run the following code in android

URLConnection l_connection = null;
// Create connection
uzip=new UnZipData(mContext);
l_url = new URL(serverurl);

if ("https".equals(l_url.getProtocol())) {
    System.out.println("<<<<<<<<<<<<< Before TLS >>>>>>>>>>>>");
    sslcontext = SSLContext.getInstance("TLS");
    System.out.println("<<<<<<<<<<<<< After TLS >>>>>>>>>>>>");
    sslcontext.init(null,
            new TrustManager[] { new CustomTrustManager()},
            new java.security.SecureRandom());
    HttpsURLConnection
            .setDefaultHostnameVerifier(new CustomHostnameVerifier());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext
            .getSocketFactory());

    l_connection = (HttpsURLConnection) l_url.openConnection();
    ((HttpsURLConnection) l_connection).setRequestMethod("POST");
} else {
    l_connection = (HttpURLConnection) l_url.openConnection();
    ((HttpURLConnection) l_connection).setRequestMethod("POST");
}
/*System.setProperty("http.agent", "Android_Phone");*/

l_connection.setConnectTimeout(10000);
l_connection.setRequestProperty("Content-Language", "en-US");
l_connection.setUseCaches(false);
l_connection.setDoInput(true);
l_connection.setDoOutput(true);
System.out.println("<<<<<<<<<<<<< Before Connection >>>>>>>>>>>>");
l_connection.connect();

On l_connection.connect(), it is giving this SSLhandshakeException. Sometimes it works, but most of the time it gives the exception. It is only happening on Android 4.0 emulator. I tested it on Android 4.4 and 5.0, it works fine. What could be the cause?

Stack trace:

04-28 15:51:13.143: W/System.err(2915): javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x870c918: Failure in SSL library, usually a protocol error
04-28 15:51:13.143: W/System.err(2915): error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:658 0xb7c393a1:0x00000000)
04-28 15:51:13.143: W/System.err(2915):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:460)
04-28 15:51:13.143: W/System.err(2915):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:257)
04-28 15:51:13.143: W/System.err(2915):     at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:210)
04-28 15:51:13.143: W/System.err(2915):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:477)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:441)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
04-28 15:51:13.153: W/System.err(2915):     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164)
04-28 15:51:13.153: W/System.err(2915):     at com.ofss.fcdb.mobile.android.rms.helpers.NetworkConnector.getConnection(NetworkConnector.java:170)
04-28 15:51:13.153: W/System.err(2915):     at com.ofss.fcdb.mobile.android.rms.util.InitiateRMS$2.run(InitiateRMS.java:221)
04-28 15:51:13.153: W/System.err(2915):     at java.lang.Thread.run(Thread.java:856)
04-28 15:51:13.153: W/System.err(2915): Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x870c918: Failure in SSL library, usually a protocol error
04-28 15:51:13.153: W/System.err(2915): error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:658 0xb7c393a1:0x00000000)
04-28 15:51:13.153: W/System.err(2915):     at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
04-28 15:51:13.153: W/System.err(2915):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:410)
04-28 15:51:13.153: W/System.err(2915):     ... 11 more
04-28 16:42:44.139: W/ResourceType(3140): No package identifier when getting value for resource number 0x00000000

Body:
I solved problem by this :
NoSSLv3SocketFactory.java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class NoSSLv3SocketFactory extends SSLSocketFactory {
    private final SSLSocketFactory delegate;

    public NoSSLv3SocketFactory() {
        this.delegate = HttpsURLConnection.getDefaultSSLSocketFactory();
    }

    public NoSSLv3SocketFactory(SSLSocketFactory delegate) {
        this.delegate = delegate;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    private Socket makeSocketSafe(Socket socket) {
        if (socket instanceof SSLSocket) {
            socket = new NoSSLv3SSLSocket((SSLSocket) socket);
        }
        return socket;
    }

    @Override
    public Socket createSocket(Socket s, String host, int port,
            boolean autoClose) throws IOException {
        return makeSocketSafe(delegate.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException {
        return makeSocketSafe(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost,
            int localPort) throws IOException {
        return makeSocketSafe(delegate.createSocket(host, port, localHost,
                localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return makeSocketSafe(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port,
            InetAddress localAddress, int localPort) throws IOException {
        return makeSocketSafe(delegate.createSocket(address, port,
                localAddress, localPort));
    }

    private class NoSSLv3SSLSocket extends DelegateSSLSocket {

        private NoSSLv3SSLSocket(SSLSocket delegate) {
            super(delegate);

        }

        @Override
        public void setEnabledProtocols(String[] protocols) {
            if (protocols != null && protocols.length == 1
                    && "SSLv3".equals(protocols[0])) {

                List<String> enabledProtocols = new ArrayList<String>(
                        Arrays.asList(delegate.getEnabledProtocols()));
                if (enabledProtocols.size() > 1) {
                    enabledProtocols.remove("SSLv3");
                    System.out.println("Removed SSLv3 from enabled protocols");
                } else {
                    System.out.println("SSL stuck with protocol available for "
                            + String.valueOf(enabledProtocols));
                }
                protocols = enabledProtocols
                        .toArray(new String[enabledProtocols.size()]);
            }

//          super.setEnabledProtocols(protocols);
            super.setEnabledProtocols(new String[]{"TLSv1.2"});
        }
    }

    public class DelegateSSLSocket extends SSLSocket {

        protected final SSLSocket delegate;

        DelegateSSLSocket(SSLSocket delegate) {
            this.delegate = delegate;
        }

        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }

        @Override
        public String[] getEnabledCipherSuites() {
            return delegate.getEnabledCipherSuites();
        }

        @Override
        public void setEnabledCipherSuites(String[] suites) {
            delegate.setEnabledCipherSuites(suites);
        }

        @Override
        public String[] getSupportedProtocols() {
            return delegate.getSupportedProtocols();
        }

        @Override
        public String[] getEnabledProtocols() {
            return delegate.getEnabledProtocols();
        }

        @Override
        public void setEnabledProtocols(String[] protocols) {
            delegate.setEnabledProtocols(protocols);
        }

        @Override
        public SSLSession getSession() {
            return delegate.getSession();
        }

        @Override
        public void addHandshakeCompletedListener(
                HandshakeCompletedListener listener) {
            delegate.addHandshakeCompletedListener(listener);
        }

        @Override
        public void removeHandshakeCompletedListener(
                HandshakeCompletedListener listener) {
            delegate.removeHandshakeCompletedListener(listener);
        }

        @Override
        public void startHandshake() throws IOException {
            delegate.startHandshake();
        }

        @Override
        public void setUseClientMode(boolean mode) {
            delegate.setUseClientMode(mode);
        }

        @Override
        public boolean getUseClientMode() {
            return delegate.getUseClientMode();
        }

        @Override
        public void setNeedClientAuth(boolean need) {
            delegate.setNeedClientAuth(need);
        }

        @Override
        public void setWantClientAuth(boolean want) {
            delegate.setWantClientAuth(want);
        }

        @Override
        public boolean getNeedClientAuth() {
            return delegate.getNeedClientAuth();
        }

        @Override
        public boolean getWantClientAuth() {
            return delegate.getWantClientAuth();
        }

        @Override
        public void setEnableSessionCreation(boolean flag) {
            delegate.setEnableSessionCreation(flag);
        }

        @Override
        public boolean getEnableSessionCreation() {
            return delegate.getEnableSessionCreation();
        }

        @Override
        public void bind(SocketAddress localAddr) throws IOException {
            delegate.bind(localAddr);
        }

        @Override
        public synchronized void close() throws IOException {
            delegate.close();
        }

        @Override
        public void connect(SocketAddress remoteAddr) throws IOException {
            delegate.connect(remoteAddr);
        }

        @Override
        public void connect(SocketAddress remoteAddr, int timeout)
                throws IOException {
            delegate.connect(remoteAddr, timeout);
        }

        @Override
        public SocketChannel getChannel() {
            return delegate.getChannel();
        }

        @Override
        public InetAddress getInetAddress() {
            return delegate.getInetAddress();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return delegate.getInputStream();
        }

        @Override
        public boolean getKeepAlive() throws SocketException {
            return delegate.getKeepAlive();
        }

        @Override
        public InetAddress getLocalAddress() {
            return delegate.getLocalAddress();
        }

        @Override
        public int getLocalPort() {
            return delegate.getLocalPort();
        }

        @Override
        public SocketAddress getLocalSocketAddress() {
            return delegate.getLocalSocketAddress();
        }

        @Override
        public boolean getOOBInline() throws SocketException {
            return delegate.getOOBInline();
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            return delegate.getOutputStream();
        }

        @Override
        public int getPort() {
            return delegate.getPort();
        }

        @Override
        public synchronized int getReceiveBufferSize() throws SocketException {
            return delegate.getReceiveBufferSize();
        }

        @Override
        public SocketAddress getRemoteSocketAddress() {
            return delegate.getRemoteSocketAddress();
        }

        @Override
        public boolean getReuseAddress() throws SocketException {
            return delegate.getReuseAddress();
        }

        @Override
        public synchronized int getSendBufferSize() throws SocketException {
            return delegate.getSendBufferSize();
        }

        @Override
        public int getSoLinger() throws SocketException {
            return delegate.getSoLinger();
        }

        @Override
        public synchronized int getSoTimeout() throws SocketException {
            return delegate.getSoTimeout();
        }

        @Override
        public boolean getTcpNoDelay() throws SocketException {
            return delegate.getTcpNoDelay();
        }

        @Override
        public int getTrafficClass() throws SocketException {
            return delegate.getTrafficClass();
        }

        @Override
        public boolean isBound() {
            return delegate.isBound();
        }

        @Override
        public boolean isClosed() {
            return delegate.isClosed();
        }

        @Override
        public boolean isConnected() {
            return delegate.isConnected();
        }

        @Override
        public boolean isInputShutdown() {
            return delegate.isInputShutdown();
        }

        @Override
        public boolean isOutputShutdown() {
            return delegate.isOutputShutdown();
        }

        @Override
        public void sendUrgentData(int value) throws IOException {
            delegate.sendUrgentData(value);
        }

        @Override
        public void setKeepAlive(boolean keepAlive) throws SocketException {
            delegate.setKeepAlive(keepAlive);
        }

        @Override
        public void setOOBInline(boolean oobinline) throws SocketException {
            delegate.setOOBInline(oobinline);
        }

        @Override
        public void setPerformancePreferences(int connectionTime, int latency,
                int bandwidth) {
            delegate.setPerformancePreferences(connectionTime, latency,
                    bandwidth);
        }

        @Override
        public synchronized void setReceiveBufferSize(int size)
                throws SocketException {
            delegate.setReceiveBufferSize(size);
        }

        @Override
        public void setReuseAddress(boolean reuse) throws SocketException {
            delegate.setReuseAddress(reuse);
        }

        @Override
        public synchronized void setSendBufferSize(int size)
                throws SocketException {
            delegate.setSendBufferSize(size);
        }

        @Override
        public void setSoLinger(boolean on, int timeout) throws SocketException {
            delegate.setSoLinger(on, timeout);
        }

        @Override
        public synchronized void setSoTimeout(int timeout)
                throws SocketException {
            delegate.setSoTimeout(timeout);
        }

        @Override
        public void setTcpNoDelay(boolean on) throws SocketException {
            delegate.setTcpNoDelay(on);
        }

        @Override
        public void setTrafficClass(int value) throws SocketException {
            delegate.setTrafficClass(value);
        }

        @Override
        public void shutdownInput() throws IOException {
            delegate.shutdownInput();
        }

        @Override
        public void shutdownOutput() throws IOException {
            delegate.shutdownOutput();
        }

        @Override
        public String toString() {
            return delegate.toString();
        }

        @Override
        public boolean equals(Object o) {
            return delegate.equals(o);
        }
    }
}

Main class :

URL url = new URL("https://www.example.com/test.png");
URLConnection l_connection = null;
SSLContext sslcontext = SSLContext.getInstance("TLSv1.2");
sslcontext.init(null, null, null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());


问:
S/4HANA Cloud SDK :com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces does not exist
The build is fails due to lack of resource: class com.sap.cloud.sdk.s4hana.datamodel.odata.services.BusinessPartnerService

Do we need to have/create this model classes in our project structure or will SDK take care of this static import?

Error after executing: mvn clean install

答:
Please use the latest SDK release in your project. Info here:
https://sap.github.io/cloud-s4-sdk-examples/release-notes/

This should resolve the error.

Best regards,
Akhil


问:
How to handle optional parameter for Class.new
I create a dynamic class using the Class.new method. But sometimes I call the method with a parameter to create an inherited class - sometimes without.

Option 1:

```<code>newclass = Class.new do
  ...
end
</code>```

Option 2:

```<code>newClass = Class.new(p) do
  ...
end
</code>```

The body of the new class is identical. But I cannot call Class.new(p) with undefined p. So I have to create an if statement and then either call Class.new with parameter or without which means I have the duplicate the code for creating the class which is not ideal since every change in my code I have to make twice. Any way how I can get around this?

答:
You can just abstract the Class.new call and leave the block in one place. Something like this:

```<code>def create_me_a_class(superklass = Object, &block)
  Class.new(superklass, &block)
end

newclass = create_me_a_class(p) do
  def my_method
    # whatever
  end
end
</code>```

Body:
I create a dynamic class using the Class.new method. But sometimes I call the method with a parameter to create an inherited class - sometimes without.

Option 1:

newclass = Class.new do
  ...
end

Option 2:

newClass = Class.new(p) do
  ...
end

The body of the new class is identical. But I cannot call Class.new(p) with undefined p. So I have to create an if statement and then either call Class.new with parameter or without which means I have the duplicate the code for creating the class which is not ideal since every change in my code I have to make twice. Any way how I can get around this?

Body:
You can just abstract the Class.new call and leave the block in one place. Something like this:

def create_me_a_class(superklass = Object, &block)
  Class.new(superklass, &block)
end

newclass = create_me_a_class(p) do
  def my_method
    # whatever
  end
end


问:
Disable Submit button on selection from DropDownListFor
I am working on this code when the submit button will be enabled only when user selects values from a DropDownListFor.

```<code>      @Html.DropDownListFor(m => m.Year, Model.YearList, "--Select Year--", new { @class = "form-control",id = "Year" })
      @Html.ValidationMessageFor(m => m.Year)

 <input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" />
</code>```

js code:

```<code>   $("#Year").change(function () {
        if ($('#Year').val()!="--Select Year--")
            $('.submit').prop("disabled", false);
        else
            $('.submit').prop("disabled", true);
    });
</code>```

No error message just the submit button is always enabled. Any help?

答:
Update your code cause selector use class but no submit class so you id selector in your javascript code

$("#Year").change(function () {
    if ($('#Year').val()) {
    $('.submit').prop("disabled", false);
}
else {
    $('.submit').prop("disabled", true);
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="Year">
        <option value="">Select</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>

<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success submit" /></code>```

Body:
I am working on this code when the submit button will be enabled only when user selects values from a DropDownListFor.

      @Html.DropDownListFor(m => m.Year, Model.YearList, "--Select Year--", new { @class = "form-control",id = "Year" })
      @Html.ValidationMessageFor(m => m.Year)

 <input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" />

js code:

   $("#Year").change(function () {
        if ($('#Year').val()!="--Select Year--")
            $('.submit').prop("disabled", false);
        else
            $('.submit').prop("disabled", true);
    });

No error message just the submit button is always enabled. Any help?

Body:
Update your code cause selector use class but no submit class so you id selector in your javascript code

$("#Year").change(function () {
    if ($('#Year').val()) {
    $('.submit').prop("disabled", false);
}
else {
    $('.submit').prop("disabled", true);
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="Year">
        <option value="">Select</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>

<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success submit" />


问:
Most efficient way to find the index of the only '1' bit in a char variable (in C)
This is an interview question:

You are given a char variable named ch, when you know that it represents a number that in its binary form, only one of its eight bits will be equal to '1'. I.E. , the only possible values for ch are: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80.

Given the variable ch, I need to write the most efficient code to get the index of that '1' bit. For example: if ch == 0x1 -> result is 0. if ch == 0x4 -> result is 2.

The obvious way is to use switch-case, but I need something more efficient.

Is there any bit manipulation you can do here for efficient implementation?

答: If you have only one bit set to 1,  that means it is a power of 2. You can directly get the index by taking log of ch.  You have to use 2 based log of course.


问:
No option for Azure NC/NV VMs?
I'm trying to create a Windows 10 Pro VM on Azure using an NC/NV server in the correct regions here: https://azure.microsoft.com/en-au/regions/services/ but don't find the option to select NC or NV even when looking at the correct regions.

Is this a limitation of the free trial?

答:
This is because your chose SSD disk type to create a VM. Try to change the disk type to HDD and then you can choose NC/NV Size .

You can see more details about this Deployment considerations in this official document.

Update

Due to the OP - @tweetypi said, there is also another cause. You may be with the free tier and restricted to 4 V-CPUs ,but NV6  requires 6 CPUs.

Also said in that document:

If you want to deploy more than a few N-series VMs, consider a
  pay-as-you-go subscription or other purchase options. If you're using
  an Azure free account, you can use only a limited number of Azure
  compute cores.

Title: No option for Azure NC/NV VMs?


问:
C++ FFmpeg create mp4 file
I'm trying to create mp4 video file with FFmpeg and C++, but in result I receive broken file (windows player shows "Can't play ... 0xc00d36c4"). If I create .h264 file, it can be played with 'ffplay' and successfully converted to mp4 via CL.

My code:

```<code>int main() {
    char *filename = "tmp.mp4";
    AVOutputFormat *fmt;
    AVFormatContext *fctx;
    AVCodecContext *cctx;
    AVStream *st;

    av_register_all();
    avcodec_register_all();

    //auto detect the output format from the name
    fmt = av_guess_format(NULL, filename, NULL);
    if (!fmt) {
        cout << "Error av_guess_format()" << endl; system("pause"); exit(1);
    }

    if (avformat_alloc_output_context2(&fctx, fmt, NULL, filename) < 0) {
        cout << "Error avformat_alloc_output_context2()" << endl; system("pause"); exit(1);
    }

    //stream creation + parameters
    st = avformat_new_stream(fctx, 0);
    if (!st) {
        cout << "Error avformat_new_stream()" << endl; system("pause"); exit(1);
    }

    st->codecpar->codec_id = fmt->video_codec;
    st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    st->codecpar->width = 352;
    st->codecpar->height = 288;
    st->time_base.num = 1;
    st->time_base.den = 25;

    AVCodec *pCodec = avcodec_find_encoder(st->codecpar->codec_id);
    if (!pCodec) {
        cout << "Error avcodec_find_encoder()" << endl; system("pause"); exit(1);
    }

    cctx = avcodec_alloc_context3(pCodec);
    if (!cctx) {
        cout << "Error avcodec_alloc_context3()" << endl; system("pause"); exit(1);
    }

    avcodec_parameters_to_context(cctx, st->codecpar);
    cctx->bit_rate = 400000;
    cctx->width = 352;
    cctx->height = 288;
    cctx->time_base.num = 1;
    cctx->time_base.den = 25;
    cctx->gop_size = 12;
    cctx->pix_fmt = AV_PIX_FMT_YUV420P;
    if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
        av_opt_set(cctx->priv_data, "preset", "ultrafast", 0);
    }
    if (fctx->oformat->flags & AVFMT_GLOBALHEADER) {
        cctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    }
    avcodec_parameters_from_context(st->codecpar, cctx);

    av_dump_format(fctx, 0, filename, 1);

    //OPEN FILE + WRITE HEADER
    if (avcodec_open2(cctx, pCodec, NULL) < 0) {
        cout << "Error avcodec_open2()" << endl; system("pause"); exit(1);
    }
    if (!(fmt->flags & AVFMT_NOFILE)) {
        if (avio_open(&fctx->pb, filename, AVIO_FLAG_WRITE) < 0) {
            cout << "Error avio_open()" << endl; system("pause"); exit(1);
        }
    }
    if (avformat_write_header(fctx, NULL) < 0) {
        cout << "Error avformat_write_header()" << endl; system("pause"); exit(1);
    }

    //CREATE DUMMY VIDEO
    AVFrame *frame = av_frame_alloc();
    frame->format = cctx->pix_fmt;
    frame->width = cctx->width;
    frame->height = cctx->height;
    av_image_alloc(frame->data, frame->linesize, cctx->width, cctx->height, cctx->pix_fmt, 32);

    AVPacket pkt;
    double video_pts = 0;
    for (int i = 0; i < 50; i++) {
        video_pts = (double)cctx->time_base.num / cctx->time_base.den * 90 * i;

        for (int y = 0; y < cctx->height; y++) {
            for (int x = 0; x < cctx->width; x++) {
                frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
                if (y < cctx->height / 2 && x < cctx->width / 2) {
                    /* Cb and Cr */
                    frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
                    frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
                }
            }
        }

        av_init_packet(&pkt);
        pkt.flags |= AV_PKT_FLAG_KEY;
        pkt.pts = frame->pts = video_pts;
        pkt.data = NULL;
        pkt.size = 0;
        pkt.stream_index = st->index;

        if (avcodec_send_frame(cctx, frame) < 0) {
            cout << "Error avcodec_send_frame()" << endl; system("pause"); exit(1);
        }
        if (avcodec_receive_packet(cctx, &pkt) == 0) {
            //cout << "Write frame " << to_string((int) pkt.pts) << endl;
            av_interleaved_write_frame(fctx, &pkt);
            av_packet_unref(&pkt);
        }
    }

    //DELAYED FRAMES
    for (;;) {
        avcodec_send_frame(cctx, NULL);
        if (avcodec_receive_packet(cctx, &pkt) == 0) {
            //cout << "-Write frame " << to_string((int)pkt.pts) << endl;
            av_interleaved_write_frame(fctx, &pkt);
            av_packet_unref(&pkt);
        }
        else {
            break;
        }
    }

    //FINISH
    av_write_trailer(fctx);
    if (!(fmt->flags & AVFMT_NOFILE)) {
        if (avio_close(fctx->pb) < 0) {
            cout << "Error avio_close()" << endl; system("pause"); exit(1);
        }
    }
    av_frame_free(&frame);
    avcodec_free_context(&cctx);
    avformat_free_context(fctx);

    system("pause");
    return 0;
}
</code>```

Output of program:

```<code>Output #0, mp4, to 'tmp.mp4':
    Stream #0:0: Video: h264, yuv420p, 352x288, q=2-31, 400 kb/s, 25 tbn
[libx264 @ 0000021c4a995ba0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 0000021c4a995ba0] profile Constrained Baseline, level 2.0
[libx264 @ 0000021c4a995ba0] 264 - core 152 r2851 ba24899 - H.264/MPEG-4 AVC codec - Copyleft 2003-2017 - http://www.videolan.org/x264.html - options: cabac=0 ref=1 deblock=0:0:0 analyse=0:0 me=dia subme=0 psy=1 psy_rd=1.00:0.00 mixed_ref=0 me_range=16 chroma_me=1 trellis=0 8x8dct=0 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=0 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=0 weightp=0 keyint=12 keyint_min=1 scenecut=0 intra_refresh=0 rc=abr mbtree=0 bitrate=400 ratetol=1.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=0
[libx264 @ 0000021c4a995ba0] frame I:5     Avg QP: 7.03  size:  9318
[libx264 @ 0000021c4a995ba0] frame P:45    Avg QP: 4.53  size:  4258
[libx264 @ 0000021c4a995ba0] mb I  I16..4: 100.0%  0.0%  0.0%
[libx264 @ 0000021c4a995ba0] mb P  I16..4:  0.0%  0.0%  0.0%  P16..4: 100.0%  0.0%  0.0%  0.0%  0.0%    skip: 0.0%
[libx264 @ 0000021c4a995ba0] final ratefactor: 9.11
[libx264 @ 0000021c4a995ba0] coded y,uvDC,uvAC intra: 18.9% 21.8% 14.5% inter: 7.8% 100.0% 15.5%
[libx264 @ 0000021c4a995ba0] i16 v,h,dc,p:  4%  5%  5% 86%
[libx264 @ 0000021c4a995ba0] i8c dc,h,v,p:  2%  9%  6% 82%
[libx264 @ 0000021c4a995ba0] kb/s:264.68
</code>```

If I will try to play mp4 file with 'ffplay' it prints:

```<code>[mov,mp4,m4a,3gp,3g2,mj2 @ 00000000026bf900] Could not find codec parameters for stream 0 (Video: h264 (avc1 / 0x31637661), none, 352x288, 138953 kb/s): unspecified pixel format
[h264 @ 00000000006c6ae0] non-existing PPS 0 referenced
[h264 @ 00000000006c6ae0] decode_slice_header error
[h264 @ 00000000006c6ae0] no frame!
</code>```

I've spent a lot of time without success of finding issue, what could be the reason of it?

Thank for help!

答:
Working solution:

```<code>#include "VideoCapture.h"

#define VIDEO_TMP_FILE "tmp.h264"
#define FINAL_FILE_NAME "record.mp4"

using namespace std;

void VideoCapture::Init(int width, int height, int fpsrate, int bitrate) {

    fps = fpsrate;

    int err;

    if (!(oformat = av_guess_format(NULL, VIDEO_TMP_FILE, NULL))) {
        Debug("Failed to define output format", 0);
        return;
    }

    if ((err = avformat_alloc_output_context2(&ofctx, oformat, NULL, VIDEO_TMP_FILE) < 0)) {
        Debug("Failed to allocate output context", err);
        Free();
        return;
    }

    if (!(codec = avcodec_find_encoder(oformat->video_codec))) {
        Debug("Failed to find encoder", 0);
        Free();
        return;
    }

    if (!(videoStream = avformat_new_stream(ofctx, codec))) {
        Debug("Failed to create new stream", 0);
        Free();
        return;
    }

    if (!(cctx = avcodec_alloc_context3(codec))) {
        Debug("Failed to allocate codec context", 0);
        Free();
        return;
    }

    videoStream->codecpar->codec_id = oformat->video_codec;
    videoStream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    videoStream->codecpar->width = width;
    videoStream->codecpar->height = height;
    videoStream->codecpar->format = AV_PIX_FMT_YUV420P;
    videoStream->codecpar->bit_rate = bitrate * 1000;
    videoStream->time_base = { 1, fps };

    avcodec_parameters_to_context(cctx, videoStream->codecpar);
    cctx->time_base = { 1, fps };
    cctx->max_b_frames = 2;
    cctx->gop_size = 12;
    if (videoStream->codecpar->codec_id == AV_CODEC_ID_H264) {
        av_opt_set(cctx, "preset", "ultrafast", 0);
    }
    if (ofctx->oformat->flags & AVFMT_GLOBALHEADER) {
        cctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    }
    avcodec_parameters_from_context(videoStream->codecpar, cctx);

    if ((err = avcodec_open2(cctx, codec, NULL)) < 0) {
        Debug("Failed to open codec", err);
        Free();
        return;
    }

    if (!(oformat->flags & AVFMT_NOFILE)) {
        if ((err = avio_open(&ofctx->pb, VIDEO_TMP_FILE, AVIO_FLAG_WRITE)) < 0) {
            Debug("Failed to open file", err);
            Free();
            return;
        }
    }

    if ((err = avformat_write_header(ofctx, NULL)) < 0) {
        Debug("Failed to write header", err);
        Free();
        return;
    }

    av_dump_format(ofctx, 0, VIDEO_TMP_FILE, 1);
}

void VideoCapture::AddFrame(uint8_t *data) {
    int err;
    if (!videoFrame) {

        videoFrame = av_frame_alloc();
        videoFrame->format = AV_PIX_FMT_YUV420P;
        videoFrame->width = cctx->width;
        videoFrame->height = cctx->height;

        if ((err = av_frame_get_buffer(videoFrame, 32)) < 0) {
            Debug("Failed to allocate picture", err);
            return;
        }
    }

    if (!swsCtx) {
        swsCtx = sws_getContext(cctx->width, cctx->height, AV_PIX_FMT_RGB24, cctx->width, cctx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, 0, 0, 0);
    }

    int inLinesize[1] = { 3 * cctx->width };

    // From RGB to YUV
    sws_scale(swsCtx, (const uint8_t * const *)&data, inLinesize, 0, cctx->height, videoFrame->data, videoFrame->linesize);

    videoFrame->pts = frameCounter++;

    if ((err = avcodec_send_frame(cctx, videoFrame)) < 0) {
        Debug("Failed to send frame", err);
        return;
    }

    AVPacket pkt;
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;

    if (avcodec_receive_packet(cctx, &pkt) == 0) {
        pkt.flags |= AV_PKT_FLAG_KEY;
        av_interleaved_write_frame(ofctx, &pkt);
        av_packet_unref(&pkt);
    }
}

void VideoCapture::Finish() {
    //DELAYED FRAMES
    AVPacket pkt;
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;

    for (;;) {
        avcodec_send_frame(cctx, NULL);
        if (avcodec_receive_packet(cctx, &pkt) == 0) {
            av_interleaved_write_frame(ofctx, &pkt);
            av_packet_unref(&pkt);
        }
        else {
            break;
        }
    }

    av_write_trailer(ofctx);
    if (!(oformat->flags & AVFMT_NOFILE)) {
        int err = avio_close(ofctx->pb);
        if (err < 0) {
            Debug("Failed to close file", err);
        }
    }

    Free();

    Remux();
}

void VideoCapture::Free() {
    if (videoFrame) {
        av_frame_free(&videoFrame);
    }
    if (cctx) {
        avcodec_free_context(&cctx);
    }
    if (ofctx) {
        avformat_free_context(ofctx);
    }
    if (swsCtx) {
        sws_freeContext(swsCtx);
    }
}

void VideoCapture::Remux() {
    AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
    int err;

    if ((err = avformat_open_input(&ifmt_ctx, VIDEO_TMP_FILE, 0, 0)) < 0) {
        Debug("Failed to open input file for remuxing", err);
        goto end;
    }
    if ((err = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
        Debug("Failed to retrieve input stream information", err);
        goto end;
    }
    if ((err = avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, FINAL_FILE_NAME))) {
        Debug("Failed to allocate output context", err);
        goto end;
    }

    AVStream *inVideoStream = ifmt_ctx->streams[0];
    AVStream *outVideoStream = avformat_new_stream(ofmt_ctx, NULL);
    if (!outVideoStream) {
        Debug("Failed to allocate output video stream", 0);
        goto end;
    }
    outVideoStream->time_base = { 1, fps };
    avcodec_parameters_copy(outVideoStream->codecpar, inVideoStream->codecpar);
    outVideoStream->codecpar->codec_tag = 0;

    if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
        if ((err = avio_open(&ofmt_ctx->pb, FINAL_FILE_NAME, AVIO_FLAG_WRITE)) < 0) {
            Debug("Failed to open output file", err);
            goto end;
        }
    }

    if ((err = avformat_write_header(ofmt_ctx, 0)) < 0) {
        Debug("Failed to write header to output file", err);
        goto end;
    }

    AVPacket videoPkt;
    int ts = 0;
    while (true) {
        if ((err = av_read_frame(ifmt_ctx, &videoPkt)) < 0) {
            break;
        }
        videoPkt.stream_index = outVideoStream->index;
        videoPkt.pts = ts;
        videoPkt.dts = ts;
        videoPkt.duration = av_rescale_q(videoPkt.duration, inVideoStream->time_base, outVideoStream->time_base);
        ts += videoPkt.duration;
        videoPkt.pos = -1;

        if ((err = av_interleaved_write_frame(ofmt_ctx, &videoPkt)) < 0) {
            Debug("Failed to mux packet", err);
            av_packet_unref(&videoPkt);
            break;
        }
        av_packet_unref(&videoPkt);
    }

    av_write_trailer(ofmt_ctx);

end:
    if (ifmt_ctx) {
        avformat_close_input(&ifmt_ctx);
    }
    if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
        avio_closep(&ofmt_ctx->pb);
    }
    if (ofmt_ctx) {
        avformat_free_context(ofmt_ctx);
    }
}
</code>```

Header file:

```<code>#define VIDEOCAPTURE_API __declspec(dllexport)

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <cstring>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <string>

extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavcodec/avfft.h>

#include <libavdevice/avdevice.h>

#include <libavfilter/avfilter.h>
#include <libavfilter/avfiltergraph.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>

#include <libavformat/avformat.h>
#include <libavformat/avio.h>

    // libav resample

#include <libavutil/opt.h>
#include <libavutil/common.h>
#include <libavutil/channel_layout.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>
#include <libavutil/time.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#include <libavutil/file.h>

    // hwaccel
#include "libavcodec/vdpau.h"
#include "libavutil/hwcontext.h"
#include "libavutil/hwcontext_vdpau.h"

    // lib swresample

#include <libswscale/swscale.h>

    std::ofstream logFile;

    void Log(std::string str) {
        logFile.open("Logs.txt", std::ofstream::app);
        logFile.write(str.c_str(), str.size());
        logFile.close();
    }

    typedef void(*FuncPtr)(const char *);
    FuncPtr ExtDebug;
    char errbuf[32];

    void Debug(std::string str, int err) {
        Log(str + " " + std::to_string(err));
        if (err < 0) {
            av_strerror(err, errbuf, sizeof(errbuf));
            str += errbuf;
        }
        Log(str);
        ExtDebug(str.c_str());
    }

    void avlog_cb(void *, int level, const char * fmt, va_list vargs) {
        static char message[8192];
        vsnprintf_s(message, sizeof(message), fmt, vargs);
        Log(message);
    }

    class VideoCapture {
    public:

        VideoCapture() {
            oformat = NULL;
            ofctx = NULL;
            videoStream = NULL;
            videoFrame = NULL;
            swsCtx = NULL;
            frameCounter = 0;

            // Initialize libavcodec
            av_register_all();
            av_log_set_callback(avlog_cb);
        }

        ~VideoCapture() {
            Free();
        }

        void Init(int width, int height, int fpsrate, int bitrate);

        void AddFrame(uint8_t *data);

        void Finish();

    private:

        AVOutputFormat *oformat;
        AVFormatContext *ofctx;

        AVStream *videoStream;
        AVFrame *videoFrame;

        AVCodec *codec;
        AVCodecContext *cctx;

        SwsContext *swsCtx;

        int frameCounter;

        int fps;

        void Free();

        void Remux();
    };

    VIDEOCAPTURE_API VideoCapture* Init(int width, int height, int fps, int bitrate) {
        VideoCapture *vc = new VideoCapture();
        vc->Init(width, height, fps, bitrate);
        return vc;
    };

    VIDEOCAPTURE_API void AddFrame(uint8_t *data, VideoCapture *vc) {
        vc->AddFrame(data);
    }

    VIDEOCAPTURE_API void Finish(VideoCapture *vc) {
        vc->Finish();
    }

    VIDEOCAPTURE_API void SetDebug(FuncPtr fp) {
        ExtDebug = fp;
    };
}
</code>```

Title: C++ FFmpeg create mp4 file

Body:
I'm trying to create mp4 video file with FFmpeg and C++, but in result I receive broken file (windows player shows "Can't play ... 0xc00d36c4"). If I create .h264 file, it can be played with 'ffplay' and successfully converted to mp4 via CL.

My code:

int main() {
    char *filename = "tmp.mp4";
    AVOutputFormat *fmt;
    AVFormatContext *fctx;
    AVCodecContext *cctx;
    AVStream *st;

    av_register_all();
    avcodec_register_all();

    //auto detect the output format from the name
    fmt = av_guess_format(NULL, filename, NULL);
    if (!fmt) {
        cout << "Error av_guess_format()" << endl; system("pause"); exit(1);
    }

    if (avformat_alloc_output_context2(&fctx, fmt, NULL, filename) < 0) {
        cout << "Error avformat_alloc_output_context2()" << endl; system("pause"); exit(1);
    }

    //stream creation + parameters
    st = avformat_new_stream(fctx, 0);
    if (!st) {
        cout << "Error avformat_new_stream()" << endl; system("pause"); exit(1);
    }

    st->codecpar->codec_id = fmt->video_codec;
    st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    st->codecpar->width = 352;
    st->codecpar->height = 288;
    st->time_base.num = 1;
    st->time_base.den = 25;

    AVCodec *pCodec = avcodec_find_encoder(st->codecpar->codec_id);
    if (!pCodec) {
        cout << "Error avcodec_find_encoder()" << endl; system("pause"); exit(1);
    }

    cctx = avcodec_alloc_context3(pCodec);
    if (!cctx) {
        cout << "Error avcodec_alloc_context3()" << endl; system("pause"); exit(1);
    }

    avcodec_parameters_to_context(cctx, st->codecpar);
    cctx->bit_rate = 400000;
    cctx->width = 352;
    cctx->height = 288;
    cctx->time_base.num = 1;
    cctx->time_base.den = 25;
    cctx->gop_size = 12;
    cctx->pix_fmt = AV_PIX_FMT_YUV420P;
    if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
        av_opt_set(cctx->priv_data, "preset", "ultrafast", 0);
    }
    if (fctx->oformat->flags & AVFMT_GLOBALHEADER) {
        cctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    }
    avcodec_parameters_from_context(st->codecpar, cctx);

    av_dump_format(fctx, 0, filename, 1);

    //OPEN FILE + WRITE HEADER
    if (avcodec_open2(cctx, pCodec, NULL) < 0) {
        cout << "Error avcodec_open2()" << endl; system("pause"); exit(1);
    }
    if (!(fmt->flags & AVFMT_NOFILE)) {
        if (avio_open(&fctx->pb, filename, AVIO_FLAG_WRITE) < 0) {
            cout << "Error avio_open()" << endl; system("pause"); exit(1);
        }
    }
    if (avformat_write_header(fctx, NULL) < 0) {
        cout << "Error avformat_write_header()" << endl; system("pause"); exit(1);
    }

    //CREATE DUMMY VIDEO
    AVFrame *frame = av_frame_alloc();
    frame->format = cctx->pix_fmt;
    frame->width = cctx->width;
    frame->height = cctx->height;
    av_image_alloc(frame->data, frame->linesize, cctx->width, cctx->height, cctx->pix_fmt, 32);

    AVPacket pkt;
    double video_pts = 0;
    for (int i = 0; i < 50; i++) {
        video_pts = (double)cctx->time_base.num / cctx->time_base.den * 90 * i;

        for (int y = 0; y < cctx->height; y++) {
            for (int x = 0; x < cctx->width; x++) {
                frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
                if (y < cctx->height / 2 && x < cctx->width / 2) {
                    /* Cb and Cr */
                    frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
                    frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
                }
            }
        }

        av_init_packet(&pkt);
        pkt.flags |= AV_PKT_FLAG_KEY;
        pkt.pts = frame->pts = video_pts;
        pkt.data = NULL;
        pkt.size = 0;
        pkt.stream_index = st->index;

        if (avcodec_send_frame(cctx, frame) < 0) {
            cout << "Error avcodec_send_frame()" << endl; system("pause"); exit(1);
        }
        if (avcodec_receive_packet(cctx, &pkt) == 0) {
            //cout << "Write frame " << to_string((int) pkt.pts) << endl;
            av_interleaved_write_frame(fctx, &pkt);
            av_packet_unref(&pkt);
        }
    }

    //DELAYED FRAMES
    for (;;) {
        avcodec_send_frame(cctx, NULL);
        if (avcodec_receive_packet(cctx, &pkt) == 0) {
            //cout << "-Write frame " << to_string((int)pkt.pts) << endl;
            av_interleaved_write_frame(fctx, &pkt);
            av_packet_unref(&pkt);
        }
        else {
            break;
        }
    }

    //FINISH
    av_write_trailer(fctx);
    if (!(fmt->flags & AVFMT_NOFILE)) {
        if (avio_close(fctx->pb) < 0) {
            cout << "Error avio_close()" << endl; system("pause"); exit(1);
        }
    }
    av_frame_free(&frame);
    avcodec_free_context(&cctx);
    avformat_free_context(fctx);

    system("pause");
    return 0;
}

Output of program:

Output #0, mp4, to 'tmp.mp4':
    Stream #0:0: Video: h264, yuv420p, 352x288, q=2-31, 400 kb/s, 25 tbn
[libx264 @ 0000021c4a995ba0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 0000021c4a995ba0] profile Constrained Baseline, level 2.0
[libx264 @ 0000021c4a995ba0] 264 - core 152 r2851 ba24899 - H.264/MPEG-4 AVC codec - Copyleft 2003-2017 - http://www.videolan.org/x264.html - options: cabac=0 ref=1 deblock=0:0:0 analyse=0:0 me=dia subme=0 psy=1 psy_rd=1.00:0.00 mixed_ref=0 me_range=16 chroma_me=1 trellis=0 8x8dct=0 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=0 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=0 weightp=0 keyint=12 keyint_min=1 scenecut=0 intra_refresh=0 rc=abr mbtree=0 bitrate=400 ratetol=1.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=0
[libx264 @ 0000021c4a995ba0] frame I:5     Avg QP: 7.03  size:  9318
[libx264 @ 0000021c4a995ba0] frame P:45    Avg QP: 4.53  size:  4258
[libx264 @ 0000021c4a995ba0] mb I  I16..4: 100.0%  0.0%  0.0%
[libx264 @ 0000021c4a995ba0] mb P  I16..4:  0.0%  0.0%  0.0%  P16..4: 100.0%  0.0%  0.0%  0.0%  0.0%    skip: 0.0%
[libx264 @ 0000021c4a995ba0] final ratefactor: 9.11
[libx264 @ 0000021c4a995ba0] coded y,uvDC,uvAC intra: 18.9% 21.8% 14.5% inter: 7.8% 100.0% 15.5%
[libx264 @ 0000021c4a995ba0] i16 v,h,dc,p:  4%  5%  5% 86%
[libx264 @ 0000021c4a995ba0] i8c dc,h,v,p:  2%  9%  6% 82%
[libx264 @ 0000021c4a995ba0] kb/s:264.68

If I will try to play mp4 file with 'ffplay' it prints:

[mov,mp4,m4a,3gp,3g2,mj2 @ 00000000026bf900] Could not find codec parameters for stream 0 (Video: h264 (avc1 / 0x31637661), none, 352x288, 138953 kb/s): unspecified pixel format
[h264 @ 00000000006c6ae0] non-existing PPS 0 referenced
[h264 @ 00000000006c6ae0] decode_slice_header error
[h264 @ 00000000006c6ae0] no frame!

I've spent a lot of time without success of finding issue, what could be the reason of it?

Thank for help!

Body:
Working solution:

#include "VideoCapture.h"

#define VIDEO_TMP_FILE "tmp.h264"
#define FINAL_FILE_NAME "record.mp4"

using namespace std;

void VideoCapture::Init(int width, int height, int fpsrate, int bitrate) {

    fps = fpsrate;

    int err;

    if (!(oformat = av_guess_format(NULL, VIDEO_TMP_FILE, NULL))) {
        Debug("Failed to define output format", 0);
        return;
    }

    if ((err = avformat_alloc_output_context2(&ofctx, oformat, NULL, VIDEO_TMP_FILE) < 0)) {
        Debug("Failed to allocate output context", err);
        Free();
        return;
    }

    if (!(codec = avcodec_find_encoder(oformat->video_codec))) {
        Debug("Failed to find encoder", 0);
        Free();
        return;
    }

    if (!(videoStream = avformat_new_stream(ofctx, codec))) {
        Debug("Failed to create new stream", 0);
        Free();
        return;
    }

    if (!(cctx = avcodec_alloc_context3(codec))) {
        Debug("Failed to allocate codec context", 0);
        Free();
        return;
    }

    videoStream->codecpar->codec_id = oformat->video_codec;
    videoStream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    videoStream->codecpar->width = width;
    videoStream->codecpar->height = height;
    videoStream->codecpar->format = AV_PIX_FMT_YUV420P;
    videoStream->codecpar->bit_rate = bitrate * 1000;
    videoStream->time_base = { 1, fps };

    avcodec_parameters_to_context(cctx, videoStream->codecpar);
    cctx->time_base = { 1, fps };
    cctx->max_b_frames = 2;
    cctx->gop_size = 12;
    if (videoStream->codecpar->codec_id == AV_CODEC_ID_H264) {
        av_opt_set(cctx, "preset", "ultrafast", 0);
    }
    if (ofctx->oformat->flags & AVFMT_GLOBALHEADER) {
        cctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    }
    avcodec_parameters_from_context(videoStream->codecpar, cctx);

    if ((err = avcodec_open2(cctx, codec, NULL)) < 0) {
        Debug("Failed to open codec", err);
        Free();
        return;
    }

    if (!(oformat->flags & AVFMT_NOFILE)) {
        if ((err = avio_open(&ofctx->pb, VIDEO_TMP_FILE, AVIO_FLAG_WRITE)) < 0) {
            Debug("Failed to open file", err);
            Free();
            return;
        }
    }

    if ((err = avformat_write_header(ofctx, NULL)) < 0) {
        Debug("Failed to write header", err);
        Free();
        return;
    }

    av_dump_format(ofctx, 0, VIDEO_TMP_FILE, 1);
}

void VideoCapture::AddFrame(uint8_t *data) {
    int err;
    if (!videoFrame) {

        videoFrame = av_frame_alloc();
        videoFrame->format = AV_PIX_FMT_YUV420P;
        videoFrame->width = cctx->width;
        videoFrame->height = cctx->height;

        if ((err = av_frame_get_buffer(videoFrame, 32)) < 0) {
            Debug("Failed to allocate picture", err);
            return;
        }
    }

    if (!swsCtx) {
        swsCtx = sws_getContext(cctx->width, cctx->height, AV_PIX_FMT_RGB24, cctx->width, cctx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, 0, 0, 0);
    }

    int inLinesize[1] = { 3 * cctx->width };

    // From RGB to YUV
    sws_scale(swsCtx, (const uint8_t * const *)&data, inLinesize, 0, cctx->height, videoFrame->data, videoFrame->linesize);

    videoFrame->pts = frameCounter++;

    if ((err = avcodec_send_frame(cctx, videoFrame)) < 0) {
        Debug("Failed to send frame", err);
        return;
    }

    AVPacket pkt;
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;

    if (avcodec_receive_packet(cctx, &pkt) == 0) {
        pkt.flags |= AV_PKT_FLAG_KEY;
        av_interleaved_write_frame(ofctx, &pkt);
        av_packet_unref(&pkt);
    }
}

void VideoCapture::Finish() {
    //DELAYED FRAMES
    AVPacket pkt;
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;

    for (;;) {
        avcodec_send_frame(cctx, NULL);
        if (avcodec_receive_packet(cctx, &pkt) == 0) {
            av_interleaved_write_frame(ofctx, &pkt);
            av_packet_unref(&pkt);
        }
        else {
            break;
        }
    }

    av_write_trailer(ofctx);
    if (!(oformat->flags & AVFMT_NOFILE)) {
        int err = avio_close(ofctx->pb);
        if (err < 0) {
            Debug("Failed to close file", err);
        }
    }

    Free();

    Remux();
}

void VideoCapture::Free() {
    if (videoFrame) {
        av_frame_free(&videoFrame);
    }
    if (cctx) {
        avcodec_free_context(&cctx);
    }
    if (ofctx) {
        avformat_free_context(ofctx);
    }
    if (swsCtx) {
        sws_freeContext(swsCtx);
    }
}

void VideoCapture::Remux() {
    AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
    int err;

    if ((err = avformat_open_input(&ifmt_ctx, VIDEO_TMP_FILE, 0, 0)) < 0) {
        Debug("Failed to open input file for remuxing", err);
        goto end;
    }
    if ((err = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
        Debug("Failed to retrieve input stream information", err);
        goto end;
    }
    if ((err = avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, FINAL_FILE_NAME))) {
        Debug("Failed to allocate output context", err);
        goto end;
    }

    AVStream *inVideoStream = ifmt_ctx->streams[0];
    AVStream *outVideoStream = avformat_new_stream(ofmt_ctx, NULL);
    if (!outVideoStream) {
        Debug("Failed to allocate output video stream", 0);
        goto end;
    }
    outVideoStream->time_base = { 1, fps };
    avcodec_parameters_copy(outVideoStream->codecpar, inVideoStream->codecpar);
    outVideoStream->codecpar->codec_tag = 0;

    if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
        if ((err = avio_open(&ofmt_ctx->pb, FINAL_FILE_NAME, AVIO_FLAG_WRITE)) < 0) {
            Debug("Failed to open output file", err);
            goto end;
        }
    }

    if ((err = avformat_write_header(ofmt_ctx, 0)) < 0) {
        Debug("Failed to write header to output file", err);
        goto end;
    }

    AVPacket videoPkt;
    int ts = 0;
    while (true) {
        if ((err = av_read_frame(ifmt_ctx, &videoPkt)) < 0) {
            break;
        }
        videoPkt.stream_index = outVideoStream->index;
        videoPkt.pts = ts;
        videoPkt.dts = ts;
        videoPkt.duration = av_rescale_q(videoPkt.duration, inVideoStream->time_base, outVideoStream->time_base);
        ts += videoPkt.duration;
        videoPkt.pos = -1;

        if ((err = av_interleaved_write_frame(ofmt_ctx, &videoPkt)) < 0) {
            Debug("Failed to mux packet", err);
            av_packet_unref(&videoPkt);
            break;
        }
        av_packet_unref(&videoPkt);
    }

    av_write_trailer(ofmt_ctx);

end:
    if (ifmt_ctx) {
        avformat_close_input(&ifmt_ctx);
    }
    if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
        avio_closep(&ofmt_ctx->pb);
    }
    if (ofmt_ctx) {
        avformat_free_context(ofmt_ctx);
    }
}

Header file:

#define VIDEOCAPTURE_API __declspec(dllexport)

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <cstring>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <string>

extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavcodec/avfft.h>

#include <libavdevice/avdevice.h>

#include <libavfilter/avfilter.h>
#include <libavfilter/avfiltergraph.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>

#include <libavformat/avformat.h>
#include <libavformat/avio.h>

    // libav resample

#include <libavutil/opt.h>
#include <libavutil/common.h>
#include <libavutil/channel_layout.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>
#include <libavutil/time.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#include <libavutil/file.h>

    // hwaccel
#include "libavcodec/vdpau.h"
#include "libavutil/hwcontext.h"
#include "libavutil/hwcontext_vdpau.h"

    // lib swresample

#include <libswscale/swscale.h>

    std::ofstream logFile;

    void Log(std::string str) {
        logFile.open("Logs.txt", std::ofstream::app);
        logFile.write(str.c_str(), str.size());
        logFile.close();
    }

    typedef void(*FuncPtr)(const char *);
    FuncPtr ExtDebug;
    char errbuf[32];

    void Debug(std::string str, int err) {
        Log(str + " " + std::to_string(err));
        if (err < 0) {
            av_strerror(err, errbuf, sizeof(errbuf));
            str += errbuf;
        }
        Log(str);
        ExtDebug(str.c_str());
    }

    void avlog_cb(void *, int level, const char * fmt, va_list vargs) {
        static char message[8192];
        vsnprintf_s(message, sizeof(message), fmt, vargs);
        Log(message);
    }

    class VideoCapture {
    public:

        VideoCapture() {
            oformat = NULL;
            ofctx = NULL;
            videoStream = NULL;
            videoFrame = NULL;
            swsCtx = NULL;
            frameCounter = 0;

            // Initialize libavcodec
            av_register_all();
            av_log_set_callback(avlog_cb);
        }

        ~VideoCapture() {
            Free();
        }

        void Init(int width, int height, int fpsrate, int bitrate);

        void AddFrame(uint8_t *data);

        void Finish();

    private:

        AVOutputFormat *oformat;
        AVFormatContext *ofctx;

        AVStream *videoStream;
        AVFrame *videoFrame;

        AVCodec *codec;
        AVCodecContext *cctx;

        SwsContext *swsCtx;

        int frameCounter;

        int fps;

        void Free();

        void Remux();
    };

    VIDEOCAPTURE_API VideoCapture* Init(int width, int height, int fps, int bitrate) {
        VideoCapture *vc = new VideoCapture();
        vc->Init(width, height, fps, bitrate);
        return vc;
    };

    VIDEOCAPTURE_API void AddFrame(uint8_t *data, VideoCapture *vc) {
        vc->AddFrame(data);
    }

    VIDEOCAPTURE_API void Finish(VideoCapture *vc) {
        vc->Finish();
    }

    VIDEOCAPTURE_API void SetDebug(FuncPtr fp) {
        ExtDebug = fp;
    };
}


问:
What is the iPhone 4 user-agent?
Has anyone found the iPhone 4's browser's user-agent string yet?</p>

答:
Note: The user agent strings from Facebook's internal browser do indicate the actual physical device. Even the cellphone carrier (eg. AT&T)

Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 [FBAN/FBIOS;FBAV/149.0.0.39.64;FBBV/79173879;FBDV/iPhone7,2;FBMD/iPhone;FBSN/iOS;FBSV/10.3.3;FBSS/2;FBCR/AT&T;FBID/phone;FBLC/en_US;FBOP/5;FBRV/0

Mozilla/5.0 (iPhone; CPU iPhone OS 11_1 like Mac OS X) AppleWebKit/604.3.5 (KHTML, like Gecko) Mobile/15B93 [FBAN/FBIOS;FBAV/148.0.0.45.64;FBBV/78032376;FBDV/iPhone10,4;FBMD/iPhone;FBSN/iOS;FBSV/11.1;FBSS/2;FBCR/AT&T;FBID/phone;FBLC/en_US;FBOP/5;FBRV/0]

These won't be the case in Safari or Chrome from iOS - only within the browser inside the Facebook app.

(I'm getting iPhone9 too though - not quite sure what that is!)

Title: What is the iPhone 4 user-agent?


问:
Is C++11 is faster than C++03 in terms of efficiency?
I work in trading firm and here latency matters a lot. The project assigns to me is developed using a mix of c and c++98 parts, But I believe we can make same project using C++11 without losing efficiency. As discussed with my seniors, they say you should stick with C and c++03 as they are efficient compare to C++11 at micro level.
Can anyone highlight me If I go with C++11, will I get better results?</p>

答:
C++ - the language - doesn't make any performance guarantees beyond complexity limit O(*) for various operations - mostly containers, and general concept of "you don't pay for what you don't use".

There are no significant changes to this (except maybe the new container types that might be a better fit in a few places).

[edit] I forgot: move semantics can significantly speed up an existing code base without any changes. (However, if you've been squeezing cycles, you probably won't benefit.)

However (there's always one in C++) compilers usually have improved. Notable sources of significant performnance gains are new technologies like link-time code generation and automatic vectorization that have become much more widespead and refined, and better support for contemporary CPU architectures.

Against a compiler upgrade speaks only the risk and cost of research and testing.

Gut feel: Your seniors shy away from the risk and the change.

"C and c++03 [...] are [more] efficient compared to C++11 at micro level" is bull. Unless your seniors didn't bother to learn the newfangled stuff introduced 20 years ago.