问:
Netty (netty-all-4.1.12.Final.jar) java.io.IOException: An existing connection was forcibly closed by the remote host
Problem description:

My program creates a Netty server and client, then it makes 2^17 connections to that server, at some point the client starts to receive this exception:

java.io.IOException: Istniejące połączenie zostało gwałtownie zamknięte przez zdalnego hosta.

The english equivalent is:

java.io.IOException: An existing connection was forcibly closed by the remote host

Obviously it is not desired that server is forcibly closing existing connections.

Steps to reproduce:

For convenience of anyone willing to reproduce this problem I've created this "single runnable java file" program that reproduces it, it needs only the netty-all-4.1.12.Final.jar dependency. It starts netty server on some free port, then creates client, perform requests, waits a bit to give the server chance to process the requests, then print statistics about how many connections was made, how many connections did server process, how many connections was lost, how many and what kind of exceptions did server encountered, and how many and what kind of exceptions did client encountered.

```<code>package netty.exception.tst;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyException {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("starting server");
        NettyServer server = new NettyServer(0);
        int port = server.getPort();
        System.out.println("server started at port: " + port);

        System.out.println("staring client");
        NettyClient client = new NettyClient();
        System.out.println("client started");

        int noOfConnectionsToPerform = 1 << 17;
        System.out.println("performing " + noOfConnectionsToPerform + " connections");
        for (int n = 0; n < noOfConnectionsToPerform; n++) {
            // send a request
            ChannelFuture f = client.getBootstrap().connect("localhost", port);
        }
        System.out.println("client performed " + noOfConnectionsToPerform + " connections");

        System.out.println("wait a bit to give a chance for server to finish processing incoming requests");
        Thread.currentThread().sleep(80000);

        System.out.println("shutting down server and client");
        server.stop();
        client.stop();

        System.out.println("stopped, server received: " + server.connectionsCount() + " connections");
        int numberOfLostConnections = noOfConnectionsToPerform - server.connectionsCount();
        if (numberOfLostConnections > 0) {
            System.out.println("Where do we lost " + numberOfLostConnections + " connections?");
        }

        System.out.println("srerver exceptions: ");
        printExceptions(server.getExceptions());
        System.out.println("client exceptions: ");
        printExceptions(client.getExceptions());
    }

    private static void printExceptions(Map<String, Integer> exceptions) {
        if (exceptions.isEmpty()) {
            System.out.println("There was no exceptions");
        }
        for (Entry<String, Integer> exception : exceptions.entrySet()) {
            System.out.println("There was " + exception.getValue() + " times this exception:");
            System.out.println(exception.getKey());
        }
    }

    public static class NettyServer {
        private ChannelFuture channelFuture;
        private EventLoopGroup bossGroup;
        private EventLoopGroup workerGroup;
        private AtomicInteger connections = new AtomicInteger(0);
        private ExceptionCounter exceptionCounter = new ExceptionCounter();

        public NettyServer(int port) throws InterruptedException {
            bossGroup = new NioEventLoopGroup();
            workerGroup = new NioEventLoopGroup();
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new TimeServerHandler() {

                                @Override
                                public void channelActive(final ChannelHandlerContext ctx) {
                                    connections.incrementAndGet();
                                    super.channelActive(ctx);
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                    exceptionCounter.countException(cause);
                                    super.exceptionCaught(ctx, cause);
                                }

                            });
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
            channelFuture = serverBootstrap.bind(port).sync();
        }

        public int getPort() {
            return ((InetSocketAddress) channelFuture.channel().localAddress()).getPort();
        }

        public int connectionsCount() {
            return connections.get();
        }

        public Map<String, Integer> getExceptions() {
            return exceptionCounter.getExceptions();
        }

        public void stop() {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            try {
                bossGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
                workerGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static class NettyClient {
        private Bootstrap bootstrap;
        private EventLoopGroup workerGroup;
        private ExceptionCounter exceptionCounter = new ExceptionCounter();

        public NettyClient() {
            workerGroup = new NioEventLoopGroup();

            bootstrap = new Bootstrap();
            bootstrap.group(workerGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new TimeClientHandler() {
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                            exceptionCounter.countException(cause);
                            super.exceptionCaught(ctx, cause);
                        }
                    });
                }
            });
        }

        public Bootstrap getBootstrap() {
            return bootstrap;
        }

        public void stop() {
            workerGroup.shutdownGracefully();
            try {
                workerGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public Map<String, Integer> getExceptions() {
            return exceptionCounter.getExceptions();
        }
    }

    public static class TimeServerHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelActive(final ChannelHandlerContext ctx) {
            final ByteBuf time = ctx.alloc().buffer(4);
            time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));

            final ChannelFuture f = ctx.writeAndFlush(time);
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) {
                    assert f == future;
                    ctx.close();
                }
            });
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            ctx.close();
        }
    }

    public static class TimeClientHandler extends ChannelInboundHandlerAdapter {
        private ThreadLocal<ByteBuf> buf = new ThreadLocal<ByteBuf>();

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) {
            buf.set(ctx.alloc().buffer(4));
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) {
            buf.get().release();
            buf.remove();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ByteBuf m = (ByteBuf) msg;
            buf.get().writeBytes(m);
            m.release();

            if (buf.get().readableBytes() >= 4) {
                long currentTimeMillis = (buf.get().readUnsignedInt() - 2208988800L) * 1000L;
                ctx.close();
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            ctx.close();
        }
    }

    public static class ExceptionCounter {
        private ConcurrentHashMap<String, AtomicInteger> exceptions = new ConcurrentHashMap<String, AtomicInteger>();

        private void countException(Throwable cause) {

            StringWriter writer = new StringWriter();
            cause.printStackTrace(new PrintWriter(writer));
            String stackTrace = writer.toString();

            AtomicInteger exceptionCount = exceptions.get(stackTrace);
            if (exceptionCount == null) {
                exceptionCount = new AtomicInteger(0);
                AtomicInteger prevCount = exceptions.putIfAbsent(stackTrace, exceptionCount);
                if (prevCount != null) {
                    exceptionCount = prevCount;
                }
            }
            exceptionCount.incrementAndGet();
        }

        public Map<String, Integer> getExceptions() {
            Map<String, Integer> newMap = exceptions.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get()));
            return Collections.unmodifiableMap(newMap);
        }
    }
}
</code>```

The output is:

```<code>starting server
server started at port: 56069
staring client
client started
performing 131072 connections
client performed 131072 connections
wait a bit to give a chance for server to finish processing incoming requests
shutting down server and client
stopped, server received: 34735 connections
Where do we lost 96337 connections?
srerver exceptions:
There was no exceptions
client exceptions:
There was 258 times this exception:
java.io.IOException: Istniejące połączenie zostało gwałtownie zamknięte przez zdalnego hosta
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
    at sun.nio.ch.IOUtil.read(IOUtil.java:192)
    at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
    at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
    at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100)
    at io.netty.buffer.WrappedByteBuf.writeBytes(WrappedByteBuf.java:813)
    at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:372)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:123)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
    at java.lang.Thread.run(Thread.java:745)

There was 30312 times this exception:
java.io.IOException: Istniejące połączenie zostało gwałtownie zamknięte przez zdalnego hosta
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
    at sun.nio.ch.IOUtil.read(IOUtil.java:192)
    at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
    at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
    at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100)
    at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:372)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:123)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
    at java.lang.Thread.run(Thread.java:745)
</code>```

Questions:

Why this exception is thrown?

Where the lost connections has gone? Why there is no error for them?

How to avoid it, what is the correct way to program this kind of "high throughput" application to not have such problems like loosing/breaking existing connections?

No related to subject, but maybe some Netty expert will know: Why when I change in TimeClientHandler the field declaration of private ThreadLocal<ByteBuf> buf to be also static, I have null pointer exception in TimeClientHandler.handlerRemoved? This is very strange, is this class somehow replicated? or are the Threads from NioEventLoopGroup somehow strange?

Environment:

Netty version: netty-all-4.1.12.Final.jar

JVM version: jdk1.8.0_111 64 bit

OS version: Windows 10 64 bit

答: There is a limit of 64k ports per IP address, so you cannot open  2^17 ports.  Since each socket uses a file handle, you might be hitting the limit of max open files per process.  See "Max open files" for working process.</p>

Body:
Problem description:

My program creates a Netty server and client, then it makes 2^17 connections to that server, at some point the client starts to receive this exception:

java.io.IOException: Istniejące połączenie zostało gwałtownie zamknięte przez zdalnego hosta.

The english equivalent is:

java.io.IOException: An existing connection was forcibly closed by the remote host

Obviously it is not desired that server is forcibly closing existing connections.

Steps to reproduce:

For convenience of anyone willing to reproduce this problem I've created this "single runnable java file" program that reproduces it, it needs only the netty-all-4.1.12.Final.jar dependency. It starts netty server on some free port, then creates client, perform requests, waits a bit to give the server chance to process the requests, then print statistics about how many connections was made, how many connections did server process, how many connections was lost, how many and what kind of exceptions did server encountered, and how many and what kind of exceptions did client encountered.

package netty.exception.tst;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyException {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("starting server");
        NettyServer server = new NettyServer(0);
        int port = server.getPort();
        System.out.println("server started at port: " + port);

        System.out.println("staring client");
        NettyClient client = new NettyClient();
        System.out.println("client started");

        int noOfConnectionsToPerform = 1 << 17;
        System.out.println("performing " + noOfConnectionsToPerform + " connections");
        for (int n = 0; n < noOfConnectionsToPerform; n++) {
            // send a request
            ChannelFuture f = client.getBootstrap().connect("localhost", port);
        }
        System.out.println("client performed " + noOfConnectionsToPerform + " connections");

        System.out.println("wait a bit to give a chance for server to finish processing incoming requests");
        Thread.currentThread().sleep(80000);

        System.out.println("shutting down server and client");
        server.stop();
        client.stop();

        System.out.println("stopped, server received: " + server.connectionsCount() + " connections");
        int numberOfLostConnections = noOfConnectionsToPerform - server.connectionsCount();
        if (numberOfLostConnections > 0) {
            System.out.println("Where do we lost " + numberOfLostConnections + " connections?");
        }

        System.out.println("srerver exceptions: ");
        printExceptions(server.getExceptions());
        System.out.println("client exceptions: ");
        printExceptions(client.getExceptions());
    }

    private static void printExceptions(Map<String, Integer> exceptions) {
        if (exceptions.isEmpty()) {
            System.out.println("There was no exceptions");
        }
        for (Entry<String, Integer> exception : exceptions.entrySet()) {
            System.out.println("There was " + exception.getValue() + " times this exception:");
            System.out.println(exception.getKey());
        }
    }

    public static class NettyServer {
        private ChannelFuture channelFuture;
        private EventLoopGroup bossGroup;
        private EventLoopGroup workerGroup;
        private AtomicInteger connections = new AtomicInteger(0);
        private ExceptionCounter exceptionCounter = new ExceptionCounter();

        public NettyServer(int port) throws InterruptedException {
            bossGroup = new NioEventLoopGroup();
            workerGroup = new NioEventLoopGroup();
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new TimeServerHandler() {

                                @Override
                                public void channelActive(final ChannelHandlerContext ctx) {
                                    connections.incrementAndGet();
                                    super.channelActive(ctx);
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                    exceptionCounter.countException(cause);
                                    super.exceptionCaught(ctx, cause);
                                }

                            });
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
            channelFuture = serverBootstrap.bind(port).sync();
        }

        public int getPort() {
            return ((InetSocketAddress) channelFuture.channel().localAddress()).getPort();
        }

        public int connectionsCount() {
            return connections.get();
        }

        public Map<String, Integer> getExceptions() {
            return exceptionCounter.getExceptions();
        }

        public void stop() {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            try {
                bossGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
                workerGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static class NettyClient {
        private Bootstrap bootstrap;
        private EventLoopGroup workerGroup;
        private ExceptionCounter exceptionCounter = new ExceptionCounter();

        public NettyClient() {
            workerGroup = new NioEventLoopGroup();

            bootstrap = new Bootstrap();
            bootstrap.group(workerGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new TimeClientHandler() {
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                            exceptionCounter.countException(cause);
                            super.exceptionCaught(ctx, cause);
                        }
                    });
                }
            });
        }

        public Bootstrap getBootstrap() {
            return bootstrap;
        }

        public void stop() {
            workerGroup.shutdownGracefully();
            try {
                workerGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public Map<String, Integer> getExceptions() {
            return exceptionCounter.getExceptions();
        }
    }

    public static class TimeServerHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelActive(final ChannelHandlerContext ctx) {
            final ByteBuf time = ctx.alloc().buffer(4);
            time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));

            final ChannelFuture f = ctx.writeAndFlush(time);
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) {
                    assert f == future;
                    ctx.close();
                }
            });
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            ctx.close();
        }
    }

    public static class TimeClientHandler extends ChannelInboundHandlerAdapter {
        private ThreadLocal<ByteBuf> buf = new ThreadLocal<ByteBuf>();

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) {
            buf.set(ctx.alloc().buffer(4));
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) {
            buf.get().release();
            buf.remove();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ByteBuf m = (ByteBuf) msg;
            buf.get().writeBytes(m);
            m.release();

            if (buf.get().readableBytes() >= 4) {
                long currentTimeMillis = (buf.get().readUnsignedInt() - 2208988800L) * 1000L;
                ctx.close();
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            ctx.close();
        }
    }

    public static class ExceptionCounter {
        private ConcurrentHashMap<String, AtomicInteger> exceptions = new ConcurrentHashMap<String, AtomicInteger>();

        private void countException(Throwable cause) {

            StringWriter writer = new StringWriter();
            cause.printStackTrace(new PrintWriter(writer));
            String stackTrace = writer.toString();

            AtomicInteger exceptionCount = exceptions.get(stackTrace);
            if (exceptionCount == null) {
                exceptionCount = new AtomicInteger(0);
                AtomicInteger prevCount = exceptions.putIfAbsent(stackTrace, exceptionCount);
                if (prevCount != null) {
                    exceptionCount = prevCount;
                }
            }
            exceptionCount.incrementAndGet();
        }

        public Map<String, Integer> getExceptions() {
            Map<String, Integer> newMap = exceptions.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get()));
            return Collections.unmodifiableMap(newMap);
        }
    }
}

The output is:

starting server
server started at port: 56069
staring client
client started
performing 131072 connections
client performed 131072 connections
wait a bit to give a chance for server to finish processing incoming requests
shutting down server and client
stopped, server received: 34735 connections
Where do we lost 96337 connections?
srerver exceptions:
There was no exceptions
client exceptions:
There was 258 times this exception:
java.io.IOException: Istniejące połączenie zostało gwałtownie zamknięte przez zdalnego hosta
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
    at sun.nio.ch.IOUtil.read(IOUtil.java:192)
    at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
    at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
    at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100)
    at io.netty.buffer.WrappedByteBuf.writeBytes(WrappedByteBuf.java:813)
    at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:372)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:123)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
    at java.lang.Thread.run(Thread.java:745)

There was 30312 times this exception:
java.io.IOException: Istniejące połączenie zostało gwałtownie zamknięte przez zdalnego hosta
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
    at sun.nio.ch.IOUtil.read(IOUtil.java:192)
    at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
    at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
    at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100)
    at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:372)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:123)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
    at java.lang.Thread.run(Thread.java:745)

Questions:

Why this exception is thrown?

Where the lost connections has gone? Why there is no error for them?

How to avoid it, what is the correct way to program this kind of "high throughput" application to not have such problems like loosing/breaking existing connections?

No related to subject, but maybe some Netty expert will know: Why when I change in TimeClientHandler the field declaration of private ThreadLocal<ByteBuf> buf to be also static, I have null pointer exception in TimeClientHandler.handlerRemoved? This is very strange, is this class somehow replicated? or are the Threads from NioEventLoopGroup somehow strange?

Environment:

Netty version: netty-all-4.1.12.Final.jar

JVM version: jdk1.8.0_111 64 bit

OS version: Windows 10 64 bit


来源: stackexchange

问:
How to display two different type of images in SSRS report for a Boolean field
I am working on a SSRS report. I have a field called IsAllergic in database which could be 1, 0 or NULL. The business requirement is Yes and No side by side in report. If Yes then show a checked image infront of Yes and unchecked infront of No.
I have tried the following.
For the Yes checkbox under Use this image I use the below query:

```<code>=switch(Fields!IsAllergic .Value <> 1, "unchecked", Fields!IsAllergic .Value = 1, "checked")
</code>```

I have set the Visibility when the report initially run to "Show".

For the No checkbox under Use this image I use the below query:

```<code>=switch(Fields!IsAllergic Value <> 1, "checked", Fields!IsAllergic .Value = 1, "unchecked")
</code>```

For this checkbox also I have set the Visibility when the report initially run to "Show".

When I run the report I get the opposite result. Yes shows an unchecked checkbox image and No shows checked checkbox.
What am I missing here?
Been looking at this for hours and help is appreciated!

答:
I ended up using IIf instead of switch.
Below is what I did.

```<code>=IIf(Fields!IsAllergic.Value <> True, "checked", "unchecked")
</code>```

This handles NULLs too. If IsAllergic is NULL or 0 then it shows unchecked checkbox and for true it shows checked chkbox.

ContentLicense: CC BY-SA 3.0

Body:
I am working on a SSRS report. I have a field called IsAllergic in database which could be 1, 0 or NULL. The business requirement is Yes and No side by side in report. If Yes then show a checked image infront of Yes and unchecked infront of No.
I have tried the following.
For the Yes checkbox under Use this image I use the below query:

=switch(Fields!IsAllergic .Value <> 1, "unchecked", Fields!IsAllergic .Value = 1, "checked")

I have set the Visibility when the report initially run to "Show".

For the No checkbox under Use this image I use the below query:

=switch(Fields!IsAllergic Value <> 1, "checked", Fields!IsAllergic .Value = 1, "unchecked")

For this checkbox also I have set the Visibility when the report initially run to "Show".

When I run the report I get the opposite result. Yes shows an unchecked checkbox image and No shows checked checkbox.
What am I missing here?
Been looking at this for hours and help is appreciated!

Body:
I ended up using IIf instead of switch.
Below is what I did.

=IIf(Fields!IsAllergic.Value <> True, "checked", "unchecked")

This handles NULLs too. If IsAllergic is NULL or 0 then it shows unchecked checkbox and for true it shows checked chkbox.


问:
mina deploy undefined method set_default
I have been trying to upgrade our app from Rails 3 to Rails 4.2.4 and have everything working minus being able to deploy. I can run rails server and console correctly, but run into an issue on the deploy.

The exact error is:

mina aborted!
NoMethodError: undefined method `set_default' for main:Object
path/config/deploy.rb:6:in `require'
path/config/deploy.rb:6:in `<top (required)>'
path/.rbenv/versions/2.1.3/bin/mina:23:in `load'
path/.rbenv/versions/2.1.3/bin/mina:23:in `<top (required)>'
path/.rbenv/versions/2.1.3/bin/bundle:23:in `load'
path/.rbenv/versions/2.1.3/bin/bundle:23:in `'

deploy.rb file

require 'mina/bundler'
require 'mina/rails'
require 'mina/git'
require 'mina/rbenv'
require 'mina_sidekiq/tasks'
require 'mina/unicorn' #line 6

Gemfile

gem 'mina'
gem 'mina-sidekiq', :require => false
gem 'mina-unicorn', :require => false

The only thing I was able to find was the :require => false in the Gemfile, which we already had.

Any ideas on where to investigate from here?

答:
mina-sidekiq has been updated and version 1.0 now requires Mina 1.0. Also fixes this issue :)

ref.: https://github.com/Mic92/mina-sidekiq

```<code>bundle update mina-sidekiq
</code>```

Body:
mina-sidekiq has been updated and version 1.0 now requires Mina 1.0. Also fixes this issue :)

ref.: https://github.com/Mic92/mina-sidekiq

bundle update mina-sidekiq


问:
Anaconda installation problems - how to uninstall Anaconda (Windows)
I recently tried installing Anaconda for my Windows 10 laptop. Unfortunately, this didn't seem to work, as there seems to be no actual Anaconda application on my computer, rather just a collection of folders and files on my desktop. I think this problem can be attributed to me downloading the 32-bit version of Anaconda while my OS is 64-bit, though I am not sure this was the problem. Regardless, I would now like to uninstall Anaconda from my computer. How would I go about uninstalling Anaconda from Windows despite Anaconda not fully downloading and only consisting of various folders on my desktop. I'm not super computer-savvy so typing in commands directly into the console seems a bit intimidating.

答:
There also is a

Uninstall-Anaconda.exe

directly in your Anaconda folder. But I'm not sure if it does something more than just deleting the folder/files.


问:
Is there any option to edit default netsuite calendar
I want to count number of weeks e.g 03-07-2017 to 09-07-2017 is 1st week and to the calendar view just as given in the picture. Is there any option to do it through scripting or functionally

答:
It's not hard to calculate with time. Take a look at moment.js, you have a lot of date/time functionality there.

But you don't specify what you actually want to do. Do you want to number the weeks from the beginning of the year, ISO style? Do you want to number the weeks within a specific month? If so, what is your definition of what is the first week? I am making a guess from your illustration that you count the first week where all days fall within the current week is week 1. But do you start your week on Sunday or Monday?
Or do you actually want to display the week number in the calendar, like in the illustration? Unless you create your own date picker, I am pretty sure that is not possible.


问:
Difference between int a[5],int a[], int a[]={2,3} in Java
How could we statically declare array? Can't it be by int a[5];?

```<code>package oops;

public class exception {
    int arr1[] = new int[10];

    public static void main(String args[]){
        int a[] ={1,9};
        int[] a ;
        int a[9];
        a[0]=10;
    }
}
</code>```

答:
int a[] = {1,9} is an array of two elements 1 and 9
int[] a is declaring an integer array called a.  Not initialized. int a[9] is an array containing nine elements.  Not initialized
int[0]=10 places the value 10 in position 0 on the array

Body:
How could we statically declare array? Can't it be by int a[5];?

package oops;

public class exception {
    int arr1[] = new int[10];

    public static void main(String args[]){
        int a[] ={1,9};
        int[] a ;
        int a[9];
        a[0]=10;
    }
}


问:
Connect to VPN by Powershell
I'd like my Windows to connect to the VPN server as soon as it loads. How can I do it using Powershell?</p>

答:
Try this works with windows 10</p>

```<code>    $vpnName = "YOUR_VPN_NAME";
    $vpn = Get-VpnConnection -Name $vpnName;
    if($vpn.ConnectionStatus -eq "Disconnected"){
    rasdial $vpnName;
    }
</code>```

Title: Connect to VPN by Powershell

Body:
Try this works with windows 10

    $vpnName = "YOUR_VPN_NAME";
    $vpn = Get-VpnConnection -Name $vpnName;
    if($vpn.ConnectionStatus -eq "Disconnected"){
    rasdial $vpnName;
    }


问:
Bixolon sdk encoding characters_android
I would like to print characters like č, ć, š to be precise Croatian characters. I am using Bixolon sdk for SPP-R200II printer.
The code is very simple for now, just want to print some string

```<code> ListaRacuna.mBixolonPrinter.printText(slanjeNaPrinter, BixolonPrinter.ALIGNMENT_LEFT, 0,     BixolonPrinter.TEXT_SIZE_HORIZONTAL1 | BixolonPrinter.TEXT_SIZE_VERTICAL1, false);
                        ListaRacuna.mBixolonPrinter.lineFeed(1, false);

                        ListaRacuna.mBixolonPrinter.cutPaper(true);
</code>```

with connection to the printer via bluetooth.

答:
CODE_PAGE_858_EURO is okay for Spanish characters, but not for Eastern European ČŠŽĐ.

The proposed solution is not working for me properly. After a lot of searching, I have come up with a solution.

Set code page that suport Slavic characters:
xx.mBixolonPrinter.setSingleByteFont(BixolonPrinter.CODE_PAGE_852_LATIN2);

Use a function to covert Slavic characters to something bixolon spp r400 will understand understand:
xx.mBixolonPrinter.printDotMatrixText(SloConvText, alignment, attribute, size, false);

where SloConvText is:
SloConvText = ReplaceSloChar(s_textLine,ConvString);

And the key solution, ReplaceSloChar (without \u0003 is not okay, uses two bytes instead, both Korean signs)

```<code>public static String ReplaceSloChar(String inString, String ConvString) {

    String S1 = inString.replaceAll("Č","\u010C\u0003");
    String S2 = S1.replaceAll("Š","\u0160\u0003");
    String S3 = S2.replaceAll("Ž","\u017D\u0003");

    String S4 = S3.replaceAll("č","\u010D\u0003");
    String S5 = S4.replaceAll("š","\u0161\u0003");
    ConvString = S5.replaceAll("ž","\u017E\u0003");

    return ConvString;
}
</code>```

It is overhead, but sending čšž in any form to bixolon spp r400 is not working at all.

Title: Bixolon sdk encoding characters_android

Body:
I would like to print characters like č, ć, š to be precise Croatian characters. I am using Bixolon sdk for SPP-R200II printer.
The code is very simple for now, just want to print some string

 ListaRacuna.mBixolonPrinter.printText(slanjeNaPrinter, BixolonPrinter.ALIGNMENT_LEFT, 0,     BixolonPrinter.TEXT_SIZE_HORIZONTAL1 | BixolonPrinter.TEXT_SIZE_VERTICAL1, false);
                        ListaRacuna.mBixolonPrinter.lineFeed(1, false);

                        ListaRacuna.mBixolonPrinter.cutPaper(true);

with connection to the printer via bluetooth.

Body:
CODE_PAGE_858_EURO is okay for Spanish characters, but not for Eastern European ČŠŽĐ.

The proposed solution is not working for me properly. After a lot of searching, I have come up with a solution.

Set code page that suport Slavic characters:
xx.mBixolonPrinter.setSingleByteFont(BixolonPrinter.CODE_PAGE_852_LATIN2);

Use a function to covert Slavic characters to something bixolon spp r400 will understand understand:
xx.mBixolonPrinter.printDotMatrixText(SloConvText, alignment, attribute, size, false);

where SloConvText is:
SloConvText = ReplaceSloChar(s_textLine,ConvString);

And the key solution, ReplaceSloChar (without \u0003 is not okay, uses two bytes instead, both Korean signs)

public static String ReplaceSloChar(String inString, String ConvString) {

    String S1 = inString.replaceAll("Č","\u010C\u0003");
    String S2 = S1.replaceAll("Š","\u0160\u0003");
    String S3 = S2.replaceAll("Ž","\u017D\u0003");

    String S4 = S3.replaceAll("č","\u010D\u0003");
    String S5 = S4.replaceAll("š","\u0161\u0003");
    ConvString = S5.replaceAll("ž","\u017E\u0003");

    return ConvString;
}

It is overhead, but sending čšž in any form to bixolon spp r400 is not working at all.


问:
Xpath get the parent tag with the child tag
I am scraping a website and the website does not have the information organized in a good way like there are sometimes fields called "Transmission" and "Engine type" and sometimes those does not exist and the problem is everything is inside each p tags, with a span tag with the Title like Transmission and  Engine Type

here you can understand it better if i show you

Sometimes there are certain fields and sometimes there isn't

Here engine type and transmission is present in vehicle information

Here engine type and transmission is not present in vehicle information

and there isn't any concrete way to map the fields for all pages
Fields gets switched cause if i try to reach the engine type text with this xpath

```<code>'.//div[@id="result"]/div[@class="details"][2]/p[2]/text()'
</code>```

maximum time i get different value cause the values in the p tags gets switched around so sometime i get transmission with this xpath and sometimes i get engine type with this xpath

so i was thinking is their a way to get the desired fields with the span titles right beside them ?

like this

```<code><div class="details">
    <p><span class="label">Chassis/VIN #:</span>017S</p>
    <p><span class="label">Displacement:</span>0 </p>
    <p><span class="label">Odometer:</span>79,111</p>
    <p><span class="label">Condition:</span><a href="#condition-rating">2-</a>
    </p>
    <p><span class="label">Body Style:</span>coupe</p>
</div>
</code>```

Every p tag has a span tag as a title, is there a way to get the p tag data with the span tag title ?

so for example i can get p tag's text engine type with the span tag title text engine type ?

there is a way to get a item by text in xpath like this

```<code>"//*[contains(text(), 'The Text Associated With The Element')]/text()"
</code>```

is there a way to implement something like this here ?

答:
You can get list of Title/Value pairs with:

```<code>//div[@class="details"]/p//text()
</code>```

Output:

```<code>Chassis/VIN #:
017S
Displacement:
0
Odometer:
79,111
Condition:
2-
Body Style:
coupe
</code>```

If you want to get specific value by title, e.g. by "Odometer:":

```<code>//div[@class="details"]/p[span="Odometer:"]/text()
</code>```

Output:

```<code>79,111
</code>```

Body:
I am scraping a website and the website does not have the information organized in a good way like there are sometimes fields called "Transmission" and "Engine type" and sometimes those does not exist and the problem is everything is inside each p tags, with a span tag with the Title like Transmission and  Engine Type

here you can understand it better if i show you

Sometimes there are certain fields and sometimes there isn't

Here engine type and transmission is present in vehicle information

Here engine type and transmission is not present in vehicle information

and there isn't any concrete way to map the fields for all pages
Fields gets switched cause if i try to reach the engine type text with this xpath

'.//div[@id="result"]/div[@class="details"][2]/p[2]/text()'

maximum time i get different value cause the values in the p tags gets switched around so sometime i get transmission with this xpath and sometimes i get engine type with this xpath

so i was thinking is their a way to get the desired fields with the span titles right beside them ?

like this

Chassis/VIN #:017S

Displacement:0

Odometer:79,111

Condition:2-

Body Style:coupe

Every p tag has a span tag as a title, is there a way to get the p tag data with the span tag title ?

so for example i can get p tag's text engine type with the span tag title text engine type ?

there is a way to get a item by text in xpath like this

"//*[contains(text(), 'The Text Associated With The Element')]/text()"

is there a way to implement something like this here ?

Body:
You can get list of Title/Value pairs with:

//div[@class="details"]/p//text()

Output:

Chassis/VIN #:
017S
Displacement:
0
Odometer:
79,111
Condition:
2-
Body Style:
coupe

If you want to get specific value by title, e.g. by "Odometer:":

//div[@class="details"]/p[span="Odometer:"]/text()

Output:

79,111


问:
Get string from a list contain Unicode in JavaScript
I have a list of Unicode values [65, 66, 67] and I want the corresponding string "ABC". I looked into the documentation and found the function String.fromCharCode()that does what I need to do. The only problem is that the arguments needs to be a sequence of numbers.

So if I use String.fromCharCode([65, 66, 67]) it gives me " ".

Is there a way that allows the list to be treated as a sequence for a function?

答:
you can use apply to solve this

var chars = [65,66,67]
var s = String.fromCharCode.apply({}, chars)
console.log(s);```

ContentLicense: CC BY-SA 4.0


问:
rails button_tag vs. button_to - class & id
I am trying to build a button with an id and a class with rails. A javascript event fires when the button get clicked. I tried different things none of them ticks all the boxes.

```<code>  <%= button_tag "Launch the js event", id: "button-feedback-by-bullet" %>
</code>```

This works but there is no class

```<code>  <%= button_tag "Launch the js event", id: "button-feedback-by-bullet", class: "btn-primary" %>
</code>```

I get an error saying there are too many arguments

```<code>  <%= button_to "Launch the js event", id: "button-feedback-by-bullet", class: "btn-primary" %>
</code>```

I get the right class but the button pass a post method and the js event does not get fired

Could you please help me find the right syntax and understand nuances between button_tag and button_to? Thanks.

答:
button_tag(content_or_options = nil, options = nil, &block) public

You should do

```<code><%= button_tag "Launch the js event", {id: "button-feedback-by-bullet", class: "btn-primary"} %>
</code>```

or with button_to

button_to(name = nil, options = nil, html_options = nil, &block)

```<code><%= button_to "Launch the js event", {}, {id: "button-feedback-by-bullet", class: "btn-primary"} %>
</code>```

Also, button_tag or button_to triggers a submit by default, perhaps you should use link_to instead

Body:
I am trying to build a button with an id and a class with rails. A javascript event fires when the button get clicked. I tried different things none of them ticks all the boxes.

  <%= button_tag "Launch the js event", id: "button-feedback-by-bullet" %>

This works but there is no class

  <%= button_tag "Launch the js event", id: "button-feedback-by-bullet", class: "btn-primary" %>

I get an error saying there are too many arguments

  <%= button_to "Launch the js event", id: "button-feedback-by-bullet", class: "btn-primary" %>

I get the right class but the button pass a post method and the js event does not get fired

Could you please help me find the right syntax and understand nuances between button_tag and button_to? Thanks.

Body:
button_tag(content_or_options = nil, options = nil, &block) public

You should do

<%= button_tag "Launch the js event", {id: "button-feedback-by-bullet", class: "btn-primary"} %>

or with button_to

button_to(name = nil, options = nil, html_options = nil, &block)

<%= button_to "Launch the js event", {}, {id: "button-feedback-by-bullet", class: "btn-primary"} %>

Also, button_tag or button_to triggers a submit by default, perhaps you should use link_to instead


问:
Stored Procedure set parameter based on other parameters input
Trying to create a stored procedure in SQL 2008R2.
I have two Parameter inputs, that depending on their input, will ideally set another parameter's value to one of four values.  Trying to determine if this can done, and if so, where is the best place to put it in the SP.
Here is a slimmed down version of my code.

```<code>Declare @FWIdle as bYN, @NewComp as bYN

set @FW = 'Y'
set @NEW = 'Y'

select Case(
when w.WearRate <0.400 then round((- 50*w.WearRate+112.5),2
when w.WearRate <0.450 then round((-100*w.WearRate+132.5),2)
when w.WearRate <0.550 then round((- 50*w.WearRate+110.5),2)
else 52.5 END as Score

from EMWear w
</code>```

Hoping to replace all w.WearRate with @Wear and setting @Wear to one of four possible fields in the view, based on the combination of the two parameters.

So something like:

```<code>if @FW = 'Y' and @NEW = 'N' then @Wear = w.FWRate else
if @FW = 'N' and @NEW = 'Y' then @Wear = w.NewRate else
if @FW = 'Y' and @NEW = 'Y' then @Wear = w.FWNewRate else
@Wear = w.WearRate
</code>```

Since I have 150+ lines of code that deals with this rate, I would prefer not to have to write this code 4 times to get the desired Value. Any help on how I can write this and keep it clean/simple would be greatly appreciated.

答:
The solution to my problem ended up being to create a temp table and insert the WearRate that I wanted to use.</p>

```<code>If OBJECT_ID('tempdb.dbo.#TempWear','U') IS NOT NULL
Drop Table #TempWear;

Create Table #TempWear
    EMCo tinyint Null,
    Component varchar(10) NULL,
    CompType varchar(10) NULL,
    WearRate decimal(38,5) NULL
    );

if @FW = 'Y' and @New = 'Y'
Begin
    Insert into #TempWear
    (EMCo, Component, CompType, WearRate)
    select w.EMCo, w.Component,w.CompType, w.FwIdleWearRate
    from bcvEMCompWearAdj w
END
else
if @FW = 'Y' and @New = 'N'
Begin
    Insert into #TempWear
    (EMCo, Component, CompType, WearRate)
    select w.EMCo, w.Component,w.CompType, w.FwWearRate
    from bcvEMCompWearAdj w
END
else
if @FW = 'N' and @New = 'Y'
Begin
    Insert into #TempWear
    (EMCo, Component, CompType, WearRate)
    sselect w.EMCo, w.Component,w.CompType, w.IdleWearRate
    from bcvEMCompWearAdj w
END
else
--if @FW = 'N' and @New = 'N'
Begin
    Insert into #TempWear
    (EMCo, Component, CompType, WearRate)
    select w.EMCo, w.Component,w.CompType, w.StdWearRate
    from bcvEMCompWearAdj w
END
</code>```

Body:
Trying to create a stored procedure in SQL 2008R2.
I have two Parameter inputs, that depending on their input, will ideally set another parameter's value to one of four values.  Trying to determine if this can done, and if so, where is the best place to put it in the SP.
Here is a slimmed down version of my code.

Declare @FWIdle as bYN, @NewComp as bYN

set @FW = 'Y'
set @NEW = 'Y'

select Case(
when w.WearRate <0.400 then round((- 50*w.WearRate+112.5),2
when w.WearRate <0.450 then round((-100*w.WearRate+132.5),2)
when w.WearRate <0.550 then round((- 50*w.WearRate+110.5),2)
else 52.5 END as Score

from EMWear w

Hoping to replace all w.WearRate with @Wear and setting @Wear to one of four possible fields in the view, based on the combination of the two parameters.

So something like:

if @FW = 'Y' and @NEW = 'N' then @Wear = w.FWRate else
if @FW = 'N' and @NEW = 'Y' then @Wear = w.NewRate else
if @FW = 'Y' and @NEW = 'Y' then @Wear = w.FWNewRate else
@Wear = w.WearRate

Since I have 150+ lines of code that deals with this rate, I would prefer not to have to write this code 4 times to get the desired Value. Any help on how I can write this and keep it clean/simple would be greatly appreciated.

Body:
The solution to my problem ended up being to create a temp table and insert the WearRate that I wanted to use.

If OBJECT_ID('tempdb.dbo.#TempWear','U') IS NOT NULL
Drop Table #TempWear;

Create Table #TempWear
    EMCo tinyint Null,
    Component varchar(10) NULL,
    CompType varchar(10) NULL,
    WearRate decimal(38,5) NULL
    );

if @FW = 'Y' and @New = 'Y'
Begin
    Insert into #TempWear
    (EMCo, Component, CompType, WearRate)
    select w.EMCo, w.Component,w.CompType, w.FwIdleWearRate
    from bcvEMCompWearAdj w
END
else
if @FW = 'Y' and @New = 'N'
Begin
    Insert into #TempWear
    (EMCo, Component, CompType, WearRate)
    select w.EMCo, w.Component,w.CompType, w.FwWearRate
    from bcvEMCompWearAdj w
END
else
if @FW = 'N' and @New = 'Y'
Begin
    Insert into #TempWear
    (EMCo, Component, CompType, WearRate)
    sselect w.EMCo, w.Component,w.CompType, w.IdleWearRate
    from bcvEMCompWearAdj w
END
else
--if @FW = 'N' and @New = 'N'
Begin
    Insert into #TempWear
    (EMCo, Component, CompType, WearRate)
    select w.EMCo, w.Component,w.CompType, w.StdWearRate
    from bcvEMCompWearAdj w
END


问:
zsh alias to remove all docker containers returns command not found
I have this alias in my .zshrc file:

```<code>alias rmcons="docker rm -f $(docker ps -aq)"
</code>```

But after trying to execute it, it removes only one container and then it prints

```<code>$rmcons
ef8197f147fb
zsh: command not found: c2ea2673f9e4
zsh: command not found: 4603059f1618
zsh: command not found: 40ad60328595
</code>```

How can I remove all containers that docker ps -aq shows?

答:
You need to use single quotes ('') instead of double quotes ("").

```<code>alias rmcons='docker rm -f $(docker ps -aq)'
</code>```

If you use double quotes, than the command substitution $(docker ps -aq) will be evaluated when you define the alias. In your example this was equivalent to

```<code>alias rmcons="docker rm -f ef8197f147fb
c2ea2673f9e4
4603059f1618
40ad60328595"
</code>```

As the newlines are command separators (like ;) this alias is substituted by  four commands: docker rm -f ef8197f147fb, c2ea2673f9e4, 4603059f1618 and 40ad60328595. The last three of which do not exist on your system, hence "command not found". It also means that the same output of docker ps -aq - as it was on alias definiton - will be used and not as it would be when running the alias.

On the other hand, if you use single quotes, the alias will actually substituted by the exact command you defined: docker rm -f $(docker ps -aq). Although docker ps -aq will still return output with newlines, these newlines are now only parsed word separators between arguments.

Body:
I have this alias in my .zshrc file:

alias rmcons="docker rm -f $(docker ps -aq)"

But after trying to execute it, it removes only one container and then it prints

$rmcons
ef8197f147fb
zsh: command not found: c2ea2673f9e4
zsh: command not found: 4603059f1618
zsh: command not found: 40ad60328595

How can I remove all containers that docker ps -aq shows?

Body:
You need to use single quotes ('') instead of double quotes ("").

alias rmcons='docker rm -f $(docker ps -aq)'

If you use double quotes, than the command substitution $(docker ps -aq) will be evaluated when you define the alias. In your example this was equivalent to

alias rmcons="docker rm -f ef8197f147fb
c2ea2673f9e4
4603059f1618
40ad60328595"

As the newlines are command separators (like ;) this alias is substituted by  four commands: docker rm -f ef8197f147fb, c2ea2673f9e4, 4603059f1618 and 40ad60328595. The last three of which do not exist on your system, hence "command not found". It also means that the same output of docker ps -aq - as it was on alias definiton - will be used and not as it would be when running the alias.

On the other hand, if you use single quotes, the alias will actually substituted by the exact command you defined: docker rm -f $(docker ps -aq). Although docker ps -aq will still return output with newlines, these newlines are now only parsed word separators between arguments.


问:
How do I get child elements from class list object?
think I have some class of same content

```<code> <div class="parentclass">

         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
    </div>

  <div class="parentclass">

         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
    </div>
</code>```

I can get all the parent class object in an array by

```<code>var pClassList= document.getElementsByClassName("parentclass");
</code>```

My question is how can I access the child classes "childClass" from pClassList array calling it index like

```<code>var childClassList1= pClassList[0].getElementsByClassName("childClass");
var childClassList2= pClassList[1].getElementsByClassName("childClass");
</code>```

答:
The following will retrieve child nodes with classname="childClass" for the first element in pClassList array:

```<code>for (var i = 0; i < pClassList[0].childNodes.length; i++) {
if (pClassList[0].childNodes[i].className == "childClass") {
  //Do something with pClassList[0].childNodes[i]
}
}
</code>```

You can do the same for the rest of the elements in pClassList array by iterating over each of them.

Body:
think I have some class of same content

I can get all the parent class object in an array by

var pClassList= document.getElementsByClassName("parentclass");

My question is how can I access the child classes "childClass" from pClassList array calling it index like

var childClassList1= pClassList[0].getElementsByClassName("childClass");
var childClassList2= pClassList[1].getElementsByClassName("childClass");

Body:
The following will retrieve child nodes with classname="childClass" for the first element in pClassList array:

for (var i = 0; i < pClassList[0].childNodes.length; i++) {
if (pClassList[0].childNodes[i].className == "childClass") {
  //Do something with pClassList[0].childNodes[i]
}
}

You can do the same for the rest of the elements in pClassList array by iterating over each of them.


问:
When to delete pointer in try-catch block
Quick best-practice question (note I am not allowed to use any smart pointers in this code). I am under the impression that if I pass a pointer to a function and an exceptional case occurs, then the memory is leaked if it's never deleted in either the called function or the function in which the memory was first allocated. Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?

Example:

```<code>int main() {
  object* myPtr = new object(); //dynamic memory on heap
  foo(*myPtr);  //pass pointer to function foo

  return 0;
}

void foo(object &pointer) {
  try {
    /* do stuff here
    with the pointer */
  }
  catch (const char &e) {
    cout<< "An error occured: " << e << endl;
  }
  catch (...)
    cout<< "Caught unknown exception." << endl;
  }
}
</code>```

Should I delete the pointer after the function returns?

```<code> int main() {
      object* myPtr = new object(); //dynamic memory on heap
      foo(*myPtr);  //pass pointer to function foo
      delete myPtr;

      return 0;
    }
</code>```

Or in the try-catch blocks?

```<code>void foo(object &pointer) {
      try {
        /* do stuff here
        with the pointer */
      }
      catch (const char &e) {
        cout<< "An error occured: " << e << endl;
        delete &pointer;
      }
      catch (...)
        cout<< "Caught unknown exception." << endl;
        delete &pointer;
      }
    }
</code>```

答:
I am under the impression that if I pass a pointer to a function and an exceptional case occurs, then the memory is leaked if it's never deleted in either the called function or the function in which the memory was first allocated.

It is not required that the memory be freed in the same function that allocated it.  But yes, in general, if the pointer is pointing at memory that was allocated with new then it is leaked if delete is never called on it at all, regardless of where that is actually called.

Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?

In your example, foo() has no concept of how the object is allocated, so no, it is not safe to call delete inside of foo().

For example, you could call foo() using one of this instead, all of which would have problems if foo() called delete:

```<code>int main() {
    object myObj;
    foo(myObj);
    return 0;
}
</code>```

```<code>int main() {
    std::unique_ptr<object> myPtr(new object);
    foo(*myPtr);
    return 0;
}
</code>```

```<code>int main() {
    std::vector<char> buffer(sizeof(object));
    object *myPtr = new (&buffer[0]) object;
    foo(*myPtr);
    myPtr->~object();
    return 0;
}
</code>```

From foo's perspective, it doesn't matter  how the object is allocated, as long as it is a valid object instance going into foo().  Since main() decides how the object is allocated, main() should be the one to decide how to free it correctly, if at all.

Body:
Quick best-practice question (note I am not allowed to use any smart pointers in this code). I am under the impression that if I pass a pointer to a function and an exceptional case occurs, then the memory is leaked if it's never deleted in either the called function or the function in which the memory was first allocated. Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?

Example:

int main() {
  object* myPtr = new object(); //dynamic memory on heap
  foo(*myPtr);  //pass pointer to function foo

  return 0;
}

void foo(object &pointer) {
  try {
    /* do stuff here
    with the pointer */
  }
  catch (const char &e) {
    cout<< "An error occured: " << e << endl;
  }
  catch (...)
    cout<< "Caught unknown exception." << endl;
  }
}

Should I delete the pointer after the function returns?

 int main() {
      object* myPtr = new object(); //dynamic memory on heap
      foo(*myPtr);  //pass pointer to function foo
      delete myPtr;

      return 0;
    }

Or in the try-catch blocks?

void foo(object &pointer) {
      try {
        /* do stuff here
        with the pointer */
      }
      catch (const char &e) {
        cout<< "An error occured: " << e << endl;
        delete &pointer;
      }
      catch (...)
        cout<< "Caught unknown exception." << endl;
        delete &pointer;
      }
    }

Body:
I am under the impression that if I pass a pointer to a function and an exceptional case occurs, then the memory is leaked if it's never deleted in either the called function or the function in which the memory was first allocated.

It is not required that the memory be freed in the same function that allocated it.  But yes, in general, if the pointer is pointing at memory that was allocated with new then it is leaked if delete is never called on it at all, regardless of where that is actually called.

Is it safe to delete the memory in the catch blocks or should I delete the memory in the calling function?

In your example, foo() has no concept of how the object is allocated, so no, it is not safe to call delete inside of foo().

For example, you could call foo() using one of this instead, all of which would have problems if foo() called delete:

int main() {
    object myObj;
    foo(myObj);
    return 0;
}

int main() {
    std::unique_ptr<object> myPtr(new object);
    foo(*myPtr);
    return 0;
}

int main() {
    std::vector<char> buffer(sizeof(object));
    object *myPtr = new (&buffer[0]) object;
    foo(*myPtr);
    myPtr->~object();
    return 0;
}

From foo's perspective, it doesn't matter  how the object is allocated, as long as it is a valid object instance going into foo().  Since main() decides how the object is allocated, main() should be the one to decide how to free it correctly, if at all.


问:
How to achieve this scrolling effect in Bootstrap?
How do I achieve this scrolling effect in Boostrap? Have a fixed image background with the content div overlayed on top when scrolling:

http://www.standardhotels.com/culture/things-to-do-july-2017-new-york-los-angeles-miami

答:
There are several ways you could achieve this. You could fix a background image to html and offset the body, adding padding to keep text in the viewport. For example:

```<code>html {
  background: url(DESIRED BACKGROUND IMAGE) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

body {
  background:lightblue;
  padding-left:150px;
  padding-right: 30px;
  position:relative;
  left:-150px;
  top:80%;
}
</code>```

Check out this basic (but very cute) kitten example.

EDIT

Looking further into your example's code, you could also add margin-top to the body and remove the positioning top. Your example shows margin-top: calc(100vh - 140px) !important;

Here's an updated version of my fiddle with the properties swapped. You can see that the effect is very similar.

Body:
There are several ways you could achieve this. You could fix a background image to html and offset the body, adding padding to keep text in the viewport. For example:

html {
  background: url(DESIRED BACKGROUND IMAGE) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

body {
  background:lightblue;
  padding-left:150px;
  padding-right: 30px;
  position:relative;
  left:-150px;
  top:80%;
}

Check out this basic (but very cute) kitten example.

EDIT

Looking further into your example's code, you could also add margin-top to the body and remove the positioning top. Your example shows margin-top: calc(100vh - 140px) !important;

Here's an updated version of my fiddle with the properties swapped. You can see that the effect is very similar.


问:
How can I get source code of a method dynamically and also which file is this method locate in
I would like to know whether I can get source code a method on the fly, and whether I can get which file is this method in.

like

```<code>A.new.method(:a).SOURCE_CODE
A.new.method(:a).FILE
</code>```

答:
Internal methods don't have source or source location (e.g. Integer#to_s)

```<code>require 'method_source'
User.method(:last).source
User.method(:last).source_location
</code>```

Body:
I would like to know whether I can get source code a method on the fly, and whether I can get which file is this method in.

like

A.new.method(:a).SOURCE_CODE
A.new.method(:a).FILE

Body:
Internal methods don't have source or source location (e.g. Integer#to_s)

require 'method_source'
User.method(:last).source
User.method(:last).source_location


问:
SQLException: incorrect syntax near '2'
whenever I call the "ExecuteNonQuery" command on the following CommandText, I get the above SQLException

```<code>myCommand.CommandText = "INSERT INTO fixtures (round_id, matchcode, date_utc, time_utc, date_london, time_london, team_A_id, team_A, team_A_country, team_B_id, team_B, team_B_country, status, gameweek, winner, fs_A, fs_B, hts_A, hts_B, ets_A, ets_B, ps_A, ps_B, last_updated) VALUES (" _
            & round_id & "," & match_id & "," & date_utc & ",'" & time_utc & "'," & date_london & ",'" & time_london & "'," & team_A_id & ",'" & team_A_name & "','" & team_A_country & "'," & team_B_id & ",'" & team_B_name & "','" & _
            team_B_country & "','" & status & "'," & gameweek & ",'" & winner & "'," & fs_A & "," & fs_B & "," & hts_A & "," & hts_B & "," & ets_A & "," & ets_B & "," & ps_A & "," & ps_B & "," & last_updated & ")"
</code>```

But whenever, i remove the last table item - "last_updated", the error disappears. Please help me resolve this issue. Is there any special treatment to be given to datetime fields???

Thanks for your help

答: You need to use parameters.</p>

ContentLicense: CC BY-SA 2.5

Title: SQLException: incorrect syntax near '2'

Body:
whenever I call the "ExecuteNonQuery" command on the following CommandText, I get the above SQLException

myCommand.CommandText = "INSERT INTO fixtures (round_id, matchcode, date_utc, time_utc, date_london, time_london, team_A_id, team_A, team_A_country, team_B_id, team_B, team_B_country, status, gameweek, winner, fs_A, fs_B, hts_A, hts_B, ets_A, ets_B, ps_A, ps_B, last_updated) VALUES (" _
            & round_id & "," & match_id & "," & date_utc & ",'" & time_utc & "'," & date_london & ",'" & time_london & "'," & team_A_id & ",'" & team_A_name & "','" & team_A_country & "'," & team_B_id & ",'" & team_B_name & "','" & _
            team_B_country & "','" & status & "'," & gameweek & ",'" & winner & "'," & fs_A & "," & fs_B & "," & hts_A & "," & hts_B & "," & ets_A & "," & ets_B & "," & ps_A & "," & ps_B & "," & last_updated & ")"

But whenever, i remove the last table item - "last_updated", the error disappears. Please help me resolve this issue. Is there any special treatment to be given to datetime fields???

Thanks for your help

Body: You need to use parameters.


问:
Change certain value in all unique keys
So I am trying to code http trigger function which would change the certain value in every unique key (user id). I have written something but the output is not what I need. Instead of changing existing values, it creates new user id.

```<code>const functions = require('firebase-functions')
const admin = require('firebase-admin')

admin.initializeApp(functions.config().firebase)

exports.picksReset = functions.https.onRequest((req, res) => {

  const ref = admin.database().ref()

  const usersPicked = []

  ref.child('users').once('value').then(snap => {
    snap.forEach(childSnap => {

      ref.child('/users/{userId}').push({picksDone: "0"})
      console.log("Changing value...")

    })
  })

  res.send("Done!")

})
</code>```

An image of my database...

答:
Using .push() creates a new child with a pushId. Instead, use .update(). See details in the documentation here. If you're looking to change the child picksDone in each user, you can do so like this:

```<code>const functions = require('firebase-functions')
const admin = require('firebase-admin')

admin.initializeApp(functions.config().firebase)

exports.picksReset = functions.https.onRequest((req, res) => {

  const ref = admin.database().ref()

  const usersPicked = []

  ref.child('users').once('value').then(snap => {
    snap.forEach(childSnap => {
      const key = childSnap.key
      ref.child(`users/${key}`).update({picksDone: "0"})
      console.log("Changing value...")

    })
  })
  res.send("Done!")
})
</code>```

Title: Change certain value in all unique keys

Body:
So I am trying to code http trigger function which would change the certain value in every unique key (user id). I have written something but the output is not what I need. Instead of changing existing values, it creates new user id.

const functions = require('firebase-functions')
const admin = require('firebase-admin')

admin.initializeApp(functions.config().firebase)

exports.picksReset = functions.https.onRequest((req, res) => {

  const ref = admin.database().ref()

  const usersPicked = []

  ref.child('users').once('value').then(snap => {
    snap.forEach(childSnap => {

      ref.child('/users/{userId}').push({picksDone: "0"})
      console.log("Changing value...")

    })
  })

  res.send("Done!")

})

An image of my database...

Body:
Using .push() creates a new child with a pushId. Instead, use .update(). See details in the documentation here. If you're looking to change the child picksDone in each user, you can do so like this:

const functions = require('firebase-functions')
const admin = require('firebase-admin')

admin.initializeApp(functions.config().firebase)

exports.picksReset = functions.https.onRequest((req, res) => {

  const ref = admin.database().ref()

  const usersPicked = []

  ref.child('users').once('value').then(snap => {
    snap.forEach(childSnap => {
      const key = childSnap.key
      ref.child(`users/${key}`).update({picksDone: "0"})
      console.log("Changing value...")

    })
  })
  res.send("Done!")
})


问:
Load json into javascript
So I have a json html link that like below

```<code>www.pretendJsonLink.com/getData
</code>```

and the data i receive is below:

```<code>{"Items":[{"date":1498850140373,"displayId":"003","sentId":"121213",
"customer":"ME"}, {"date":1452870140571,"displayId":"007","sentId":"152713",
"customer":"YOU"}],"Count":2,"ScannedCount":2}
</code>```

I need to load this into a js file  so i can then call them as needed in a html file in an id="" tag

Like Items.date and Items.customer or something like it

Any help would be great and I understand that this should be a simple task, but i can also forward my search history as well :) i have been looking for solutions that work, but just cant seem to find anything that fits my needs

答:
You can use XMLHttpRequest . I found a gist that gives a good example and included it (simplified), below:</p>

```<code>var req = new XMLHttpRequest();
req.open('GET', 'www.pretendJsonLink.com/getData');

req.onload = function() {
    if (req.status == 200) {
      // do what you want, here, with the req.response
      // take a look at the object that gets returned, you may need
      // to call JSON.parse(), etc.
      console.log('success', req.response);
    } else {
      console.log('error', req.statusText);
    }
};

// Handle network errors
req.onerror = function() {
    console.log("Network Error");
};

// Make the request
req.send();
</code>```

Title: Load json into javascript

Body:
So I have a json html link that like below

www.pretendJsonLink.com/getData

and the data i receive is below:

{"Items":[{"date":1498850140373,"displayId":"003","sentId":"121213",
"customer":"ME"}, {"date":1452870140571,"displayId":"007","sentId":"152713",
"customer":"YOU"}],"Count":2,"ScannedCount":2}

I need to load this into a js file  so i can then call them as needed in a html file in an id="" tag

Like Items.date and Items.customer or something like it

Any help would be great and I understand that this should be a simple task, but i can also forward my search history as well :) i have been looking for solutions that work, but just cant seem to find anything that fits my needs

Body:
You can use XMLHttpRequest . I found a gist that gives a good example and included it (simplified), below:

var req = new XMLHttpRequest();
req.open('GET', 'www.pretendJsonLink.com/getData');

req.onload = function() {
    if (req.status == 200) {
      // do what you want, here, with the req.response
      // take a look at the object that gets returned, you may need
      // to call JSON.parse(), etc.
      console.log('success', req.response);
    } else {
      console.log('error', req.statusText);
    }
};

// Handle network errors
req.onerror = function() {
    console.log("Network Error");
};

// Make the request
req.send();


问:
Setup.exe and autorun.inf
I have Visual Studio 2008 project on which I added a Setup Project. It generates all files to install the application correctly.

Now I am trying to add an autorun.inf to the cd, which is supposed to start the Setup.exe.
After a lot of attempts and every combinations possible, nothing works, the install don't start. I even tried a batch file which start Setup.exe but no use.

Is there something I missing, because double-clicking on it works.

答:
My two cents...

Did you begun you autorun.inf file with [autorun] ?

Any trailing empty lines at the end of the autorun.inf file ?

Are you sure autorun is activated on that CD drive ?

Did you respect the syntax : open=filename.exe /param1

Are your CD drive on the network (Windows will probably not allow a program to self execute on the intranet).

You have probably already checked all this twice. Best luck.

OwnerDisplayName: Sébastien Lachance

Title: Setup.exe and autorun.inf

LastEditorDisplayName: Jon B

OwnerDisplayName: Sylvain Rodrigue

LastEditorDisplayName: mmyers


问:
Given a file, find the ten most frequently occurring words as efficiently as possible
This is apparently an interview question (found it in a collection of interview questions), but even if it's not it's pretty cool.

We are told to do this efficiently on all complexity measures. I thought of creating a HashMap that maps the words to their frequency. That would be O(n) in time and space complexity, but since there may be lots of words we cannot assume that we can store everything in memory.

I must add that nothing in the question says that the words cannot be stored in memory, but what if that were the case? If that's not the case, then the question does not seem as challenging.

答:
I think the trie data structure is a choice.

In the trie, you can record word count in each node representing frequency of word consisting of characters on the path from root to current node.

The time complexity to setup the trie is O(Ln) ~ O(n) (where L is number of characters in the longest word, which we can treat as a constant). To find the top 10 words, we can traversal the trie, which also costs O(n). So it takes O(n) to solve this problem.


问:
How to minify ES6 functions with gulp-uglify?
When I run gulp I get the following error:

```<code>[12:54:14] { [GulpUglifyError: unable to minify JavaScript]
cause:
{ [SyntaxError: Unexpected token: operator (>)]
 message: 'Unexpected token: operator (>)',
 filename: 'bundle.js',
 line: 3284,
 col: 46,
 pos: 126739 },
plugin: 'gulp-uglify',
fileName: 'C:\\servers\\vagrant\\workspace\\awesome\\web\\tool\\bundle.js',
showStack: false }
</code>```

The offending line contains an arrow function:

```<code>let zeroCount = numberArray.filter(v => v === 0).length
</code>```

I know I can replace it with the following to remedy the minification error by abandoning ES6 syntax:

```<code>let zeroCount = numberArray.filter(function(v) {return v === 0;}).length
</code>```

How can I minify code containing ES6 features via gulp?

答:
unfortunately, as per now, you can't use uglify with es-next code,
you can:

Transpile to ES5using Babel

Use Babili instead of Uglify.

Body:
When I run gulp I get the following error:

[12:54:14] { [GulpUglifyError: unable to minify JavaScript]
cause:
{ [SyntaxError: Unexpected token: operator (>)]
 message: 'Unexpected token: operator (>)',
 filename: 'bundle.js',
 line: 3284,
 col: 46,
 pos: 126739 },
plugin: 'gulp-uglify',
fileName: 'C:\\servers\\vagrant\\workspace\\awesome\\web\\tool\\bundle.js',
showStack: false }

The offending line contains an arrow function:

let zeroCount = numberArray.filter(v => v === 0).length

I know I can replace it with the following to remedy the minification error by abandoning ES6 syntax:

let zeroCount = numberArray.filter(function(v) {return v === 0;}).length

How can I minify code containing ES6 features via gulp?


答:
You can leverage gulp-babel as such...

```<code>const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

gulp.task('minify', () => {
  return gulp.src('src/**/*.js')
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(uglify())
    // [...]
});
</code>```

This will transpile your es6 early in the pipeline and churn out as widely supported "plain" javascript by the time you minify.

May be important to note - as pointed out in comments - the core babel compiler ships as a peer dependency in this plugin. In case the core lib is not being pulled down via another dep in your repo, ensure this is installed on your end.

Looking at the peer dependency in gulp-babel the author is specifying @babel/core (7.x). Though, the slightly older babel-core (6.x) will work as well. My guess is the author (who is the same for both projects) is in the midsts of reorganizing their module naming. Either way, both npm installation endpoints point to https://github.com/babel/babel/tree/master/packages/babel-core, so you'll be fine with either of the following...

```<code>npm install babel-core --save-dev
</code>```

or

```<code>npm install @babel/core --save-dev
</code>```

Title: How to minify ES6 functions with gulp-uglify?

Body:
You can leverage gulp-babel as such...

const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

gulp.task('minify', () => {
  return gulp.src('src/**/*.js')
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(uglify())
    // [...]
});

This will transpile your es6 early in the pipeline and churn out as widely supported "plain" javascript by the time you minify.

May be important to note - as pointed out in comments - the core babel compiler ships as a peer dependency in this plugin. In case the core lib is not being pulled down via another dep in your repo, ensure this is installed on your end.

Looking at the peer dependency in gulp-babel the author is specifying @babel/core (7.x). Though, the slightly older babel-core (6.x) will work as well. My guess is the author (who is the same for both projects) is in the midsts of reorganizing their module naming. Either way, both npm installation endpoints point to https://github.com/babel/babel/tree/master/packages/babel-core, so you'll be fine with either of the following...

npm install babel-core --save-dev

or

npm install @babel/core --save-dev


问:
Git: New pull request from the same branch still shows previous commits
I forked a repo on github, then I did git checkout X and made some changes to branch X. After finishing up,  I made a pull request from branch X of the forked repo to branch X of the original repo.

My changes got merged with branch X of the original repo, then I made some more changes and made another pull request from my branch X to original repo's branch X. However, this still shows my previously merged commits as under,

Here, commits made till Jul 05, 2017 have already been merged to branch X of the original repo. I only need the commits on Jul 06 to show up on this pull request. After trying for quite some time I'm unable to find a solution. Here's what I did based on this post,

 setup new upstream like so -

git remote add upstream https://path/to/original/repo.git

 fetch changes to update my forked repo - git fetch upstream

 rebase onto branch X - git rebase X

However, now I see an even bigger list of commits staged for the pull request. I'm sure I don't fully understand how pull requests work but I'm assuming this is because my forked repo does not know that previous commits have already been merged.

I know the usual workflow should be to fork the repo, make a new branch for every change, make a pull request, delete the branch once changes have been merged. I wasn't aware of that and stumbled on this problem. How do I only include the newly (un-merged) commits in the pull request, and not all the previous ones as well?

答:
One way is to cherry-pick the commits from a fresh new branch from upstream:

```<code>git fetch upstream X:X_new
git checkout X_new
git cherry-pick 92495c5
git cherry-pick ...
</code>```

You can then open a new pull request. If you want to keep the same pull-request, you will need to rename it to the old name, and force push to your repo:

```<code>git checkout X
git checkout -b X_backup
git branch -D X
git checkout X_new
git checkout -b X
git push origin X -f
</code>```

and then if it fits your need, you can delete the other branches:

```<code>git branch -D X_backup
git branch -D X_new
</code>```

Body:
One way is to cherry-pick the commits from a fresh new branch from upstream:

git fetch upstream X:X_new
git checkout X_new
git cherry-pick 92495c5
git cherry-pick ...

You can then open a new pull request. If you want to keep the same pull-request, you will need to rename it to the old name, and force push to your repo:

git checkout X
git checkout -b X_backup
git branch -D X
git checkout X_new
git checkout -b X
git push origin X -f

and then if it fits your need, you can delete the other branches:

git branch -D X_backup
git branch -D X_new


答:
If you take a look at the value of myCommand.CommandText in the debugger after the strings have been concatenated I think it will be easy to see the problem. My guess is that you probably need quotes around the value of your datetime:

```<code>... & ",'" & last_updated & "')"
</code>```

You may also need to specify the format used to convert the DateTime to a string, for example last_updated.ToString("yyyy-MM-dd HH:mm:ss").

However it would be better to use parameterized queries, as pointed out in the comments. Then things will just work.

Title: SQLException: incorrect syntax near '2'

Body:
If you take a look at the value of myCommand.CommandText in the debugger after the strings have been concatenated I think it will be easy to see the problem. My guess is that you probably need quotes around the value of your datetime:

... & ",'" & last_updated & "')"

You may also need to specify the format used to convert the DateTime to a string, for example last_updated.ToString("yyyy-MM-dd HH:mm:ss").

However it would be better to use parameterized queries, as pointed out in the comments. Then things will just work.


问:
How to properly write query SELECT'ing multiple tables
please advise on query below. I want to select multiple tables. entryId is from table stockTracking. I bet i should use JOIN or smt.. Cheers!

```<code>$updateEntryId  = $_GET["entryId"];
$query          = "SELECT *
                   FROM stockTracking, loggers, boxes
                   WHERE entryId ='$updateEntryId'";
$result         = mysqli_query($connection, $query);
</code>```

table

```<code>boxes|boxId boxQuantity boxName
        2           10      CL64

loggers | loggerId loggerQuantity loggerName
              2         10           34242342
stockTracking| entryId  time        destination reference
              2        timestamp        Paris       1312
</code>```

I have updated query to following, however what wrong with my WHERE statement?
As i add WHERE entryId='$updateEntryId' if fails to display any results

```<code>$updateEntryId  = $_GET["entryId"];
$query          = "SELECT *
               FROM stockTracking
               JOIN loggers
               ON entryId=loggerId
               JOIN boxes
               ON boxId=entryId
               WHERE entryId='$updateEntryId'";
</code>```

答:
Yes, you are right. You should perform a JOIN operation among-st the tables like below. replace some_column in below sample sql code with your actual column name on which you have relationship between the tables

```<code>SELECT s.*
FROM stockTracking s
JOIN loggers l ON s.some_column = l.some_column
JOIN boxes b ON b.some_column = s.some_column
WHERE s.entryId ='$updateEntryId'
</code>```

Body:
please advise on query below. I want to select multiple tables. entryId is from table stockTracking. I bet i should use JOIN or smt.. Cheers!

$updateEntryId  = $_GET["entryId"];
$query          = "SELECT *
                   FROM stockTracking, loggers, boxes
                   WHERE entryId ='$updateEntryId'";
$result         = mysqli_query($connection, $query);

table

boxes|boxId boxQuantity boxName
        2           10      CL64

loggers | loggerId loggerQuantity loggerName
              2         10           34242342
stockTracking| entryId  time        destination reference
              2        timestamp        Paris       1312

I have updated query to following, however what wrong with my WHERE statement?
As i add WHERE entryId='$updateEntryId' if fails to display any results

$updateEntryId  = $_GET["entryId"];
$query          = "SELECT *
               FROM stockTracking
               JOIN loggers
               ON entryId=loggerId
               JOIN boxes
               ON boxId=entryId
               WHERE entryId='$updateEntryId'";

Body:
Yes, you are right. You should perform a JOIN operation among-st the tables like below. replace some_column in below sample sql code with your actual column name on which you have relationship between the tables

SELECT s.*
FROM stockTracking s
JOIN loggers l ON s.some_column = l.some_column
JOIN boxes b ON b.some_column = s.some_column
WHERE s.entryId ='$updateEntryId'


问:
Get data in Main class using Observer pattern
I'm getting JSON data from a remote API. For this I'm using the Observer pattern. I created an Observer called WordTranslationObserver that gets the JSON data from the callback method. The problem is that I don't know how to get this data in the Main class...

In my Main class I can't implement PropertyChangeListener and use a translationModel.addChangeListener(this) because I'm in a static context, so "this" can't work.

What is the proper way to be able to get my data from translation.getText() in my Main class ?

Main class

```<code>public class Main    {
    public static void main(String[] args) throws IOException {

        WordTranslation wordTranslation = new WordTranslation();
        WordTranslationObserver myObserver = new WordTranslationObserver(wordTranslation);
        wordTranslation.translate("sắt", "vie", "eng");

    }
}
</code>```

Observer

```<code>public class WordTranslationObserver implements PropertyChangeListener {
    public WordTranslationObserver(WordTranslation translationModel) {
        translationModel.addChangeListener(this);
    }

    @Override
    public void propertyChange(PropertyChangeEvent event) {
        System.out.println("Changed property: " + event.getPropertyName());
        ArrayList<Translation> translations = (ArrayList<Translation>) event.getNewValue();

        // Print recieved data from JSON to the console
        // I want to be able to get translation.getText() in my Main class
        for (Translation translation : translations) {
            System.out.println(translation.getText());
        }
    }
}
</code>```

Data

```<code>public class WordTranslation {
    public static final String TRANSLATIONS = "translations";
    private static final String BASE_URL = "http://deu.hablaa.com/hs/translation/";
    private List<PropertyChangeListener> listener = new ArrayList<PropertyChangeListener>();
    ArrayList<Translation> translations;

     public void addChangeListener(PropertyChangeListener newListener) {
            listener.add(newListener);
     }

     public void notifyListeners(String property, Translation[] translationArray) {
            translations = new ArrayList<>();
            // TODO Auto-generated method stub
            for (Translation t : translationArray) {
                translations.add(t);
            }
            for (PropertyChangeListener name : listener) {
                name.propertyChange(new PropertyChangeEvent(this, "translations", null, translations));
        }
    }

     public void translate(String word, String from, String to) {
            final Translation[][] translations = new Translation[1][1];

            String url = String.format("%s%s/%s-%s",BASE_URL, word, from, to);//  args) "http://xxx";
        System.out.println(url);
        final Gson gson = new Gson();

        // should be a singleton
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                             .url(url)
                             .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                translations[0] = gson.fromJson(response.body().charStream(),Translation[].class);
                notifyListeners(TRANSLATIONS,translations[0]);

            }
            });

        }

}
</code>```

答:
You could have an observer set static variables if you really wanted to, that could be polled for changes but this would defeat the principle of using the observer pattern which is event driven.

Perhaps there is some specific reason why you want this information available in the main class but I would be more inclined to offload any processing onto observers as you have already (cleanly) done, adding new implementations as you need them.

If you just want the information available to your main class (not necessarily in a static context), have your Main class implement PropertyChangeListener and register a new Main() with your WorldTranslation in the same way you have done with the WorldTranslationObserver.

HTH

Body:
I'm getting JSON data from a remote API. For this I'm using the Observer pattern. I created an Observer called WordTranslationObserver that gets the JSON data from the callback method. The problem is that I don't know how to get this data in the Main class...

In my Main class I can't implement PropertyChangeListener and use a translationModel.addChangeListener(this) because I'm in a static context, so "this" can't work.

What is the proper way to be able to get my data from translation.getText() in my Main class ?

Main class

public class Main    {
    public static void main(String[] args) throws IOException {

        WordTranslation wordTranslation = new WordTranslation();
        WordTranslationObserver myObserver = new WordTranslationObserver(wordTranslation);
        wordTranslation.translate("sắt", "vie", "eng");

    }
}

Observer

public class WordTranslationObserver implements PropertyChangeListener {
    public WordTranslationObserver(WordTranslation translationModel) {
        translationModel.addChangeListener(this);
    }

    @Override
    public void propertyChange(PropertyChangeEvent event) {
        System.out.println("Changed property: " + event.getPropertyName());
        ArrayList<Translation> translations = (ArrayList<Translation>) event.getNewValue();

        // Print recieved data from JSON to the console
        // I want to be able to get translation.getText() in my Main class
        for (Translation translation : translations) {
            System.out.println(translation.getText());
        }
    }
}

Data

public class WordTranslation {
    public static final String TRANSLATIONS = "translations";
    private static final String BASE_URL = "http://deu.hablaa.com/hs/translation/";
    private List<PropertyChangeListener> listener = new ArrayList<PropertyChangeListener>();
    ArrayList<Translation> translations;

     public void addChangeListener(PropertyChangeListener newListener) {
            listener.add(newListener);
     }

     public void notifyListeners(String property, Translation[] translationArray) {
            translations = new ArrayList<>();
            // TODO Auto-generated method stub
            for (Translation t : translationArray) {
                translations.add(t);
            }
            for (PropertyChangeListener name : listener) {
                name.propertyChange(new PropertyChangeEvent(this, "translations", null, translations));
        }
    }

     public void translate(String word, String from, String to) {
            final Translation[][] translations = new Translation[1][1];

            String url = String.format("%s%s/%s-%s",BASE_URL, word, from, to);//  args) "http://xxx";
        System.out.println(url);
        final Gson gson = new Gson();

        // should be a singleton
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                             .url(url)
                             .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                translations[0] = gson.fromJson(response.body().charStream(),Translation[].class);
                notifyListeners(TRANSLATIONS,translations[0]);

            }
            });

        }

}