问:
Waiting on Interlocked == 0?
Disclaimer: My C# isn't even close to as good as my C++

I am trying to learn how to do async sockets in C# in order to write a test app for a component of mine. My former attempts using TcpClient ended in failure and you can read the outstanding questions on that here:

TcpClient.NetworkStream Async operations - Canceling / Disconnect

Detect errors with NetworkStream.WriteAsync

Since, I could not get that working, I tried using Socket.BeginX and Socket.EndX instead. I got much further along. My problem now is that in the listing below, when it comes time to disconnect, which in turn calls shutdown and close on the socket, async operations are still outstanding and they will throw an object disposed exception or an object is set to null exception.

I found a similar post about that here:

After disposing async socket (.Net) callbacks still get called

However, I do not accept that answer, because if you are using exceptions for intended behavior, then 1) They are not exceptional 2) You cannot tell if the exception was thrown for your intended case or if it was thrown because you actually used a disposed object or a null reference in your async method, other than the socket.

In C++ with async socket code, I'd keep track of the number of outstanding async operations with Interlocked and when it came time to disconnect, I'd call shutdown, then wait for the interlocked to hit 0, and then close and destroy any members I needed to.

How would I go about waiting in my Disconnect method for all outstanding Async operations to complete in C# in the following listing?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using log4net;
using System.Net.Sockets;
using System.Net;

namespace IntegrationTests
{
    public class Client2
    {
        class ReceiveContext
        {
            public Socket    m_socket;
            public const int m_bufferSize = 1024;
            public byte[]    m_buffer = new byte[m_bufferSize];
        }

        private static readonly ILog log = LogManager.GetLogger("root");

        static private ulong m_lastId = 1;

        private ulong  m_id;
        private string m_host;
        private uint   m_port;
        private uint   m_timeoutMilliseconds;
        private string m_clientId;
        private Socket m_socket;
        private uint   m_numOutstandingAsyncOps;

        public Client2(string host, uint port, string clientId, uint timeoutMilliseconds)
        {
            m_id                     = m_lastId++;
            m_host                   = host;
            m_port                   = port;
            m_clientId              = clientId;
            m_timeoutMilliseconds    = timeoutMilliseconds;
            m_socket                 = null;
            m_numOutstandingAsyncOps = 0;
        }

        ~Client2()
        {
            Disconnect();
        }

        public void Connect()
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry(m_host);
            IPAddress[] ipV4Addresses = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).ToArray();
            IPAddress[] ipV6Addresses = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetworkV6).ToArray();
            IPEndPoint endpoint = new IPEndPoint(ipV4Addresses[0], (int)m_port);

            m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_socket.ReceiveTimeout = (int)m_timeoutMilliseconds;
            m_socket.SendTimeout    = (int)m_timeoutMilliseconds;

            try
            {
                m_socket.Connect(endpoint);

                log.Info(string.Format("Connected to: {0}", m_socket.RemoteEndPoint.ToString()));

                // Issue the next async receive
                ReceiveContext context = new ReceiveContext();
                context.m_socket = m_socket;
                m_socket.BeginReceive(context.m_buffer, 0, ReceiveContext.m_bufferSize, SocketFlags.None, new AsyncCallback(OnReceive), context);
            }
            catch (Exception e)
            {
                // Error
                log.Error(string.Format("Client #{0} Exception caught OnConnect. Exception: {1}"
                                       , m_id, e.ToString()));
            }
        }

        public void Disconnect()
        {
            if (m_socket != null)
            {
                m_socket.Shutdown(SocketShutdown.Both);

                // TODO - <--- Error here in the callbacks where they try to use the socket and it is disposed
                //        We need to wait here until all outstanding async operations complete
                //        Should we use Interlocked to keep track of them and wait on it somehow?
                m_socket.Close();
                m_socket = null;
            }
        }

        public void Login()
        {
            string loginRequest = string.Format("loginstuff{0})", m_clientId);
            var data = Encoding.ASCII.GetBytes(loginRequest);

            m_socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(OnSend), m_socket);
        }

        public void MakeRequest(string thingy)
        {
            string message = string.Format("requeststuff{0}", thingy);
            var data = Encoding.ASCII.GetBytes(message);

            m_socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(OnSend), m_socket);
        }

        void OnReceive(IAsyncResult asyncResult)
        {
            ReceiveContext context = (ReceiveContext)asyncResult.AsyncState;

            string data = null;
            try
            {
                int bytesReceived = context.m_socket.EndReceive(asyncResult);
                data = Encoding.ASCII.GetString(context.m_buffer, 0, bytesReceived);

                ReceiveContext newContext = new ReceiveContext();
                newContext.m_socket = context.m_socket;

                m_socket.BeginReceive(newContext.m_buffer, 0, ReceiveContext.m_bufferSize, SocketFlags.None, new AsyncCallback(OnReceive), newContext);
            }
            catch(SocketException e)
            {
                if(e.SocketErrorCode == SocketError.ConnectionAborted) // Check if we disconnected on our end
                {
                    return;
                }
            }
            catch (Exception e)
            {
                // Error
                log.Error(string.Format("Client #{0} Exception caught OnReceive. Exception: {1}"
                                       , m_id, e.ToString()));
            }
        }

        void OnSend(IAsyncResult asyncResult)
        {
            Socket socket = (Socket)asyncResult.AsyncState;

            try
            {
                int bytesSent = socket.EndSend(asyncResult);
            }
            catch(Exception e)
            {
                log.Error(string.Format("Client #{0} Exception caught OnSend. Exception: {1}"
                                       , m_id, e.ToString()));
            }
        }
    }
}
</code>```

Main:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using log4net;
using log4net.Config;

namespace IntegrationTests
{
    class Program
    {
        private static readonly ILog log = LogManager.GetLogger("root");

        static void Main(string[] args)
        {
            try
            {
                XmlConfigurator.Configure();
                log.Info("Starting Component Integration Tests...");

                Client2 client = new Client2("127.0.0.1", 24001, "MyClientId", 60000);
                client.Connect();
                client.Login();
                client.MakeRequest("StuffAndPuff");

                System.Threading.Thread.Sleep(60000); // Sim work until user shutsdown

                client.Disconnect();
            }
            catch (Exception e)
            {
                log.Error(string.Format("Caught an exception in main. Exception: {0}"
                                      , e.ToString()));
            }
        }
    }
}
</code>```

EDIT:

Here is my additional attempt using the answer proposed by Evk, to the best of my ability. It works fine as far as I can tell.

Problem with this is, that I feel like I basically made everything that was asynchronous into a synchronous call, because of the requirements to lock around anything that would change the counter or the state of the socket. Again, I am novice at C# compared to my C++, so please do point out if I completely missed the mark interpreting his answer.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IntegrationTests
{
    public class Client
    {
        class ReceiveContext
        {
            public const int     _bufferSize    = 1024;
            public byte[]        _buffer        = new byte[_bufferSize]; // Contains bytes from one receive
            public StringBuilder _stringBuilder = new StringBuilder();   // Contains bytes for multiple receives in order to build message up to delim
        }

        private static readonly ILog _log = LogManager.GetLogger("root");

        static private ulong _lastId = 1;
        private ulong  _id;

        protected string         _host;
        protected int            _port;
        protected int            _timeoutMilliseconds;
        protected string         _sessionId;
        protected Socket         _socket;
        protected object         _lockNumOutstandingAsyncOps;
        protected int            _numOutstandingAsyncOps;
        private bool             _disposed = false;

        public Client(string host, int port, string sessionId, int timeoutMilliseconds)
        {
            _id                         = _lastId++;
            _host                       = host;
            _port                       = port;
            _sessionId                  = sessionId;
            _timeoutMilliseconds        = timeoutMilliseconds;
            _socket                     = null;
            _numOutstandingAsyncOps     = 0;
            _lockNumOutstandingAsyncOps = new object();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if(_disposed)
            {
                return;
            }

            if (disposing)
            {
                _socket.Close();
            }

            _disposed = true;
        }

        public void Connect()
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                IPHostEntry ipHostInfo = Dns.GetHostEntry(_host);
                IPAddress[] ipV4Addresses = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).ToArray();
                IPAddress[] ipV6Addresses = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetworkV6).ToArray();
                IPEndPoint endpoint = new IPEndPoint(ipV4Addresses[0], _port);

                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.ReceiveTimeout = _timeoutMilliseconds;
                _socket.SendTimeout = _timeoutMilliseconds;

                try
                {
                    _socket.Connect(endpoint);
                }
                catch (Exception e)
                {
                    // Error
                    Debug.WriteLine(string.Format("Client #{0} Exception caught OnConnect. Exception: {1}"
                                           , _id, e.ToString()));
                    return;
                }

                Debug.WriteLine(string.Format("Client #{0} connected to: {1}", _id, _socket.RemoteEndPoint.ToString()));

                // Issue the first async receive
                ReceiveContext context = new ReceiveContext();

                ++_numOutstandingAsyncOps;
                _socket.BeginReceive(context._buffer, 0, ReceiveContext._bufferSize, SocketFlags.None, new AsyncCallback(OnReceive), context);
            }
        }

        public void Disconnect()
        {
            if (_socket != null)
            {
                // We need to wait here until all outstanding async operations complete
                // In order to avoid getting 'Object was disposed' exceptions in those async ops that use the socket
                lock(_lockNumOutstandingAsyncOps)
                {
                    Debug.WriteLine(string.Format("Client #{0} Disconnecting...", _id));

                    _socket.Shutdown(SocketShutdown.Both);

                    while (_numOutstandingAsyncOps > 0)
                    {
                        Monitor.Wait(_lockNumOutstandingAsyncOps);
                    }

                    _socket.Close();
                    _socket = null;
                }
            }
        }

        public void Login()
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                if (_socket != null && _socket.Connected)
                {
                    string loginRequest = string.Format("loginstuff{0}", _clientId);
                    var data = Encoding.ASCII.GetBytes(loginRequest);

                    Debug.WriteLine(string.Format("Client #{0} Sending Login Request: {1}"
                                           , _id, loginRequest));

                    ++_numOutstandingAsyncOps;
                    _socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(OnSend), _socket);
                }
                else
                {
                    Debug.WriteLine(string.Format("Client #{0} Login was called, but Socket is null or no longer connected."
                                           , _id));
                }
            }
        }

        public void MakeRequest(string thingy)
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                if (_socket != null && _socket.Connected)
                {
                    string message = string.Format("requeststuff{0}", thingy);
                    var data = Encoding.ASCII.GetBytes(message);

                    Debug.WriteLine(string.Format("Client #{0} Sending Request: {1}"
                                           , _id, message));

                    ++_numOutstandingAsyncOps;
                    _socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(OnSend), _socket);
                }
                else
                {
                    Debug.WriteLine(string.Format("Client #{0} MakeRequest was called, but Socket is null or no longer connected."
                                           , _id));
                }
            }
        }

        protected void OnReceive(IAsyncResult asyncResult)
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                ReceiveContext context = (ReceiveContext)asyncResult.AsyncState;

                string data = null;

                try
                {
                    int bytesReceived = _socket.EndReceive(asyncResult);
                    data = Encoding.ASCII.GetString(context._buffer, 0, bytesReceived);

                    // If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received,
                    // the EndReceive method will complete immediately and return zero bytes
                    if (bytesReceived > 0)
                    {
                        StringBuilder stringBuilder = context._stringBuilder.Append(data);

                        int index = -1;
                        do
                        {
                            index = stringBuilder.ToString().IndexOf("#");
                            if (index != -1)
                            {
                                string message = stringBuilder.ToString().Substring(0, index + 1);
                                stringBuilder.Remove(0, index + 1);

                                Debug.WriteLine(string.Format("Client #{0} Received Data: {1}"
                                                       , _id, message));
                            }
                        } while (index != -1);
                    }
                }
                catch (SocketException e)
                {
                    // Check if we disconnected on our end
                    if (e.SocketErrorCode == SocketError.ConnectionAborted)
                    {
                        // Ignore
                    }
                    else
                    {
                        // Error
                        Debug.WriteLine(string.Format("Client #{0} SocketException caught OnReceive. Exception: {1}"
                                               , _id, e.ToString()));
                        Disconnect();
                    }
                }
                catch (Exception e)
                {
                    // Error
                    Debug.WriteLine(string.Format("Client #{0} Exception caught OnReceive. Exception: {1}"
                                           , _id, e.ToString()));
                    Disconnect();
                }
                finally
                {
                    --_numOutstandingAsyncOps;
                    Monitor.Pulse(_lockNumOutstandingAsyncOps);
                }
            }

            // Issue the next async receive
            lock (_lockNumOutstandingAsyncOps)
            {
                if (_socket != null && _socket.Connected)
                {
                    ++_numOutstandingAsyncOps;

                    ReceiveContext newContext = new ReceiveContext();
                    _socket.BeginReceive(newContext._buffer, 0, ReceiveContext._bufferSize, SocketFlags.None, new AsyncCallback(OnReceive), newContext);
                }
            }
        }

        protected void OnSend(IAsyncResult asyncResult)
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                try
                {
                    int bytesSent = _socket.EndSend(asyncResult);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(string.Format("Client #{0} Exception caught OnSend. Exception: {1}"
                                           , _id, e.ToString()));
                    Disconnect();
                }
                finally
                {
                    --_numOutstandingAsyncOps;
                    Monitor.Pulse(_lockNumOutstandingAsyncOps);
                }
            }
        }
    }
}
</code>```

答:
You can use Monitor.Wait and Monitor.Pulse for that:

```<code>static int _outstandingOperations;
static readonly object _lock = new object();
static void Main() {
    for (int i = 0; i < 100; i++) {
        var tmp = i;
        Task.Run(() =>
        {
            lock (_lock) {
                _outstandingOperations++;
            }
            // some work
            Thread.Sleep(new Random(tmp).Next(0, 5000));
            lock (_lock) {
                _outstandingOperations--;
                // notify condition might have changed
                Monitor.Pulse(_lock);
            }
        });
    }

    lock (_lock) {
        // condition check
        while (_outstandingOperations > 0)
            // will wait here until pulsed, lock will be released during wait
            Monitor.Wait(_lock);
    }
}
</code>```

Title: Waiting on Interlocked == 0?

Body:
Disclaimer: My C# isn't even close to as good as my C++

I am trying to learn how to do async sockets in C# in order to write a test app for a component of mine. My former attempts using TcpClient ended in failure and you can read the outstanding questions on that here:

TcpClient.NetworkStream Async operations - Canceling / Disconnect

Detect errors with NetworkStream.WriteAsync

Since, I could not get that working, I tried using Socket.BeginX and Socket.EndX instead. I got much further along. My problem now is that in the listing below, when it comes time to disconnect, which in turn calls shutdown and close on the socket, async operations are still outstanding and they will throw an object disposed exception or an object is set to null exception.

I found a similar post about that here:

After disposing async socket (.Net) callbacks still get called

However, I do not accept that answer, because if you are using exceptions for intended behavior, then 1) They are not exceptional 2) You cannot tell if the exception was thrown for your intended case or if it was thrown because you actually used a disposed object or a null reference in your async method, other than the socket.

In C++ with async socket code, I'd keep track of the number of outstanding async operations with Interlocked and when it came time to disconnect, I'd call shutdown, then wait for the interlocked to hit 0, and then close and destroy any members I needed to.

How would I go about waiting in my Disconnect method for all outstanding Async operations to complete in C# in the following listing?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using log4net;
using System.Net.Sockets;
using System.Net;

namespace IntegrationTests
{
    public class Client2
    {
        class ReceiveContext
        {
            public Socket    m_socket;
            public const int m_bufferSize = 1024;
            public byte[]    m_buffer = new byte[m_bufferSize];
        }

        private static readonly ILog log = LogManager.GetLogger("root");

        static private ulong m_lastId = 1;

        private ulong  m_id;
        private string m_host;
        private uint   m_port;
        private uint   m_timeoutMilliseconds;
        private string m_clientId;
        private Socket m_socket;
        private uint   m_numOutstandingAsyncOps;

        public Client2(string host, uint port, string clientId, uint timeoutMilliseconds)
        {
            m_id                     = m_lastId++;
            m_host                   = host;
            m_port                   = port;
            m_clientId              = clientId;
            m_timeoutMilliseconds    = timeoutMilliseconds;
            m_socket                 = null;
            m_numOutstandingAsyncOps = 0;
        }

        ~Client2()
        {
            Disconnect();
        }

        public void Connect()
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry(m_host);
            IPAddress[] ipV4Addresses = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).ToArray();
            IPAddress[] ipV6Addresses = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetworkV6).ToArray();
            IPEndPoint endpoint = new IPEndPoint(ipV4Addresses[0], (int)m_port);

            m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_socket.ReceiveTimeout = (int)m_timeoutMilliseconds;
            m_socket.SendTimeout    = (int)m_timeoutMilliseconds;

            try
            {
                m_socket.Connect(endpoint);

                log.Info(string.Format("Connected to: {0}", m_socket.RemoteEndPoint.ToString()));

                // Issue the next async receive
                ReceiveContext context = new ReceiveContext();
                context.m_socket = m_socket;
                m_socket.BeginReceive(context.m_buffer, 0, ReceiveContext.m_bufferSize, SocketFlags.None, new AsyncCallback(OnReceive), context);
            }
            catch (Exception e)
            {
                // Error
                log.Error(string.Format("Client #{0} Exception caught OnConnect. Exception: {1}"
                                       , m_id, e.ToString()));
            }
        }

        public void Disconnect()
        {
            if (m_socket != null)
            {
                m_socket.Shutdown(SocketShutdown.Both);

                // TODO - <--- Error here in the callbacks where they try to use the socket and it is disposed
                //        We need to wait here until all outstanding async operations complete
                //        Should we use Interlocked to keep track of them and wait on it somehow?
                m_socket.Close();
                m_socket = null;
            }
        }

        public void Login()
        {
            string loginRequest = string.Format("loginstuff{0})", m_clientId);
            var data = Encoding.ASCII.GetBytes(loginRequest);

            m_socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(OnSend), m_socket);
        }

        public void MakeRequest(string thingy)
        {
            string message = string.Format("requeststuff{0}", thingy);
            var data = Encoding.ASCII.GetBytes(message);

            m_socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(OnSend), m_socket);
        }

        void OnReceive(IAsyncResult asyncResult)
        {
            ReceiveContext context = (ReceiveContext)asyncResult.AsyncState;

            string data = null;
            try
            {
                int bytesReceived = context.m_socket.EndReceive(asyncResult);
                data = Encoding.ASCII.GetString(context.m_buffer, 0, bytesReceived);

                ReceiveContext newContext = new ReceiveContext();
                newContext.m_socket = context.m_socket;

                m_socket.BeginReceive(newContext.m_buffer, 0, ReceiveContext.m_bufferSize, SocketFlags.None, new AsyncCallback(OnReceive), newContext);
            }
            catch(SocketException e)
            {
                if(e.SocketErrorCode == SocketError.ConnectionAborted) // Check if we disconnected on our end
                {
                    return;
                }
            }
            catch (Exception e)
            {
                // Error
                log.Error(string.Format("Client #{0} Exception caught OnReceive. Exception: {1}"
                                       , m_id, e.ToString()));
            }
        }

        void OnSend(IAsyncResult asyncResult)
        {
            Socket socket = (Socket)asyncResult.AsyncState;

            try
            {
                int bytesSent = socket.EndSend(asyncResult);
            }
            catch(Exception e)
            {
                log.Error(string.Format("Client #{0} Exception caught OnSend. Exception: {1}"
                                       , m_id, e.ToString()));
            }
        }
    }
}

Main:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using log4net;
using log4net.Config;

namespace IntegrationTests
{
    class Program
    {
        private static readonly ILog log = LogManager.GetLogger("root");

        static void Main(string[] args)
        {
            try
            {
                XmlConfigurator.Configure();
                log.Info("Starting Component Integration Tests...");

                Client2 client = new Client2("127.0.0.1", 24001, "MyClientId", 60000);
                client.Connect();
                client.Login();
                client.MakeRequest("StuffAndPuff");

                System.Threading.Thread.Sleep(60000); // Sim work until user shutsdown

                client.Disconnect();
            }
            catch (Exception e)
            {
                log.Error(string.Format("Caught an exception in main. Exception: {0}"
                                      , e.ToString()));
            }
        }
    }
}

EDIT:

Here is my additional attempt using the answer proposed by Evk, to the best of my ability. It works fine as far as I can tell.

Problem with this is, that I feel like I basically made everything that was asynchronous into a synchronous call, because of the requirements to lock around anything that would change the counter or the state of the socket. Again, I am novice at C# compared to my C++, so please do point out if I completely missed the mark interpreting his answer.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IntegrationTests
{
    public class Client
    {
        class ReceiveContext
        {
            public const int     _bufferSize    = 1024;
            public byte[]        _buffer        = new byte[_bufferSize]; // Contains bytes from one receive
            public StringBuilder _stringBuilder = new StringBuilder();   // Contains bytes for multiple receives in order to build message up to delim
        }

        private static readonly ILog _log = LogManager.GetLogger("root");

        static private ulong _lastId = 1;
        private ulong  _id;

        protected string         _host;
        protected int            _port;
        protected int            _timeoutMilliseconds;
        protected string         _sessionId;
        protected Socket         _socket;
        protected object         _lockNumOutstandingAsyncOps;
        protected int            _numOutstandingAsyncOps;
        private bool             _disposed = false;

        public Client(string host, int port, string sessionId, int timeoutMilliseconds)
        {
            _id                         = _lastId++;
            _host                       = host;
            _port                       = port;
            _sessionId                  = sessionId;
            _timeoutMilliseconds        = timeoutMilliseconds;
            _socket                     = null;
            _numOutstandingAsyncOps     = 0;
            _lockNumOutstandingAsyncOps = new object();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if(_disposed)
            {
                return;
            }

            if (disposing)
            {
                _socket.Close();
            }

            _disposed = true;
        }

        public void Connect()
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                IPHostEntry ipHostInfo = Dns.GetHostEntry(_host);
                IPAddress[] ipV4Addresses = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).ToArray();
                IPAddress[] ipV6Addresses = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetworkV6).ToArray();
                IPEndPoint endpoint = new IPEndPoint(ipV4Addresses[0], _port);

                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.ReceiveTimeout = _timeoutMilliseconds;
                _socket.SendTimeout = _timeoutMilliseconds;

                try
                {
                    _socket.Connect(endpoint);
                }
                catch (Exception e)
                {
                    // Error
                    Debug.WriteLine(string.Format("Client #{0} Exception caught OnConnect. Exception: {1}"
                                           , _id, e.ToString()));
                    return;
                }

                Debug.WriteLine(string.Format("Client #{0} connected to: {1}", _id, _socket.RemoteEndPoint.ToString()));

                // Issue the first async receive
                ReceiveContext context = new ReceiveContext();

                ++_numOutstandingAsyncOps;
                _socket.BeginReceive(context._buffer, 0, ReceiveContext._bufferSize, SocketFlags.None, new AsyncCallback(OnReceive), context);
            }
        }

        public void Disconnect()
        {
            if (_socket != null)
            {
                // We need to wait here until all outstanding async operations complete
                // In order to avoid getting 'Object was disposed' exceptions in those async ops that use the socket
                lock(_lockNumOutstandingAsyncOps)
                {
                    Debug.WriteLine(string.Format("Client #{0} Disconnecting...", _id));

                    _socket.Shutdown(SocketShutdown.Both);

                    while (_numOutstandingAsyncOps > 0)
                    {
                        Monitor.Wait(_lockNumOutstandingAsyncOps);
                    }

                    _socket.Close();
                    _socket = null;
                }
            }
        }

        public void Login()
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                if (_socket != null && _socket.Connected)
                {
                    string loginRequest = string.Format("loginstuff{0}", _clientId);
                    var data = Encoding.ASCII.GetBytes(loginRequest);

                    Debug.WriteLine(string.Format("Client #{0} Sending Login Request: {1}"
                                           , _id, loginRequest));

                    ++_numOutstandingAsyncOps;
                    _socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(OnSend), _socket);
                }
                else
                {
                    Debug.WriteLine(string.Format("Client #{0} Login was called, but Socket is null or no longer connected."
                                           , _id));
                }
            }
        }

        public void MakeRequest(string thingy)
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                if (_socket != null && _socket.Connected)
                {
                    string message = string.Format("requeststuff{0}", thingy);
                    var data = Encoding.ASCII.GetBytes(message);

                    Debug.WriteLine(string.Format("Client #{0} Sending Request: {1}"
                                           , _id, message));

                    ++_numOutstandingAsyncOps;
                    _socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(OnSend), _socket);
                }
                else
                {
                    Debug.WriteLine(string.Format("Client #{0} MakeRequest was called, but Socket is null or no longer connected."
                                           , _id));
                }
            }
        }

        protected void OnReceive(IAsyncResult asyncResult)
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                ReceiveContext context = (ReceiveContext)asyncResult.AsyncState;

                string data = null;

                try
                {
                    int bytesReceived = _socket.EndReceive(asyncResult);
                    data = Encoding.ASCII.GetString(context._buffer, 0, bytesReceived);

                    // If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received,
                    // the EndReceive method will complete immediately and return zero bytes
                    if (bytesReceived > 0)
                    {
                        StringBuilder stringBuilder = context._stringBuilder.Append(data);

                        int index = -1;
                        do
                        {
                            index = stringBuilder.ToString().IndexOf("#");
                            if (index != -1)
                            {
                                string message = stringBuilder.ToString().Substring(0, index + 1);
                                stringBuilder.Remove(0, index + 1);

                                Debug.WriteLine(string.Format("Client #{0} Received Data: {1}"
                                                       , _id, message));
                            }
                        } while (index != -1);
                    }
                }
                catch (SocketException e)
                {
                    // Check if we disconnected on our end
                    if (e.SocketErrorCode == SocketError.ConnectionAborted)
                    {
                        // Ignore
                    }
                    else
                    {
                        // Error
                        Debug.WriteLine(string.Format("Client #{0} SocketException caught OnReceive. Exception: {1}"
                                               , _id, e.ToString()));
                        Disconnect();
                    }
                }
                catch (Exception e)
                {
                    // Error
                    Debug.WriteLine(string.Format("Client #{0} Exception caught OnReceive. Exception: {1}"
                                           , _id, e.ToString()));
                    Disconnect();
                }
                finally
                {
                    --_numOutstandingAsyncOps;
                    Monitor.Pulse(_lockNumOutstandingAsyncOps);
                }
            }

            // Issue the next async receive
            lock (_lockNumOutstandingAsyncOps)
            {
                if (_socket != null && _socket.Connected)
                {
                    ++_numOutstandingAsyncOps;

                    ReceiveContext newContext = new ReceiveContext();
                    _socket.BeginReceive(newContext._buffer, 0, ReceiveContext._bufferSize, SocketFlags.None, new AsyncCallback(OnReceive), newContext);
                }
            }
        }

        protected void OnSend(IAsyncResult asyncResult)
        {
            lock (_lockNumOutstandingAsyncOps)
            {
                try
                {
                    int bytesSent = _socket.EndSend(asyncResult);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(string.Format("Client #{0} Exception caught OnSend. Exception: {1}"
                                           , _id, e.ToString()));
                    Disconnect();
                }
                finally
                {
                    --_numOutstandingAsyncOps;
                    Monitor.Pulse(_lockNumOutstandingAsyncOps);
                }
            }
        }
    }
}

Body:
You can use Monitor.Wait and Monitor.Pulse for that:

static int _outstandingOperations;
static readonly object _lock = new object();
static void Main() {
    for (int i = 0; i < 100; i++) {
        var tmp = i;
        Task.Run(() =>
        {
            lock (_lock) {
                _outstandingOperations++;
            }
            // some work
            Thread.Sleep(new Random(tmp).Next(0, 5000));
            lock (_lock) {
                _outstandingOperations--;
                // notify condition might have changed
                Monitor.Pulse(_lock);
            }
        });
    }

    lock (_lock) {
        // condition check
        while (_outstandingOperations > 0)
            // will wait here until pulsed, lock will be released during wait
            Monitor.Wait(_lock);
    }
}


来源: stackexchange

问:
Split data into multiple Workbooks based on column
I am trying to split my data into multiple excel files that will carry the name of my "unique value". I usually perform this task every day.

I have about 50 columns, column A contains the unique value, which can be repeated several times. The other columns carry information regarding the unique value. I would also prefer if the original formatting of the file remains.

I have the macro which is splitting the data within workbook (multiple worksheets). But I want to split the data into different workbooks. If possible, save the different workbooks with unique value name.

Code: `

```<code>Sub parse_data()
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
vcol = 1
Set ws = Sheets("Sheet1")
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1:C1"
titlerow = ws.Range(title).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
For i = 2 To lr
On Error Resume Next
If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
End If
Next
myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
Sheets(myarr(i) & "").Columns.AutoFit
Next
ws.AutoFilterMode = False
ws.Activate
End Sub`
</code>```

答:
It looks like your posted code above came from www.extendoffice.com

A simple google search turned up more code on that site that does what you ask for:

https://www.extendoffice.com/documents/excel/1174-excel-split-data-into-multiple-worksheets-based-on-column.html#a1

ContentLicense: CC BY-SA 3.0

Body:
I am trying to split my data into multiple excel files that will carry the name of my "unique value". I usually perform this task every day.

I have about 50 columns, column A contains the unique value, which can be repeated several times. The other columns carry information regarding the unique value. I would also prefer if the original formatting of the file remains.

I have the macro which is splitting the data within workbook (multiple worksheets). But I want to split the data into different workbooks. If possible, save the different workbooks with unique value name.

Code: `

Sub parse_data()
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
vcol = 1
Set ws = Sheets("Sheet1")
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1:C1"
titlerow = ws.Range(title).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
For i = 2 To lr
On Error Resume Next
If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
End If
Next
myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
Sheets(myarr(i) & "").Columns.AutoFit
Next
ws.AutoFilterMode = False
ws.Activate
End Sub`


问:
Can I globally switch to native text rendering in Qt Quick Controls 2?
I would like to use native rendering for all the text in my application. For each Text, Label, etc. element I can do this

```<code>Text {
    renderType: Text.NativeRendering
}
</code>```

to trigger native rendering. I can also use the software renderer for the whole application:

```<code>QQuickWindow::setSceneGraphBackend(QSGRendererInterface::Software);
</code>```

However due to some bugs with the software renderer and some performance issues, I would like to avoid that.

Is there a global switch to change the render type?

答:
The environment variable QML_DISABLE_DISTANCEFIELD controls this.
If you put

```<code>qputenv("QML_DISABLE_DISTANCEFIELD", "1");
</code>```

at the beginning of your main, you will get a nice and sharp text rendering everywhere.

Source: http://www.kdab.com/~thomas/stuff/distancefield.html

Body:
I would like to use native rendering for all the text in my application. For each Text, Label, etc. element I can do this

Text {
    renderType: Text.NativeRendering
}

to trigger native rendering. I can also use the software renderer for the whole application:

QQuickWindow::setSceneGraphBackend(QSGRendererInterface::Software);

However due to some bugs with the software renderer and some performance issues, I would like to avoid that.

Is there a global switch to change the render type?

Body:
The environment variable QML_DISABLE_DISTANCEFIELD controls this.
If you put

qputenv("QML_DISABLE_DISTANCEFIELD", "1");

at the beginning of your main, you will get a nice and sharp text rendering everywhere.

Source: http://www.kdab.com/~thomas/stuff/distancefield.html


问:
correct way to call api using react
I have a react code as below which basically creates a treemap:

```<code>class ChartModal extends Component{
   constructor(props){
      super(props)
}
callApi(){

  fetch(someurl)
  .then((result) => {

    return result.json();
  }).then((jsonResult) => {
    console.log(jsonResult);
  })
}
render(){
  return(
    <Modal
            onOk={() => this.props.toggleVisibility()}
            onCancel={() => this.props.toggleVisibility()}
            visible={this.props.isVisible}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >
            <h1>HOWDY</h1>
            <TreeMap
                data =  {this.callApi()}//this is where i want the data returned by apicall
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}
</code>```

Now I want the data returned by api call to be used inside the tree map component, but the way I am doing it now doesn't seem to be working.
When I run this, the data in the tree map comes out to be null though I expect a json returned by api call to be there.

答:
You need to invoke the API in componentWillMount or any other life cycle hooks and in your API callback use setState to ensure that the result is set to the components state variable. That way after the setState your component can access the value resolved by your API call.

NOTE: this.state.result will be null during the first render. Make sure to have a null check in the TreeMap component before accessing this.props.data.

IMP NOTE

Great suggestion from @aram90 about the setState invocation on unmounted components. To avoid this this.canSetState, instance variable is defined by me and added to prevent any possible setState invocation on unmounted components.

I used this approach just to call the API as early as possible even if it means a nanosecond. However, another approach would be to call the API in componentDidMount and then check for this._ismounted instance variable accordingly. For more on this checkout the answer here Is there a way to check if the react component is unmounted?. React docs suggests not to use isMounted().

There are many ways to achieve this but this is more React kind of way.

```<code>class ChartModal extends Component{
  constructor(props){
    super(props)

    this.state = {
      result: null
    }
    this.canSetState = false;
  }

  componentWillMount() {
    this.canSetState = true;
    this.callApi();
  }

  componentWillUnmount() {
    this.canSetState = false;
  }

  callApi(){

    fetch(someurl)
    .then((result) => {

      return result.json();
    }).then((jsonResult) => {
      this.canSetState && this.setState({result: jsonResult})
    })
  }

  render(){
    return (
      <Modal
        onOk={() => this.props.toggleVisibility()}
        onCancel={() => this.props.toggleVisibility()}
        visible={this.props.isVisible}
        okText={'ok'}
        cancelText={'cancel'}
        confirmLoading={false}
        title="Intent distribution chart"
      >
        <h1>HOWDY</h1>
        <TreeMap
          data={this.state.result}
          width={400}
          valueUnit={'count'}
        />
      </Modal>
    )
  }
}
</code>```

Title: correct way to call api using react

Body:
I have a react code as below which basically creates a treemap:

class ChartModal extends Component{
   constructor(props){
      super(props)
}
callApi(){

  fetch(someurl)
  .then((result) => {

    return result.json();
  }).then((jsonResult) => {
    console.log(jsonResult);
  })
}
render(){
  return(
    <Modal
            onOk={() => this.props.toggleVisibility()}
            onCancel={() => this.props.toggleVisibility()}
            visible={this.props.isVisible}
            okText={'ok'}
            cancelText={'cancel'}
            confirmLoading={false}
            title="Intent distribution chart"
        >

HOWDY

            <TreeMap
                data =  {this.callApi()}//this is where i want the data returned by apicall
                width={400}
                valueUnit={'count'}
            />
        </Modal>
    )
  }
}

Now I want the data returned by api call to be used inside the tree map component, but the way I am doing it now doesn't seem to be working.
When I run this, the data in the tree map comes out to be null though I expect a json returned by api call to be there.

Body:
You need to invoke the API in componentWillMount or any other life cycle hooks and in your API callback use setState to ensure that the result is set to the components state variable. That way after the setState your component can access the value resolved by your API call.

NOTE: this.state.result will be null during the first render. Make sure to have a null check in the TreeMap component before accessing this.props.data.

IMP NOTE

Great suggestion from @aram90 about the setState invocation on unmounted components. To avoid this this.canSetState, instance variable is defined by me and added to prevent any possible setState invocation on unmounted components.

I used this approach just to call the API as early as possible even if it means a nanosecond. However, another approach would be to call the API in componentDidMount and then check for this._ismounted instance variable accordingly. For more on this checkout the answer here Is there a way to check if the react component is unmounted?. React docs suggests not to use isMounted().

There are many ways to achieve this but this is more React kind of way.

class ChartModal extends Component{
  constructor(props){
    super(props)

    this.state = {
      result: null
    }
    this.canSetState = false;
  }

  componentWillMount() {
    this.canSetState = true;
    this.callApi();
  }

  componentWillUnmount() {
    this.canSetState = false;
  }

  callApi(){

    fetch(someurl)
    .then((result) => {

      return result.json();
    }).then((jsonResult) => {
      this.canSetState && this.setState({result: jsonResult})
    })
  }

  render(){
    return (
      <Modal
        onOk={() => this.props.toggleVisibility()}
        onCancel={() => this.props.toggleVisibility()}
        visible={this.props.isVisible}
        okText={'ok'}
        cancelText={'cancel'}
        confirmLoading={false}
        title="Intent distribution chart"
      >
        <h1>HOWDY</h1>
        <TreeMap
          data={this.state.result}
          width={400}
          valueUnit={'count'}
        />
      </Modal>
    )
  }
}


问:
qt creator error on "import QtMultimedia"
Recently, I have been studying on Qt5 Audio and followed this youtube lecture.

https://www.youtube.com/watch?v=Dh6ax1xVJD0

During the course I had to put the line into one of 'qml' file

```<code>import QtMultimedia 5.0
</code>```

The name "QtMultimedia 5.0" came up automatically so did the help menu.
However, the line has red underline that says "QML module not found Import paths:..."

How may I fix this problem?
OS: Ubuntu
Project build steps: Applications => "Qt Quick UI" => "Qt Quick 2.0"

Thank you for reading my story.
JB

答: try this command export LD_LIBRARY_PATH=/path-to-your-qt-installation/Qt5.9.2/5.9.2/gcc_64/lib it helped me with similar issue with PyQt and QML

Body:
Recently, I have been studying on Qt5 Audio and followed this youtube lecture.

https://www.youtube.com/watch?v=Dh6ax1xVJD0

During the course I had to put the line into one of 'qml' file

import QtMultimedia 5.0

The name "QtMultimedia 5.0" came up automatically so did the help menu.
However, the line has red underline that says "QML module not found Import paths:..."

How may I fix this problem?
OS: Ubuntu
Project build steps: Applications => "Qt Quick UI" => "Qt Quick 2.0"

Thank you for reading my story.
JB


问:
Using htaccess, check multiples directories for request before throwing 404
I have a folder full of legacy files that I need to carry over during a site redesign, but I'd like to keep them all in their own folder, called legacy. If a request comes in for an old URL, such as

```<code>/old-project/foo.html
</code>```

but that isn't found, I'd like the server to check the legacy folder

```<code>/legacy/old-project/foo.html
</code>```

and serve that up before throwing a 404. Thoughts?

答:
http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

Google it for more. This gets asked a lot.

Beginners tutorial: http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/

Advanced info: http://www.askapache.com/htaccess/crazy-advanced-mod_rewrite-tutorial.html

In case that wasn't enough:

```<code>RewriteEngine On
RewriteRule ^/old-project/(.*)$ /legacy/old-project/$1
</code>```

Update, per clarification in comment:

This set of rules should do the trick quite nicely. It only redirects requests that aren't for existing files, symlinks, or directories (for indexing).

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^/old-project/(.*)$ /legacy/old-project/$1 [NC,L]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a folder full of legacy files that I need to carry over during a site redesign, but I'd like to keep them all in their own folder, called legacy. If a request comes in for an old URL, such as

/old-project/foo.html

but that isn't found, I'd like the server to check the legacy folder

/legacy/old-project/foo.html

and serve that up before throwing a 404. Thoughts?

Body:
http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

Google it for more. This gets asked a lot.

Beginners tutorial: http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/

Advanced info: http://www.askapache.com/htaccess/crazy-advanced-mod_rewrite-tutorial.html

In case that wasn't enough:

RewriteEngine On
RewriteRule ^/old-project/(.*)$ /legacy/old-project/$1

Update, per clarification in comment:

This set of rules should do the trick quite nicely. It only redirects requests that aren't for existing files, symlinks, or directories (for indexing).

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^/old-project/(.*)$ /legacy/old-project/$1 [NC,L]


问:
Failed to exec start script
Angular: 5.0.1 /
Angular CLI: 1.5.0 /
Node: 8.9.1 /
npm: 5.5.1 /
Os: win32 x64

I get the below error when executing "npm start" in the terminal/command prompt. Can anyone help me resolve this? I have spent a whole day trying to fix it with no luck.

Here is the scripts section of my package.json

```<code>"scripts": {
    "start": "webpack-dev-server --inline --progress --port 8080"
  },
</code>```

webpack.config.js

```<code>module.exports = require('./config/webpack.dev.js');
</code>```

webpack.common.js

```<code>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['.ts', '.js']
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        loaders: [
          {
            loader: 'awesome-typescript-loader',
            options: { configFileName: helpers.root('src', 'tsconfig.json') }
          } , 'angular2-template-loader'
        ]
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file-loader?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw-loader'
      }
    ]
  },

  plugins: [
    // Workaround for angular/angular#11580
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)@angular/,
      helpers.root('./src'), // location of your src
      {} // a map of your routes
    ),

    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    new HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ]
};
</code>```

webpack.dev.js

```<code>var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-module-eval-source-map',

  output: {
    path: helpers.root('dist'),
    publicPath: '/',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js'
  },

  plugins: [
    new ExtractTextPlugin('[name].css')
  ],

  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});
</code>```

webpack.prod.js

```<code>var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

module.exports = webpackMerge(commonConfig, {
  devtool: 'source-map',

  output: {
    path: helpers.root('dist'),
    publicPath: '/',
    filename: '[name].[hash].js',
    chunkFilename: '[id].[hash].chunk.js'
  },

  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
      mangle: {
        keep_fnames: true
      }
    }),
    new ExtractTextPlugin('[name].[hash].css'),
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(ENV)
      }
    }),
    new webpack.LoaderOptionsPlugin({
      htmlLoader: {
        minimize: false // workaround for ng2
      }
    })
  ]
});
</code>```

Here is the error

0 info it worked if it ends with ok 1 verbose cli [ 'C:\Program
  Files\nodejs\node.exe', 1 verbose cli   'C:\Program
  Files\nodejs\node_modules\npm\bin\npm-cli.js', 1 verbose cli

  'start' ] 2 info using npm@5.5.1 3 info using node@v8.9.1 4 verbose
  run-script [ 'prestart', 'start', 'poststart' ] 5 info lifecycle
  angular-io-example@1.0.0~prestart: angular-io-example@1.0.0 6 info
  lifecycle angular-io-example@1.0.0~start: angular-io-example@1.0.0 7
  verbose lifecycle angular-io-example@1.0.0~start: unsafe-perm in
  lifecycle true 8 verbose lifecycle angular-io-example@1.0.0~start:
  PATH: C:\Program
  Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\Users\cbonsu\Downloads\sample_pro\webpack\node_modules.bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program
  Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program
  Files\Git\cmd;C:\Program Files (x86)\Microsoft SQL
  Server\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\130\DTS\Binn\;C:\Program Files\Microsoft SQL
  Server\130\DTS\Binn\;C:\Program Files\Microsoft SQL Server\Client
  SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files
  (x86)\Microsoft SQL
  Server\130\Tools\Binn\ManagementStudio\;C:\WINDOWS\system32\config\systemprofile.dnx\bin;C:\Program
  Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft\Web Platform
  Installer\;C:\Program Files\dotnet\;C:\Program
  Files\nodejs\;C:\Users\cbonsu\AppData\Local\Microsoft\WindowsApps;C:\Program
  Files\nodejs;C:\Program Files\Microsoft VS
  Code\bin;C:\Users\cbonsu\AppData\Roaming\npm 9 verbose lifecycle
  angular-io-example@1.0.0~start: CWD:
  C:\Users\cbonsu\Downloads\sample_pro\webpack 10 silly lifecycle
  angular-io-example@1.0.0~start: Args: [ '/d /s /c', 10 silly lifecycle
  'webpack-dev-server --inline --progress --port 8080' ] 11 silly
  lifecycle angular-io-example@1.0.0~start: Returned: code: 1  signal:
  null 12 info lifecycle angular-io-example@1.0.0~start: Failed to exec
  start script 13 verbose stack Error: angular-io-example@1.0.0 start:
  webpack-dev-server --inline --progress --port 8080 13 verbose stack
  Exit status 1 13 verbose stack     at EventEmitter.
  (C:\Program
  Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:280:16)
  13 verbose stack     at emitTwo (events.js:126:13) 13 verbose stack

  at EventEmitter.emit (events.js:214:7) 13 verbose stack     at
  ChildProcess. (C:\Program
  Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
  13 verbose stack     at emitTwo (events.js:126:13) 13 verbose stack

  at ChildProcess.emit (events.js:214:7) 13 verbose stack     at
  maybeClose (internal/child_process.js:925:16) 13 verbose stack     at
  Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
  14 verbose pkgid angular-io-example@1.0.0 15 verbose cwd
  C:\Users\cbonsu\Downloads\sample_pro\webpack 16 verbose Windows_NT
  10.0.15063 17 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js"
  "start" 18 verbose node v8.9.1 19 verbose npm  v5.5.1 20 error code
  ELIFECYCLE 21 error errno 1 22 error angular-io-example@1.0.0 start:
  webpack-dev-server --inline --progress --port 8080 22 error Exit
  status 1 23 error Failed at the angular-io-example@1.0.0 start script.
  23 error This is probably not a problem with npm. There is likely
  additional logging output above. 24 verbose exit [ 1, true ]

答:
it should make it </p>

```<code>npm cache clean --force

npm install

npm start
</code>```

Title: Failed to exec start script

Body:
Angular: 5.0.1 /
Angular CLI: 1.5.0 /
Node: 8.9.1 /
npm: 5.5.1 /
Os: win32 x64

I get the below error when executing "npm start" in the terminal/command prompt. Can anyone help me resolve this? I have spent a whole day trying to fix it with no luck.

Here is the scripts section of my package.json

"scripts": {
    "start": "webpack-dev-server --inline --progress --port 8080"
  },

webpack.config.js

module.exports = require('./config/webpack.dev.js');

webpack.common.js

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['.ts', '.js']
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        loaders: [
          {
            loader: 'awesome-typescript-loader',
            options: { configFileName: helpers.root('src', 'tsconfig.json') }
          } , 'angular2-template-loader'
        ]
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file-loader?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw-loader'
      }
    ]
  },

  plugins: [
    // Workaround for angular/angular#11580
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)@angular/,
      helpers.root('./src'), // location of your src
      {} // a map of your routes
    ),

    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    new HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ]
};

webpack.dev.js

var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-module-eval-source-map',

  output: {
    path: helpers.root('dist'),
    publicPath: '/',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js'
  },

  plugins: [
    new ExtractTextPlugin('[name].css')
  ],

  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});

webpack.prod.js

var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

module.exports = webpackMerge(commonConfig, {
  devtool: 'source-map',

  output: {
    path: helpers.root('dist'),
    publicPath: '/',
    filename: '[name].[hash].js',
    chunkFilename: '[id].[hash].chunk.js'
  },

  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
      mangle: {
        keep_fnames: true
      }
    }),
    new ExtractTextPlugin('[name].[hash].css'),
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(ENV)
      }
    }),
    new webpack.LoaderOptionsPlugin({
      htmlLoader: {
        minimize: false // workaround for ng2
      }
    })
  ]
});

Here is the error

0 info it worked if it ends with ok 1 verbose cli [ 'C:\Program
  Files\nodejs\node.exe', 1 verbose cli   'C:\Program
  Files\nodejs\node_modules\npm\bin\npm-cli.js', 1 verbose cli

  'start' ] 2 info using npm@5.5.1 3 info using node@v8.9.1 4 verbose
  run-script [ 'prestart', 'start', 'poststart' ] 5 info lifecycle
  angular-io-example@1.0.0~prestart: angular-io-example@1.0.0 6 info
  lifecycle angular-io-example@1.0.0~start: angular-io-example@1.0.0 7
  verbose lifecycle angular-io-example@1.0.0~start: unsafe-perm in
  lifecycle true 8 verbose lifecycle angular-io-example@1.0.0~start:
  PATH: C:\Program
  Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\Users\cbonsu\Downloads\sample_pro\webpack\node_modules.bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program
  Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program
  Files\Git\cmd;C:\Program Files (x86)\Microsoft SQL
  Server\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\130\DTS\Binn\;C:\Program Files\Microsoft SQL
  Server\130\DTS\Binn\;C:\Program Files\Microsoft SQL Server\Client
  SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
  Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files
  (x86)\Microsoft SQL
  Server\130\Tools\Binn\ManagementStudio\;C:\WINDOWS\system32\config\systemprofile.dnx\bin;C:\Program
  Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft\Web Platform
  Installer\;C:\Program Files\dotnet\;C:\Program
  Files\nodejs\;C:\Users\cbonsu\AppData\Local\Microsoft\WindowsApps;C:\Program
  Files\nodejs;C:\Program Files\Microsoft VS
  Code\bin;C:\Users\cbonsu\AppData\Roaming\npm 9 verbose lifecycle
  angular-io-example@1.0.0~start: CWD:
  C:\Users\cbonsu\Downloads\sample_pro\webpack 10 silly lifecycle
  angular-io-example@1.0.0~start: Args: [ '/d /s /c', 10 silly lifecycle
  'webpack-dev-server --inline --progress --port 8080' ] 11 silly
  lifecycle angular-io-example@1.0.0~start: Returned: code: 1  signal:
  null 12 info lifecycle angular-io-example@1.0.0~start: Failed to exec
  start script 13 verbose stack Error: angular-io-example@1.0.0 start:
  webpack-dev-server --inline --progress --port 8080 13 verbose stack
  Exit status 1 13 verbose stack     at EventEmitter.
  (C:\Program
  Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:280:16)
  13 verbose stack     at emitTwo (events.js:126:13) 13 verbose stack

  at EventEmitter.emit (events.js:214:7) 13 verbose stack     at
  ChildProcess. (C:\Program
  Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
  13 verbose stack     at emitTwo (events.js:126:13) 13 verbose stack

  at ChildProcess.emit (events.js:214:7) 13 verbose stack     at
  maybeClose (internal/child_process.js:925:16) 13 verbose stack     at
  Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
  14 verbose pkgid angular-io-example@1.0.0 15 verbose cwd
  C:\Users\cbonsu\Downloads\sample_pro\webpack 16 verbose Windows_NT
  10.0.15063 17 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js"
  "start" 18 verbose node v8.9.1 19 verbose npm  v5.5.1 20 error code
  ELIFECYCLE 21 error errno 1 22 error angular-io-example@1.0.0 start:
  webpack-dev-server --inline --progress --port 8080 22 error Exit
  status 1 23 error Failed at the angular-io-example@1.0.0 start script.
  23 error This is probably not a problem with npm. There is likely
  additional logging output above. 24 verbose exit [ 1, true ]

Body:
it should make it

npm cache clean --force

npm install

npm start

ContentLicense: CC BY-SA 4.0


问:
Why can't I add a reference to a .NET Core 2.0 Library in my UWP v6.0.1 Project?
I have two .NET Core 2.0 projects and a Universal Windows Platform version v6.0.1 project (main) in my solution (both targets set to Build 16299). When any of the two .NET Core 2.0 projects, I get an error message "Unable to add a reference to project "xx". It would be nice if it told me why.

As a test, I added a new .NET Standard 2.0 library and I was able to reference it. From my limited understanding, .Net Standard 2.0 is compatible with .Net Core 2.0 which is the latest, so shouldn't .NET Core 2.0 also be compatible with UWP 6.0.1?  When I look at the chart comparing .NET standards, it clearly states that .NET Standard 2.0 is and .NET Core 2.0 are compatible.

.Net Standard Versions

If all of this isn't amazingly confounding, the UWP project has the Microsoft .NETCore packages which list .NET Core 2.0:

Also, although not shown, the UWP package has a .NETCore, Version 5.0 dependency!  I was under the impression .NET Core is only at version 2.0:

What's going on here?  Some clarification would be great.

ASIDE:  Microsoft appears to be an incoherent organization as exhibited with this mindbogglingly confusing .NET architecture along with its scattered and disorganized documentation. It seems as if all the different departments are duplicating efforts with no higher level guidance.  Perhaps, they need a .NET Czar.

答:
.NET Core implements .NET Standard but it may have some APIs that are not available anywhere else. What you're saying is like saying "UWP implements .NET Standard so I could use UWP APIs in every .NET Standard project" and that's not true.

.NET Standard is just a subset of APIs available on all the .NET platforms. It's a replacement for PCLs. You can use .NET Standard library in every .NET app/library that uses .NET that implements that certain version of .NET Standard.

PS: Yeah, the relations between .NET Standard and others is kinda confusing. Also took me some time to understand it.


问:
Matching keywords in a dictionary to a list in Python
The following dictionary gives the word and its value:

```<code>keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}
</code>```

Following the dictionary are two tweets in a list in a list.
For each tweet, we need to find which of the words from keywords are present in it.

```<code>tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]
</code>```

The target is to find the sum of the keyword values found in each tweet line.

The code created needs to be a loop because there are more than 2 tweets.
I do not understand how I should execute this process.

Appreciate your insight!

答:
Try this:</p>

```<code>keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}
tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]
total = 0

for i in keywords:
    for j in tweets:
        if i in j:
            occourance = j.count(i)
            print('keyword=', i)
            total += keywords[i]*occourance
print('sum is: ', total)

output:
    keyword= best
    keyword= excited
    sum is:  20
</code>```

Body:
The following dictionary gives the word and its value:

keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}

Following the dictionary are two tweets in a list in a list.
For each tweet, we need to find which of the words from keywords are present in it.

tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]

The target is to find the sum of the keyword values found in each tweet line.

The code created needs to be a loop because there are more than 2 tweets.
I do not understand how I should execute this process.

Appreciate your insight!

Body:
Try this:

keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}
tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]
total = 0

for i in keywords:
    for j in tweets:
        if i in j:
            occourance = j.count(i)
            print('keyword=', i)
            total += keywords[i]*occourance
print('sum is: ', total)

output:
    keyword= best
    keyword= excited
    sum is:  20


问:
coldfusion pagination (Next & Previous)
I have to do pagination in my project:

below code working fine just I'm not able to figure out for (next / prev) buttons how can i handle. im using mysql database
it will be great help if you give me some best practice tips &
if there is any other easy way? please give me reference it will be great help

here is my code:

```<code><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="application/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!---
<cfquery name="data" datasource="#application.dsn#">
    select * from yourTable
</cfquery>

--->

<!--- Generate fake data --->
<cfset data = queryNew("id,name","integer,varchar")>
<cfloop index="x" from="1" to="80">
    <cfset queryAddRow(data, {id:x,name:"User #x#"})>
</cfloop>

    <cfparam name="URL.PageId" default="0">
<cfset RecordsPerPage = 5>

<cfset TotalPages = (data.Recordcount/RecordsPerPage)-1>
<cfset StartRow = (URL.PageId*RecordsPerPage)+1>
<cfset EndRow = StartRow+RecordsPerPage-1>
<cfoutput>
 <table border="1">
   <tr>
      <th>No.</th>
      <th>PARKNAME</th>
      <th>REGION </th>
      <th>STATE</th>
   </tr>
   <cfloop query="data">
    <cfif CurrentRow gte StartRow >
       <tr>
          <td>#CurrentRow#</td>
          <td>#name#</td>
          <td>US</td>
          <td>MO</td>
       </tr>
    </cfif>
    <cfif CurrentRow eq EndRow>
       <cfbreak>
    </cfif>
   </cfloop>
</cfoutput>
   <tr>
      <td colspan="4">
       <cfloop index="Pages" from="0" to="#TotalPages#">
        <cfoutput>
           <cfset DisplayPgNo = Pages+1>
           <cfif URL.PageId eq pages>
              <strong>#DisplayPgNo#</strong>
           <cfelse>
              <a href="?PageId=#Pages#">#DisplayPgNo#</a>
           </cfif>
        </cfoutput>
       </cfloop>
      </td>
   </tr>
</table>

 <nav aria-label="...">
  <ul class="pagination">
    <li class="page-item disabled">
      <a class="page-link" href="#" tabindex="-1">Previous</a>
    </li>
      <cfloop index="Pages" from="0" to="#TotalPages#">
        <cfoutput>
           <cfset DisplayPgNo = Pages+1>
           <cfif URL.PageId eq pages>
                <li class="page-item">
                    <li class="page-item active">
                    <a class="page-link" href="##">#DisplayPgNo#</a>
               </li>
           <cfelse>
               <li class="page-item"><a class="page-link" href="?PageId=#Pages#">#DisplayPgNo#</a></li>
           </cfif>
        </cfoutput>
       </cfloop>
        <li class="page-item">
            <a class="page-link" href="#">Next</a>
        </li>
  </ul>
</nav>
</code>```

答:
Previous should look like

```<code><li class="page-item <cfif url.pageid LTE 1>disabled</cfif>">
  <a class="page-link" href="?Pagesid=#(url.pageid - 1)#" tabindex="-1">Previous</a>
</li>
</code>```

Similar code for Next

Title: coldfusion pagination (Next & Previous)

Body:
I have to do pagination in my project:

below code working fine just I'm not able to figure out for (next / prev) buttons how can i handle. im using mysql database
it will be great help if you give me some best practice tips &
if there is any other easy way? please give me reference it will be great help

here is my code:

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

<cfset data = queryNew("id,name","integer,varchar")>
<cfloop index="x" from="1" to="80">
    <cfset queryAddRow(data, {id:x,name:"User #x#"})>
</cfloop>

    <cfparam name="URL.PageId" default="0">
<cfset RecordsPerPage = 5>

<cfset TotalPages = (data.Recordcount/RecordsPerPage)-1>
<cfset StartRow = (URL.PageId*RecordsPerPage)+1>
<cfset EndRow = StartRow+RecordsPerPage-1>
<cfoutput>

      No.
      PARKNAME
      REGION
      STATE

   <cfloop query="data">
    <cfif CurrentRow gte StartRow >

          #CurrentRow#
          #name#
          US
          MO

    </cfif>
    <cfif CurrentRow eq EndRow>
       <cfbreak>
    </cfif>
   </cfloop>
</cfoutput>

       <cfloop index="Pages" from="0" to="#TotalPages#">
        <cfoutput>
           <cfset DisplayPgNo = Pages+1>
           <cfif URL.PageId eq pages>
              #DisplayPgNo#
           <cfelse>
              #DisplayPgNo#
           </cfif>
        </cfoutput>
       </cfloop>

      Previous

      <cfloop index="Pages" from="0" to="#TotalPages#">
        <cfoutput>
           <cfset DisplayPgNo = Pages+1>
           <cfif URL.PageId eq pages>

                    #DisplayPgNo#

           <cfelse>

#DisplayPgNo#

           </cfif>
        </cfoutput>
       </cfloop>

            Next

Body:
Previous should look like

<li class="page-item <cfif url.pageid LTE 1>disabled</cfif>">
  <a class="page-link" href="?Pagesid=#(url.pageid - 1)#" tabindex="-1">Previous</a>
</li>

Similar code for Next


问:
Count sort in C could only sort first 4 numbers
I am just working for a C programm using counting sort to sort numbers, here is my code, and I am using a external txt file for input. and the library arrayio.h is a given code for input.

```<code>#include <stdio.h>
#include <stdlib.h>
#include "arrayio.h"

int MAX_LAENGE = 1000;
int MAX_VALUE = 100;
int i,j,k;

void count_sort_calculate_counts(int input_array[], int len, int count_array[]) {
    for (i=0; i<len;i++) {
        count_array[i] = 0;
    }
    for (j=0; j<len;j++) {
        count_array[input_array[j]] = count_array[input_array[j]] + 1;
    }
}

void count_sort_write_output_array(int output_array[], int len, int count_array[]) {
    k=0;
    for (j=0;j<len;j++) {
        for (i=0; i<count_array[j]; i++) {
            output_array[k] = j;
            k = k + 1;
        }
    }
}

int main(int argc, char *argv[]) {
    if (argc < 2){
        printf("Aufruf: %s <Dateiname>\n", argv[0]);
        printf("Beispiel: %s zahlen.txt\n", argv[0]);
        exit(1);
    }
    char *filename = argv[1];

    int input_array[MAX_LAENGE];
    int len = read_array_from_file(input_array, MAX_LAENGE, filename);

    printf("Unsortiertes Array:");
    print_array(input_array, len);

    int count_array[MAX_LAENGE];
    int output_array[MAX_LAENGE];
    count_sort_calculate_counts(input_array, len, count_array);
    count_sort_write_output_array(output_array, len, count_array);

    printf("Sortiertes Array:");
    print_array(output_array, len);
    return 0;
}
</code>```

My problem is that when I run this program, it returns only the first 4 numbers.
for example, when I input:

```<code>90 38 42 34 8 0 77 1 84 5 25 72 44 42 90 63 23
</code>```

It returns:

```<code>0 1 5 8 0 0 0 0 0 0 0 0 0 0 0 0 0
</code>```

答:
The error is in the code that distributes the counts back to the output array. You end iterations of counts upon reaching the length of the original array, while you should be ending it when you reach the max value:

```<code>void count_sort_write_output_array(int output_array[], int len, int count_array[]){
    k=0;
    for (j=0;j<MAX_LAENGE;j++)
    {
        for (i=0; i<count_array[j]; i++)
        {
            output_array[k++] = j;
        }
    }
}
</code>```

Demo.

To earn some "points for style" consider hiding the array of counts inside a single sorting function that computes counts and distributes the values back to the output array. After all, counts is an intermediate result that should be of no interest to users of your code, so you should not ask users of your sorting function to allocate it.

Body:
I am just working for a C programm using counting sort to sort numbers, here is my code, and I am using a external txt file for input. and the library arrayio.h is a given code for input.

#include <stdio.h>
#include <stdlib.h>
#include "arrayio.h"

int MAX_LAENGE = 1000;
int MAX_VALUE = 100;
int i,j,k;

void count_sort_calculate_counts(int input_array[], int len, int count_array[]) {
    for (i=0; i<len;i++) {
        count_array[i] = 0;
    }
    for (j=0; j<len;j++) {
        count_array[input_array[j]] = count_array[input_array[j]] + 1;
    }
}

void count_sort_write_output_array(int output_array[], int len, int count_array[]) {
    k=0;
    for (j=0;j<len;j++) {
        for (i=0; i<count_array[j]; i++) {
            output_array[k] = j;
            k = k + 1;
        }
    }
}

int main(int argc, char *argv[]) {
    if (argc < 2){
        printf("Aufruf: %s <Dateiname>\n", argv[0]);
        printf("Beispiel: %s zahlen.txt\n", argv[0]);
        exit(1);
    }
    char *filename = argv[1];

    int input_array[MAX_LAENGE];
    int len = read_array_from_file(input_array, MAX_LAENGE, filename);

    printf("Unsortiertes Array:");
    print_array(input_array, len);

    int count_array[MAX_LAENGE];
    int output_array[MAX_LAENGE];
    count_sort_calculate_counts(input_array, len, count_array);
    count_sort_write_output_array(output_array, len, count_array);

    printf("Sortiertes Array:");
    print_array(output_array, len);
    return 0;
}

My problem is that when I run this program, it returns only the first 4 numbers.
for example, when I input:

90 38 42 34 8 0 77 1 84 5 25 72 44 42 90 63 23

It returns:

0 1 5 8 0 0 0 0 0 0 0 0 0 0 0 0 0

Body:
The error is in the code that distributes the counts back to the output array. You end iterations of counts upon reaching the length of the original array, while you should be ending it when you reach the max value:

void count_sort_write_output_array(int output_array[], int len, int count_array[]){
    k=0;
    for (j=0;j<MAX_LAENGE;j++)
    {
        for (i=0; i<count_array[j]; i++)
        {
            output_array[k++] = j;
        }
    }
}

Demo.

To earn some "points for style" consider hiding the array of counts inside a single sorting function that computes counts and distributes the values back to the output array. After all, counts is an intermediate result that should be of no interest to users of your code, so you should not ask users of your sorting function to allocate it.


问:
Using Acumatica REST API with Microsoft Flow
Has anyone tried using the Acumatica REST APIs with Microsoft Flow?

I tried it a few weeks ago using Sergey's instructions (click here) and it worked fine.

But now I'm getting the following message on the second step.

{
  "message": "You are not logged in."
}

The first step is where I authenticate (just like in Sergey's instructions), then I pass the headers from the first step to the second step (just like in Sergey's instructions), but somehow the second step doesn't think that I'm logged in.

Any ideas?

Here are some screenshots (the only thing I changed for the screenshot is the password):

https://i.imgur.com/uD3CpCa.png

https://i.imgur.com/CZ6XLsW.png

https://i.imgur.com/8XB1LT2.png

Here are the Headers Outputs from the first call (HTTP):
X-Handled-By
Acumatica-PX.Export/AuthenticationManagerModule
Set-Cookie
ASP.NET_SessionId=0koh1ysshqsfmzr0srib2s5z; path=/; HttpOnly,UserBranch=16; path=/,Locale=Culture=en-US&TimeZone=GMTM0800A; expires=Sat, 18-Nov-2017 17:51:27 GMT; path=/,.ASPXAUTH=880C71F4E1A76C36E7E468337C01BC9E6E4C898E1977BAAAF2A35F7217B1D9132794A9547071508A35A2D4B9132DC4B55E86DD6E9C9B8D46CAECE39D74CC9B44BDD47E7C0D836D22D8F4EEFAF8142A9987418B8003EFF5B340DF735E7F8F36EDE5D25300D887E4DADEB0A80B707D87F6B0D32437; path=/; HttpOnly
Server
Microsoft-IIS/7.5
X-Powered-By
ASP.NET
Date
Wed, 15 Nov 2017 17:51:27 GMT
Content-Length
0

Here are the Headers Inputs from the second call (HTTP 2):
{
  "X-Handled-By": "Acumatica-PX.Export/AuthenticationManagerModule",
  "Set-Cookie": "ASP.NET_SessionId=0koh1ysshqsfmzr0srib2s5z; path=/; HttpOnly,UserBranch=16; path=/,Locale=Culture=en-US&TimeZone=GMTM0800A; expires=Sat, 18-Nov-2017 17:51:27 GMT; path=/,.ASPXAUTH=880C71F4E1A76C36E7E468337C01BC9E6E4C898E1977BAAAF2A35F7217B1D9132794A9547071508A35A2D4B9132DC4B55E86DD6E9C9B8D46CAECE39D74CC9B44BDD47E7C0D836D22D8F4EEFAF8142A9987418B8003EFF5B340DF735E7F8F36EDE5D25300D887E4DADEB0A80B707D87F6B0D32437; path=/; HttpOnly",
  "Server": "Microsoft-IIS/7.5",
  "X-Powered-By": "ASP.NET",
  "Date": "Wed, 15 Nov 2017 17:51:27 GMT",
  "Content-Length": "0"
}

Here are the Headers Outputs from the second call (HTTP 2):
X-Handled-By
Acumatica-PX.Export/AuthenticationManagerModule
Date
Wed, 15 Nov 2017 17:51:27 GMT
Set-Cookie
ASP.NET_SessionId=dklemj2usv2zveyc3acxnhm5; path=/; HttpOnly
Server
Microsoft-IIS/7.5
X-Powered-By
ASP.NET
Content-Length
36
Content-Type
application/json; charset=utf-8

答:
I had one previously and the difference that I see between your and mine is that your login post doesn't have any headers.

Mine had :

Accept                application/json

Content-Type          application/json

Here is a screenshot of my working flow : https://imgur.com/a/trgBa

EDIT :

After playing with this a bit more I have found a way off making this work. though it is using OAuth authentication instead of cookie based authentication.
Here is how :

I first created a connected application on the screen of the same name in acumatica

Of the following type : Ressource Owner Password Credentials

I also created added a shared secret while taking note of its value (it is only showed once).

I created the first http call in flow using the following information

URL : https://"Acumatica ERP instance URL"/identity/connect/token

Header : Content type /  application/x-www-form-urlencoded

Body : grant_type=password&client_id=Value1&client_secret=Value2&username=Value3&password=Value4&scope=api

Value1 : ID of the connected application created in step 1

Value2 :Value of the shared secret saved from step 1. If lost just remove and add another secret. just be careful no one else is using that secret

Value3 : Username of existing account

Value4 : Password of account specified in value 3

Create the second HTTP call that will do the web service request

URL : https://"Acumatica ERP instance URL"/entity/Default/17.200.001/Case

Header : Authorization / bearer substring(substring(string(body('HTTP_2')),indexOf(string(body('HTTP_2')),':'),34),2,32)

Body : a normal REST API body for the requested operation

The Substring is only separated by a space in the header

Here are image representing the 2 HTTP calls


问:
Erlang Universal Binary Format? Anyone using it?
I recently stumbled upon this 2002 conference paper (Getting Erlang to talk to the outside world by Joe Armstrong) and I was wondering whether this is a standard that was ignored or if there was any adoption?

Should I focus on Apache Thrift for inter-platform communication? (whatever solution I choose will involve at least Erlang)

答:
I don't know if anyone's using Erlang's binary serialization format per se, outside of Erlang programs; but BERT (Binary ERlang Term) is an Erlang-compatible binary data interchange format and RPC protocol specified and open-sourced by the GitHub guys. It's based on and fully binary-compatible with the Erlang external term format.

As you can see on the BERT website, there are implementations in a number of programming languages, including C++, JavaScript, Ruby, Python, Scala, Haskell, Go, Factor, Scheme, Clojure, and Common Lisp. The mailing list currently has 85+ members subscribed to it, so quite a few people are indeed using BERT, and hence indirectly the Erlang binary format.

In my own use, mostly in Ruby and Common Lisp applications, BERT has proved useful as essentially a binary form of S-expressions.


问:
Added button successfully by using .innerHTML but can't access the button using its class name
```<code>    function displaMatches (matches) {
  var searchText = document.querySelector('.search').value;
  var menu = document.querySelector('.menu')
  matches.forEach(match => {
    menu.innerHTML += `<li><button class="suggestion">${match}</button></li>`
  });

  var suggestions = document.querySelectorAll('.suggestion');
  suggestions.forEach(suggestion => {
    suggestion.addEventListener('click', () => {
      document.querySelector('.search').value = suggestion.textContent;
    });
  });
}
var search = document.querySelector('.search')

search.addEventListener('change', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

search.addEventListener('keyup', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

function autocomplete () {
  var searchText = document.querySelector('.search').value

  fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/autocomplete?&text=${searchText}&latitude=37.3351534&longitude=-122.0352478`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${access_token}`,
    }
  }).then((res) => {
    return res.json();
  }).then((data) => {
    var allData = [];
    allData.push(data);
    console.log(allData);
    let businesses = allData[0].businesses
    let categories = allData[0].categories
    let terms = allData[0].terms

    let matches = [];

    businesses.forEach(business => {
      matches.push(business.name);
    });

    categories.forEach(category => {
      matches.push(category.title);
    });

    terms.forEach(term => {
      matches.push(term.text);
    });
    displaMatches(matches);
  });
}
</code>```

I can see buttons being added successfully to the menu on the page. However, when I tried to access a button using the class name "suggestion", what I got is null. What did I do wrong?

I changed my codes and the displayMatches function is now working fine. However, after I added the suggestion to the search box, the search button no longer works. If I disable the suggestion function, and type my own words into the search box, I can search anything with no problem. Can anyone explain why?

答:
You appear to be missing an = sign. Should be:

menu.innerHTML += `<li><button class="suggestion">${match}</button></li>`

Also, keep in mind that if you to add an event listener to every .suggestion instead of just the first one, you need to use var suggestion = document.querySelectorAll('.suggestion')

Body:
    function displaMatches (matches) {
  var searchText = document.querySelector('.search').value;
  var menu = document.querySelector('.menu')
  matches.forEach(match => {
    menu.innerHTML += `<li><button class="suggestion">${match}</button></li>`
  });

  var suggestions = document.querySelectorAll('.suggestion');
  suggestions.forEach(suggestion => {
    suggestion.addEventListener('click', () => {
      document.querySelector('.search').value = suggestion.textContent;
    });
  });
}
var search = document.querySelector('.search')

search.addEventListener('change', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

search.addEventListener('keyup', () => {
  var searchText = document.querySelector('.search').value
  autocomplete();
});

function autocomplete () {
  var searchText = document.querySelector('.search').value

  fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/autocomplete?&text=${searchText}&latitude=37.3351534&longitude=-122.0352478`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${access_token}`,
    }
  }).then((res) => {
    return res.json();
  }).then((data) => {
    var allData = [];
    allData.push(data);
    console.log(allData);
    let businesses = allData[0].businesses
    let categories = allData[0].categories
    let terms = allData[0].terms

    let matches = [];

    businesses.forEach(business => {
      matches.push(business.name);
    });

    categories.forEach(category => {
      matches.push(category.title);
    });

    terms.forEach(term => {
      matches.push(term.text);
    });
    displaMatches(matches);
  });
}

I can see buttons being added successfully to the menu on the page. However, when I tried to access a button using the class name "suggestion", what I got is null. What did I do wrong?

I changed my codes and the displayMatches function is now working fine. However, after I added the suggestion to the search box, the search button no longer works. If I disable the suggestion function, and type my own words into the search box, I can search anything with no problem. Can anyone explain why?


问:
Turn a lazy graph into a strict graph without mutation - OCaml
Assume I have a (directed) graph with nodes of type

```<code>type lazy_node_t = LazyNode of int * lazy_node_t Lazy.t list;;
</code>```

where the first int is an arbitrary tag, and the list is a list of lazy nodes accessible from the current node.

Is there any way I can turn this into a graph of type node_t = Node of int * node_t list, without using any mutable values? I realize it's possible using arrays, for instance.

Thanks!

答:
I do not know why you want to avoid mutable values, but I assume the reason implies that efficiency is not an issue.

In principle you can turn any algorithm that uses mutable values into one that doesn't. In the case of arrays in particular, you can use Map.Make(Int).t instead, where Int is struct type t=int let compare=compare end.

UPDATE:

Just to clarify: With what I have in mind the integers in the module Int do not have anything to do with the graph tags. They are indices into the replacement for the arrays.

My answer is based on the assumption, though, that you need the arrays only as intermediate structures. That is you have a solution using arrays that outputs the desired value of type node_t = Node of int * node_t list. Jeffrey Scofield's answer suggests that I might have misunderstood; that you only have a solution that outputs a value of type node_t = Node of int * node_t array. In that case my answer is of no help.

Body:
Assume I have a (directed) graph with nodes of type

type lazy_node_t = LazyNode of int * lazy_node_t Lazy.t list;;

where the first int is an arbitrary tag, and the list is a list of lazy nodes accessible from the current node.

Is there any way I can turn this into a graph of type node_t = Node of int * node_t list, without using any mutable values? I realize it's possible using arrays, for instance.

Thanks!