问:
Position of `@` label in Kotlin when denoting receiver with `this`
I am a newbie in Kotlin. I am curious about the difference of labeled this in Kotlin with prefix @ or postfix @.

I have just seen a code which writes SignInActivity@this, which seems to work exactly same as this@SignInActivity.

Are these two exactly the same thing? If not, what is the difference between the two?

I was trying to do some research on *@this form, but I couldn't find any reference on it. All I could find was this official doc which demonstrates this@*. It will be nice if anybody could share me with the correct reference I should go to.

答:
SignInActivity@ this is just another expression for this, with the functionality of defining an unnecessary label called SignInActivity(which has nothing to do with actual class name) for this.

According to Kotlin grammar documentation:

```<code>labelReference (used by atomicExpression, jump)
   : "@" ++ LabelName
   ;
labelDefinition (used by prefixUnaryOperation, annotatedLambda)
  : LabelName ++ "@"
  ;
</code>```

hello@ is just a label with the name "hello" (for Returns and Jumps) ,

whereas @hello is a reference for the labeled loop or block.

These expressions combined can be used as below:

```<code>loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop //jump to loop@
   }
}
</code>```

Body:
SignInActivity@ this is just another expression for this, with the functionality of defining an unnecessary label called SignInActivity(which has nothing to do with actual class name) for this.

According to Kotlin grammar documentation:

labelReference (used by atomicExpression, jump)
   : "@" ++ LabelName
   ;
labelDefinition (used by prefixUnaryOperation, annotatedLambda)
  : LabelName ++ "@"
  ;

hello@ is just a label with the name "hello" (for Returns and Jumps) ,

whereas @hello is a reference for the labeled loop or block.

These expressions combined can be used as below:

loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop //jump to loop@
   }
}


来源: stackexchange

问:
XMS - how to restore connection to WebSphere SIBus after network outage
I'm connecting to a JMS queue. The queue is hosted by WebSphere Application Server (version 8.0.0.5), using SIBus.

I have a simple program to reproduce some problematic behavior, it is written in C# and uses XMS (IBM's .NET API) to connect to the queue. Note: I obtained the IBM.XMS dlls from here: MQC71: WebSphere MQ V7.1 Clients

The scenario is this:

run the program (use an empty queue, so it sits waiting on a blocking Receive call)

disconnect network (unplug ethernet)

after a few minutes, the Receive call throws an exception

the program attempts to connect anew

this fails due to the network being down

...let it loop a bit to verify this error keeps occurring

restore the network (plug in ethernet)

the same error continues to occur (verified with WireShark that no network traffic occurs during the connectionFactory.CreateConnection() call)

So, the question is: why does the CreateConnection() call do nothing (does not send any packets) but fail?

```<code>using IBM.XMS;
using System;

namespace SimpleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    string queueURI = "queue://your.details.GoHereDearReader";
                    string providerEndpoint = "1.2.3.4:1234";
                    string targetTransportChain = "InboundBasicMessaging";
                    string busName = "some_bus_name";

                    XMSFactoryFactory factoryFactory = XMSFactoryFactory.GetInstance(XMSC.CT_WPM);
                    IConnectionFactory connectionFactory = factoryFactory.CreateConnectionFactory();
                    connectionFactory.SetStringProperty(XMSC.WPM_PROVIDER_ENDPOINTS, providerEndpoint);
                    connectionFactory.SetStringProperty(XMSC.WPM_TARGET_TRANSPORT_CHAIN, targetTransportChain);
                    connectionFactory.SetStringProperty(XMSC.WPM_BUS_NAME, busName);

                    Log("Connecting...");
                    using (var connection = connectionFactory.CreateConnection())
                    {
                        using (var session = connection.CreateSession(false, AcknowledgeMode.AutoAcknowledge))
                        {
                            using (var destination = session.CreateQueue(queueURI))
                            {
                                destination.SetIntProperty(XMSC.DELIVERY_MODE, XMSC.DELIVERY_NOT_PERSISTENT);
                                connection.Start();

                                using (IMessageConsumer consumer =  session.CreateConsumer(destination))
                                {
                                    Log("Receiving...");
                                    IMessage recvMsg = consumer.Receive();
                                    Log("recvMsg:" + recvMsg);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Log(e.ToString());
                }
                Log("Sleeping some before consuming more...");
                System.Threading.Thread.Sleep(10 * 1000);
            }//while
        }//Main

        static void Log(string text)
        {
            Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + "--------------------------  " + text);
        }

    }
}
</code>```

And some output:

```<code>16:38:19.483--------------------------  Connecting...
16:38:19.936--------------------------  Receiving...
16:43:31.952--------------------------  IBM.XMS.XMSException: EXCEPTION_RECEIVED_CWSIA0022
EXCEPTION_RECEIVED_CWSIA0022.explanation
EXCEPTION_RECEIVED_CWSIA0022.useraction
   at IBM.XMS.Impl.Connection.Dispose(Boolean disposing)
   at IBM.XMS.Impl.Connection.Dispose()
   at SimpleTest.Program.Main(String[] args) in c:\Users\Administrator\Documents\Visual Studio Projects\TestJMSDequeue\SimpleTest\Program.cs:line 43

Linked Exception : IBM.XMS.SIB.JFAP.JFapConversationClosedException: Exception of type 'IBM.XMS.SIB.JFAP.JFapConversationClosedException' was thrown.
   at IBM.XMS.SIB.JFAP.ConversationImpl.Send(IByteBuffer[] data, JFAPSegmentType segmentType, UInt16 requestNumber, IoPriority priority, Boolean pooledBufferHint, IReceiveListener recvListener, ISendListener sendListener, Object state)
   at IBM.XMS.SIB.JFAP.ConversationImpl.RequestReplyExchange(IByteBuffer[] data, JFAPSegmentType segmentType, UInt16 requestNumber, IoPriority priority, Boolean pooledBufferHint)
   at IBM.XMS.SIB.JFAP.ConversationImpl.RequestReplyExchange(IByteBuffer data, JFAPSegmentType segmentType, UInt16 requestNumber, IoPriority priority, Boolean pooledBufferHint)
   at IBM.XMS.SIB.Comms.Client.JFAPCommunicator.RequestReplyExchange(IByteBuffer data, JFAPSegmentType sendSegType, MessagePriority priority, Boolean canPoolOnReceive)
   at IBM.XMS.SIB.Comms.Client.ConnectionProxy.Close()
   at IBM.XMS.Impl.Connection.Dispose(Boolean disposing)
16:43:31.952--------------------------  Sleeping some before consuming more...
16:43:41.967--------------------------  Connecting...
Exception  : System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
FFDC to xmsffdc8416_2013.03.08T10.43.41.967444.txt
Exception  : IBM.XMS.Formats.MFP.MessageEncodeFailedException: Exception of type 'IBM.XMS.Formats.MFP.MessageEncodeFailedException' was thrown. ---> System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   --- End of inner exception stack trace ---
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   at IBM.XMS.Formats.MFP.SIB.TrmFirstContactMessageImpl.Encode(Object connection)
   at IBM.XMS.SIB.Trm.ClientBootstrapHandler.Connect(IClientConnection clientConnection)
FFDC to xmsffdc8416_2013.03.08T10.43.41.983044.txt
16:43:41.983--------------------------  IBM.XMS.XMSException: EXCEPTION_RECEIVED_CWSIA0241
EXCEPTION_RECEIVED_CWSIA0241.explanation
EXCEPTION_RECEIVED_CWSIA0241.useraction
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection()
   at SimpleTest.Program.Main(String[] args) in c:\Users\Administrator\Documents\Visual Studio Projects\TestJMSDequeue\SimpleTest\Program.cs:line 26

Linked Exception : IBM.XMS.Core.SIResourceException: CWSIT0006E: It is not possible to connect to bus your_bus_name_here because the following bootstrap servers could not be contacted  1.2.3.4:1234:BootstrapBasicMessaging and the following bootstrap servers returned an error condition . See previous messages for the reason for each bootstrap server failure.
The client cannot connect to the bus. This situation may be due to configuration problems, network problems or it may be that none of the required bootstrap servers or messaging engines are currently available.
Ensure that the network is working correctly and that the required bootstrap servers and messaging engines are available. ---> IBM.XMS.Core.SIConnectionLostException: Exception of type 'IBM.XMS.Core.SIConnectionLostException' was thrown.
   at IBM.XMS.SIB.Comms.Client.ClientSideConnection.Connect(ConnectionProperties cp, IClientComponentHandshake cch, SICoreConnectionProperties siProps)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   --- End of inner exception stack trace ---
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.CreateConnection(Credentials credentials, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactory.CreateConnection(String username, String password, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
16:43:41.983--------------------------  Sleeping some before consuming more...
16:43:51.998--------------------------  Connecting...
Exception  : System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
FFDC to xmsffdc8416_2013.03.08T10.43.51.998262.txt
Exception  : IBM.XMS.Formats.MFP.MessageEncodeFailedException: Exception of type 'IBM.XMS.Formats.MFP.MessageEncodeFailedException' was thrown. ---> System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   --- End of inner exception stack trace ---
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   at IBM.XMS.Formats.MFP.SIB.TrmFirstContactMessageImpl.Encode(Object connection)
   at IBM.XMS.SIB.Trm.ClientBootstrapHandler.Connect(IClientConnection clientConnection)
FFDC to xmsffdc8416_2013.03.08T10.43.51.998262.txt
16:43:51.998--------------------------  IBM.XMS.XMSException: EXCEPTION_RECEIVED_CWSIA0241
EXCEPTION_RECEIVED_CWSIA0241.explanation
EXCEPTION_RECEIVED_CWSIA0241.useraction
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection()
   at SimpleTest.Program.Main(String[] args) in c:\Users\Administrator\Documents\Visual Studio Projects\TestJMSDequeue\SimpleTest\Program.cs:line 26

Linked Exception : IBM.XMS.Core.SIResourceException: CWSIT0006E: It is not possible to connect to bus your_bus_name_here because the following bootstrap servers could not be contacted  1.2.3.4:1234:BootstrapBasicMessaging and the following bootstrap servers returned an error condition . See previous messages for the reason for each bootstrap server failure.
The client cannot connect to the bus. This situation may be due to configuration problems, network problems or it may be that none of the required bootstrap servers or messaging engines are currently available.
Ensure that the network is working correctly and that the required bootstrap servers and messaging engines are available. ---> IBM.XMS.Core.SIConnectionLostException: Exception of type 'IBM.XMS.Core.SIConnectionLostException' was thrown.
   at IBM.XMS.SIB.Comms.Client.ClientSideConnection.Connect(ConnectionProperties cp, IClientComponentHandshake cch, SICoreConnectionProperties siProps)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   --- End of inner exception stack trace ---
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.CreateConnection(Credentials credentials, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactory.CreateConnection(String username, String password, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
16:43:51.998--------------------------  Sleeping some before consuming more...
16:44:02.013--------------------------  Connecting...
Exception  : System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
FFDC to xmsffdc8416_2013.03.08T10.44.02.013479.txt
Exception  : IBM.XMS.Formats.MFP.MessageEncodeFailedException: Exception of type 'IBM.XMS.Formats.MFP.MessageEncodeFailedException' was thrown. ---> System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   --- End of inner exception stack trace ---
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   at IBM.XMS.Formats.MFP.SIB.TrmFirstContactMessageImpl.Encode(Object connection)
   at IBM.XMS.SIB.Trm.ClientBootstrapHandler.Connect(IClientConnection clientConnection)
FFDC to xmsffdc8416_2013.03.08T10.44.02.013479.txt
16:44:02.013--------------------------  IBM.XMS.XMSException: EXCEPTION_RECEIVED_CWSIA0241
EXCEPTION_RECEIVED_CWSIA0241.explanation
EXCEPTION_RECEIVED_CWSIA0241.useraction
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection()
   at SimpleTest.Program.Main(String[] args) in c:\Users\Administrator\Documents\Visual Studio Projects\TestJMSDequeue\SimpleTest\Program.cs:line 26

Linked Exception : IBM.XMS.Core.SIResourceException: CWSIT0006E: It is not possible to connect to bus your_bus_name_here because the following bootstrap servers could not be contacted  1.2.3.4:1234:BootstrapBasicMessaging and the following bootstrap servers returned an error condition . See previous messages for the reason for each bootstrap server failure.
The client cannot connect to the bus. This situation may be due to configuration problems, network problems or it may be that none of the required bootstrap servers or messaging engines are currently available.
Ensure that the network is working correctly and that the required bootstrap servers and messaging engines are available. ---> IBM.XMS.Core.SIConnectionLostException: Exception of type 'IBM.XMS.Core.SIConnectionLostException' was thrown.
   at IBM.XMS.SIB.Comms.Client.ClientSideConnection.Connect(ConnectionProperties cp, IClientComponentHandshake cch, SICoreConnectionProperties siProps)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   --- End of inner exception stack trace ---
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.CreateConnection(Credentials credentials, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactory.CreateConnection(String username, String password, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
16:44:02.013--------------------------  Sleeping some before consuming more...
</code>```

Note that in the above output I unplugged the network shortly after "Receiving..." and plugged it in again at 16:43:52, but the errors continued after that until I killed the program.

答:
I know this is an old post, but maybe it will be still helpful.

You receive this error after you created 65.535 connections. It doesn't matter if you close the connection / dispose the object.

I see the following solutions:

1.) You can either create a connection once and reuse the connection for all your operations on the queue, until the connection breaks. Then you have to do a reconnect. (yes that's bad and against the common patterns. I wouldn't advice to do this)

2.) There is a bugfix for the version 8.0.0.6 available. EDIT: APAR #(IJ01244)
I don't know yet when it will included into future releases.
I guess you can contact the IBM support and refer to this PMR ID to receive an updated version of the IBM.XMS.SIB.dll

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm connecting to a JMS queue. The queue is hosted by WebSphere Application Server (version 8.0.0.5), using SIBus.

I have a simple program to reproduce some problematic behavior, it is written in C# and uses XMS (IBM's .NET API) to connect to the queue. Note: I obtained the IBM.XMS dlls from here: MQC71: WebSphere MQ V7.1 Clients

The scenario is this:

run the program (use an empty queue, so it sits waiting on a blocking Receive call)

disconnect network (unplug ethernet)

after a few minutes, the Receive call throws an exception

the program attempts to connect anew

this fails due to the network being down

...let it loop a bit to verify this error keeps occurring

restore the network (plug in ethernet)

the same error continues to occur (verified with WireShark that no network traffic occurs during the connectionFactory.CreateConnection() call)

So, the question is: why does the CreateConnection() call do nothing (does not send any packets) but fail?

using IBM.XMS;
using System;

namespace SimpleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    string queueURI = "queue://your.details.GoHereDearReader";
                    string providerEndpoint = "1.2.3.4:1234";
                    string targetTransportChain = "InboundBasicMessaging";
                    string busName = "some_bus_name";

                    XMSFactoryFactory factoryFactory = XMSFactoryFactory.GetInstance(XMSC.CT_WPM);
                    IConnectionFactory connectionFactory = factoryFactory.CreateConnectionFactory();
                    connectionFactory.SetStringProperty(XMSC.WPM_PROVIDER_ENDPOINTS, providerEndpoint);
                    connectionFactory.SetStringProperty(XMSC.WPM_TARGET_TRANSPORT_CHAIN, targetTransportChain);
                    connectionFactory.SetStringProperty(XMSC.WPM_BUS_NAME, busName);

                    Log("Connecting...");
                    using (var connection = connectionFactory.CreateConnection())
                    {
                        using (var session = connection.CreateSession(false, AcknowledgeMode.AutoAcknowledge))
                        {
                            using (var destination = session.CreateQueue(queueURI))
                            {
                                destination.SetIntProperty(XMSC.DELIVERY_MODE, XMSC.DELIVERY_NOT_PERSISTENT);
                                connection.Start();

                                using (IMessageConsumer consumer =  session.CreateConsumer(destination))
                                {
                                    Log("Receiving...");
                                    IMessage recvMsg = consumer.Receive();
                                    Log("recvMsg:" + recvMsg);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Log(e.ToString());
                }
                Log("Sleeping some before consuming more...");
                System.Threading.Thread.Sleep(10 * 1000);
            }//while
        }//Main

        static void Log(string text)
        {
            Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + "--------------------------  " + text);
        }

    }
}

And some output:

16:38:19.483--------------------------  Connecting...
16:38:19.936--------------------------  Receiving...
16:43:31.952--------------------------  IBM.XMS.XMSException: EXCEPTION_RECEIVED_CWSIA0022
EXCEPTION_RECEIVED_CWSIA0022.explanation
EXCEPTION_RECEIVED_CWSIA0022.useraction
   at IBM.XMS.Impl.Connection.Dispose(Boolean disposing)
   at IBM.XMS.Impl.Connection.Dispose()
   at SimpleTest.Program.Main(String[] args) in c:\Users\Administrator\Documents\Visual Studio Projects\TestJMSDequeue\SimpleTest\Program.cs:line 43

Linked Exception : IBM.XMS.SIB.JFAP.JFapConversationClosedException: Exception of type 'IBM.XMS.SIB.JFAP.JFapConversationClosedException' was thrown.
   at IBM.XMS.SIB.JFAP.ConversationImpl.Send(IByteBuffer[] data, JFAPSegmentType segmentType, UInt16 requestNumber, IoPriority priority, Boolean pooledBufferHint, IReceiveListener recvListener, ISendListener sendListener, Object state)
   at IBM.XMS.SIB.JFAP.ConversationImpl.RequestReplyExchange(IByteBuffer[] data, JFAPSegmentType segmentType, UInt16 requestNumber, IoPriority priority, Boolean pooledBufferHint)
   at IBM.XMS.SIB.JFAP.ConversationImpl.RequestReplyExchange(IByteBuffer data, JFAPSegmentType segmentType, UInt16 requestNumber, IoPriority priority, Boolean pooledBufferHint)
   at IBM.XMS.SIB.Comms.Client.JFAPCommunicator.RequestReplyExchange(IByteBuffer data, JFAPSegmentType sendSegType, MessagePriority priority, Boolean canPoolOnReceive)
   at IBM.XMS.SIB.Comms.Client.ConnectionProxy.Close()
   at IBM.XMS.Impl.Connection.Dispose(Boolean disposing)
16:43:31.952--------------------------  Sleeping some before consuming more...
16:43:41.967--------------------------  Connecting...
Exception  : System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
FFDC to xmsffdc8416_2013.03.08T10.43.41.967444.txt
Exception  : IBM.XMS.Formats.MFP.MessageEncodeFailedException: Exception of type 'IBM.XMS.Formats.MFP.MessageEncodeFailedException' was thrown. ---> System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   --- End of inner exception stack trace ---
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   at IBM.XMS.Formats.MFP.SIB.TrmFirstContactMessageImpl.Encode(Object connection)
   at IBM.XMS.SIB.Trm.ClientBootstrapHandler.Connect(IClientConnection clientConnection)
FFDC to xmsffdc8416_2013.03.08T10.43.41.983044.txt
16:43:41.983--------------------------  IBM.XMS.XMSException: EXCEPTION_RECEIVED_CWSIA0241
EXCEPTION_RECEIVED_CWSIA0241.explanation
EXCEPTION_RECEIVED_CWSIA0241.useraction
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection()
   at SimpleTest.Program.Main(String[] args) in c:\Users\Administrator\Documents\Visual Studio Projects\TestJMSDequeue\SimpleTest\Program.cs:line 26

Linked Exception : IBM.XMS.Core.SIResourceException: CWSIT0006E: It is not possible to connect to bus your_bus_name_here because the following bootstrap servers could not be contacted  1.2.3.4:1234:BootstrapBasicMessaging and the following bootstrap servers returned an error condition . See previous messages for the reason for each bootstrap server failure.
The client cannot connect to the bus. This situation may be due to configuration problems, network problems or it may be that none of the required bootstrap servers or messaging engines are currently available.
Ensure that the network is working correctly and that the required bootstrap servers and messaging engines are available. ---> IBM.XMS.Core.SIConnectionLostException: Exception of type 'IBM.XMS.Core.SIConnectionLostException' was thrown.
   at IBM.XMS.SIB.Comms.Client.ClientSideConnection.Connect(ConnectionProperties cp, IClientComponentHandshake cch, SICoreConnectionProperties siProps)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   --- End of inner exception stack trace ---
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.CreateConnection(Credentials credentials, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactory.CreateConnection(String username, String password, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
16:43:41.983--------------------------  Sleeping some before consuming more...
16:43:51.998--------------------------  Connecting...
Exception  : System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
FFDC to xmsffdc8416_2013.03.08T10.43.51.998262.txt
Exception  : IBM.XMS.Formats.MFP.MessageEncodeFailedException: Exception of type 'IBM.XMS.Formats.MFP.MessageEncodeFailedException' was thrown. ---> System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   --- End of inner exception stack trace ---
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   at IBM.XMS.Formats.MFP.SIB.TrmFirstContactMessageImpl.Encode(Object connection)
   at IBM.XMS.SIB.Trm.ClientBootstrapHandler.Connect(IClientConnection clientConnection)
FFDC to xmsffdc8416_2013.03.08T10.43.51.998262.txt
16:43:51.998--------------------------  IBM.XMS.XMSException: EXCEPTION_RECEIVED_CWSIA0241
EXCEPTION_RECEIVED_CWSIA0241.explanation
EXCEPTION_RECEIVED_CWSIA0241.useraction
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection()
   at SimpleTest.Program.Main(String[] args) in c:\Users\Administrator\Documents\Visual Studio Projects\TestJMSDequeue\SimpleTest\Program.cs:line 26

Linked Exception : IBM.XMS.Core.SIResourceException: CWSIT0006E: It is not possible to connect to bus your_bus_name_here because the following bootstrap servers could not be contacted  1.2.3.4:1234:BootstrapBasicMessaging and the following bootstrap servers returned an error condition . See previous messages for the reason for each bootstrap server failure.
The client cannot connect to the bus. This situation may be due to configuration problems, network problems or it may be that none of the required bootstrap servers or messaging engines are currently available.
Ensure that the network is working correctly and that the required bootstrap servers and messaging engines are available. ---> IBM.XMS.Core.SIConnectionLostException: Exception of type 'IBM.XMS.Core.SIConnectionLostException' was thrown.
   at IBM.XMS.SIB.Comms.Client.ClientSideConnection.Connect(ConnectionProperties cp, IClientComponentHandshake cch, SICoreConnectionProperties siProps)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   --- End of inner exception stack trace ---
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.CreateConnection(Credentials credentials, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactory.CreateConnection(String username, String password, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
16:43:51.998--------------------------  Sleeping some before consuming more...
16:44:02.013--------------------------  Connecting...
Exception  : System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
FFDC to xmsffdc8416_2013.03.08T10.44.02.013479.txt
Exception  : IBM.XMS.Formats.MFP.MessageEncodeFailedException: Exception of type 'IBM.XMS.Formats.MFP.MessageEncodeFailedException' was thrown. ---> System.InvalidOperationException: UniqueLinkObject no seen on handshake.
   at IBM.XMS.Formats.MFP.SIB.SchemaManager.SendSchemas(ICommsConnection connection, JMFSchema[] schemas)
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   --- End of inner exception stack trace ---
   at IBM.XMS.Formats.MFP.SIB.JsMsgObject.Encode(Object connection)
   at IBM.XMS.Formats.MFP.SIB.TrmFirstContactMessageImpl.Encode(Object connection)
   at IBM.XMS.SIB.Trm.ClientBootstrapHandler.Connect(IClientConnection clientConnection)
FFDC to xmsffdc8416_2013.03.08T10.44.02.013479.txt
16:44:02.013--------------------------  IBM.XMS.XMSException: EXCEPTION_RECEIVED_CWSIA0241
EXCEPTION_RECEIVED_CWSIA0241.explanation
EXCEPTION_RECEIVED_CWSIA0241.useraction
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection()
   at SimpleTest.Program.Main(String[] args) in c:\Users\Administrator\Documents\Visual Studio Projects\TestJMSDequeue\SimpleTest\Program.cs:line 26

Linked Exception : IBM.XMS.Core.SIResourceException: CWSIT0006E: It is not possible to connect to bus your_bus_name_here because the following bootstrap servers could not be contacted  1.2.3.4:1234:BootstrapBasicMessaging and the following bootstrap servers returned an error condition . See previous messages for the reason for each bootstrap server failure.
The client cannot connect to the bus. This situation may be due to configuration problems, network problems or it may be that none of the required bootstrap servers or messaging engines are currently available.
Ensure that the network is working correctly and that the required bootstrap servers and messaging engines are available. ---> IBM.XMS.Core.SIConnectionLostException: Exception of type 'IBM.XMS.Core.SIConnectionLostException' was thrown.
   at IBM.XMS.SIB.Comms.Client.ClientSideConnection.Connect(ConnectionProperties cp, IClientComponentHandshake cch, SICoreConnectionProperties siProps)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   --- End of inner exception stack trace ---
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.Bootstrap(Credentials credentials, SICoreConnectionProperties connectionProperties, ClientAttachProperties cap)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactoryImpl.CreateConnection(Credentials credentials, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.SIB.Trm.TrmSICoreConnectionFactory.CreateConnection(String username, String password, SICoreConnectionProperties connectionProperties)
   at IBM.XMS.Impl.ConnectionFactory.CreateConnection(String userName, String password)
16:44:02.013--------------------------  Sleeping some before consuming more...

Note that in the above output I unplugged the network shortly after "Receiving..." and plugged it in again at 16:43:52, but the errors continued after that until I killed the program.


问:
best practice for trigger a method by user's input in angular2
I have this scenario: expecting an user's input and use that to _http.get() from server.
I have tried using keyup event, but can't manage. Any recommendation is much appreciated.

My template:

```<code><div class="col-md-8">
   <input type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate()" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
</div>
</code>```

My ts file:

```<code>populate(){
  console.log(this.workOrder);
  this._lookup.getIcrData().subscribe(res => {
    console.log(res);
  });
}
</code>```

答:
ngModelChange is usually a good option

```<code><input type="text" class="form-control"
    [(ngModel)]="workOrder"
    (ngModelChange)="populate()"
    placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
</code>```

Body:
I have this scenario: expecting an user's input and use that to _http.get() from server.
I have tried using keyup event, but can't manage. Any recommendation is much appreciated.

My template:

   <input type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate()" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>

My ts file:

populate(){
  console.log(this.workOrder);
  this._lookup.getIcrData().subscribe(res => {
    console.log(res);
  });
}

Body:
ngModelChange is usually a good option

<input type="text" class="form-control"
    [(ngModel)]="workOrder"
    (ngModelChange)="populate()"
    placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>


问:
Segmentation fault at the end of an array of strings in a while loop
Here's part of my code

```<code>char **images; // An array of strings filled with valid data

while(*images)
{
    printf("input image = %s\n", *images);
    images++;
}
</code>```

I'm expecting it to exit the loop when the end of the array is reached but it still goes inside the loop and crashes. Please suggest how to fix this issue. The number of elements in the array is not fixed.

答:
The code will not know how to stop since the while loop is always true, i.e not zero. Even if you run past the end of the array into unmarked address space the code will keep going and then segfault as you suggest.

You should always close off string data with a marker such as "\0" and perform a check in the while loop i.e:

```<code>while ( strcmp(*images, "\0") != 0 )
</code>```

or you should know the size of the **images array and stop after reading the last item. For this reason its probably better to use a for loop instead of a while loop. The strcmp version above is much less efficient. The for loop should be very efficient.

Body:
Here's part of my code

char **images; // An array of strings filled with valid data

while(*images)
{
    printf("input image = %s\n", *images);
    images++;
}

I'm expecting it to exit the loop when the end of the array is reached but it still goes inside the loop and crashes. Please suggest how to fix this issue. The number of elements in the array is not fixed.

Body:
The code will not know how to stop since the while loop is always true, i.e not zero. Even if you run past the end of the array into unmarked address space the code will keep going and then segfault as you suggest.

You should always close off string data with a marker such as "\0" and perform a check in the while loop i.e:

while ( strcmp(*images, "\0") != 0 )

or you should know the size of the **images array and stop after reading the last item. For this reason its probably better to use a for loop instead of a while loop. The strcmp version above is much less efficient. The for loop should be very efficient.


问:
Process Id of Chomium-browser not showing in terminal
I am writing a bash script and I need to kill any browser running at the time of script execution. For that I want the process id of every browser running in the background. I tried all the following, but nothing worked.  See this

 pidof chromium

 pidof chromium-browser

 pgrep chromium-browser

 ps -A | grep chromium-browser

 ps -aux | grep chromium-browser | grep pid

However,  See this . It worked for firefox browser. Can Anyone figure out If it's something wrong with command or Chromium-browser itself. Also Can anyone tell any other method to get the process id. I shall try that out by the time.

答:
You can try the following piece of script to list all pids of processes containing chromium-browser in their command name :

```<code>ps -aux | grep chromium-browser |  tr -s ' ' | cut -d ' ' -f 2
</code>```

Your other commands didn't work because the process running for chromium-browser is /usr/lib/chromium-browser/chromium-browser (at least for me on xubuntu). You can check the real process by typing ps -aux.

Note: weirdly enough, pgrep chromium-browser doesn't return anything, but pgrep chromium and pgrep chromium-browse work just fine.

pgrep -f chromium-browser is also good

Body:
You can try the following piece of script to list all pids of processes containing chromium-browser in their command name :

ps -aux | grep chromium-browser |  tr -s ' ' | cut -d ' ' -f 2

Your other commands didn't work because the process running for chromium-browser is /usr/lib/chromium-browser/chromium-browser (at least for me on xubuntu). You can check the real process by typing ps -aux.

Note: weirdly enough, pgrep chromium-browser doesn't return anything, but pgrep chromium and pgrep chromium-browse work just fine.

pgrep -f chromium-browser is also good


问:
EndDate Issue - Last Month of Year
I have a .netapp application (C#) that I use to extract data from an API.

It is having a problem just now as we are running this for December 2017.. but we want it to name as January 2018. (well 01/01/2018)

I think they way we have written it means it's looking for 13/2017 which obviously doesn't exist.

Can anyone recommend how to ammend this so we can run it just now and how we can ensure we don't run into this issue again next December?

```<code>public override string ToString()
    {
        var reportDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, 1);

        if (!String.IsNullOrWhiteSpace(AppConfigHelper.EndDate))
        {
            var year = Int32.Parse(AppConfigHelper.EndDate.Substring(6, 4));
            var month = Int32.Parse(AppConfigHelper.EndDate.Substring(3, 2));
            var day = Int32.Parse(AppConfigHelper.EndDate.Substring(0, 2));
            reportDate = new DateTime(year, month, day);
            reportDate = reportDate.AddDays(1);
        }
</code>```

答:
You can use DateTime.Today.AddMonths(1):

```<code>var nextMonth = DateTime.Today.AddMonths(1);
reportDate = new DateTme(nextMonth.Year, nextMonth.Month, 1);
// ...
</code>```

By the way, you don't need string methods and int.Parse to get the DateTime, use ParseExact:

```<code>if (!String.IsNullOrWhiteSpace(AppConfigHelper.EndDate))
{
    reportDate = DateTime.ParseExact(AppConfigHelper.EndDate, "ddMMyyyy", null);
    reportDate = reportDate.AddDays(1);
}
</code>```

Title: EndDate Issue - Last Month of Year

Body:
I have a .netapp application (C#) that I use to extract data from an API.

It is having a problem just now as we are running this for December 2017.. but we want it to name as January 2018. (well 01/01/2018)

I think they way we have written it means it's looking for 13/2017 which obviously doesn't exist.

Can anyone recommend how to ammend this so we can run it just now and how we can ensure we don't run into this issue again next December?

public override string ToString()
    {
        var reportDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, 1);

        if (!String.IsNullOrWhiteSpace(AppConfigHelper.EndDate))
        {
            var year = Int32.Parse(AppConfigHelper.EndDate.Substring(6, 4));
            var month = Int32.Parse(AppConfigHelper.EndDate.Substring(3, 2));
            var day = Int32.Parse(AppConfigHelper.EndDate.Substring(0, 2));
            reportDate = new DateTime(year, month, day);
            reportDate = reportDate.AddDays(1);
        }

Body:
You can use DateTime.Today.AddMonths(1):

var nextMonth = DateTime.Today.AddMonths(1);
reportDate = new DateTme(nextMonth.Year, nextMonth.Month, 1);
// ...

By the way, you don't need string methods and int.Parse to get the DateTime, use ParseExact:

if (!String.IsNullOrWhiteSpace(AppConfigHelper.EndDate))
{
    reportDate = DateTime.ParseExact(AppConfigHelper.EndDate, "ddMMyyyy", null);
    reportDate = reportDate.AddDays(1);
}


问:
php str_replace wont work for translating word
I am trying to add translate word for my project. But the str_replace doesn't work.

I have a database table for language.

If user choosed English then for example user see this word:

English: Mustafa went to the cinema with his friend ahmet today.

If user choosed Turkish then for example user see this word:

Turkish: Mustafa bugün arkadaşı ahmet ile birlikte sinemaya gitti.

I have used str_replace like this:

```<code>    $splaceHolder = array( "{{username}}",
                           "{{otherusername}}" );

    $sname = array( "<a href='".$base_url.$username."'>".$username."</a>",
                    "<a href='".$base_url.$otherusername."'>".$otherusername."</a>" );
</code>```

and str_replace here:

```<code>$note = str_replace($splaceHolder, $sname, $lang['text'][$lang]);
</code>```

The $lang['text'][$lang] be coming from language table and text is for English:

```<code>{{username}} went to the cinema with his friend {{otherusername}} today.
</code>```

For Turkish:

```<code>{{username}} bugün arkadaşı {{otherusername}} ile birlikte sinemaya gitti.
</code>```

str_replace doesn't work here.

It show for english this {{username}} went to the cinema with his friend {{otherusername}} today. to this Mustafa went to the cinema with his friend ahmet today.

for show for Turkish this {{username}} bugün arkadaşı {{otherusername}} ile birlikte sinemaya gitti. tho this  Mustafa bugün arkadaşı ahmet ile birlikte sinemaya gitti.

But I only geting like the following way.

{{username}} went to the cinema with his friend {{otherusername}}
  today.

答:
str_replace works for your example.

Try this:

```<code><?php
    $string = "{{username}} went to the cinema with his friend {{otherusername}} today.";

    $res = str_replace("{{username}}", "firstuser", $string);
    $res = str_replace("{{otherusername}}", "seconduser", $res);
    echo "result: ".$res."<br />";
?>
</code>```

Even you can perform both replaces with a single line:

```<code>$res = str_replace(["{{username}}", "{{otherusername}}"], ["firstuser", "seconduser"], $string);
</code>```

Works for me.

Body:
I am trying to add translate word for my project. But the str_replace doesn't work.

I have a database table for language.

If user choosed English then for example user see this word:

English: Mustafa went to the cinema with his friend ahmet today.

If user choosed Turkish then for example user see this word:

Turkish: Mustafa bugün arkadaşı ahmet ile birlikte sinemaya gitti.

I have used str_replace like this:

    $splaceHolder = array( "{{username}}",
                           "{{otherusername}}" );

    $sname = array( "".$username."",
                    "".$otherusername."" );

and str_replace here:

$note = str_replace($splaceHolder, $sname, $lang['text'][$lang]);

The $lang['text'][$lang] be coming from language table and text is for English:

{{username}} went to the cinema with his friend {{otherusername}} today.

For Turkish:

{{username}} bugün arkadaşı {{otherusername}} ile birlikte sinemaya gitti.

str_replace doesn't work here.

It show for english this {{username}} went to the cinema with his friend {{otherusername}} today. to this Mustafa went to the cinema with his friend ahmet today.

for show for Turkish this {{username}} bugün arkadaşı {{otherusername}} ile birlikte sinemaya gitti. tho this  Mustafa bugün arkadaşı ahmet ile birlikte sinemaya gitti.

But I only geting like the following way.

{{username}} went to the cinema with his friend {{otherusername}}
  today.

Body:
str_replace works for your example.

Try this:

<?php
    $string = "{{username}} went to the cinema with his friend {{otherusername}} today.";

    $res = str_replace("{{username}}", "firstuser", $string);
    $res = str_replace("{{otherusername}}", "seconduser", $res);
    echo "result: ".$res."<br />";
?>

Even you can perform both replaces with a single line:

$res = str_replace(["{{username}}", "{{otherusername}}"], ["firstuser", "seconduser"], $string);

Works for me.


问:
UISearchController iOS 11 Customization
I had been using the following code prior to iOS 11 to customize the appearance of the UISearchController search bar:

```<code>var searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.setDefaultSearchBar()
searchController.searchResultsUpdater = self

if #available(iOS 11.0, *) {
    navigationItem.searchController = searchController
} else {
    tableView.tableHeaderView = searchController.searchBar
}

extension UISearchBar {
    func setDefaultSearchBar() {
        self.tintColor = UIColor.blue
        self.searchBarStyle = .minimal
        self.backgroundImage = UIImage(color: UIColor.clear)
        let searchBarTextField = self.value(forKey: "searchField") as! UITextField
        searchBarTextField.textColor = UIColor.white
        searchBarTextField.tintColor = UIColor.blue
        searchBarTextField = .dark
    }
}
</code>```

However, the appearance of the search bar fails to update when running the same code on iOS 11.

iOS 10:

iOS 11:

Much of the attention to this question so far has focused on the text color of the search bar. I am looking at more than this - the background color, tint color, the search indicator, clear button color, etc.

答:
To properly set the text typed into the search bar to white use (when using a dark field color):

```<code>searchController.searchBar.barStyle = .black
</code>```

To set the textfield background color

```<code>if #available(iOS 11.0, *) {

        if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {
            if let backgroundview = textfield.subviews.first {

                // Background color
                backgroundview.backgroundColor = UIColor.white

                // Rounded corner
                backgroundview.layer.cornerRadius = 10;
                backgroundview.clipsToBounds = true;
            }
        }
    }
</code>```

However using something like

```<code>textfield.textColor = UIColor.blue
</code>```

in the above does not seem to work.

ContentLicense: CC BY-SA 4.0

Title: UISearchController iOS 11 Customization

Body:
I had been using the following code prior to iOS 11 to customize the appearance of the UISearchController search bar:

var searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.setDefaultSearchBar()
searchController.searchResultsUpdater = self

if #available(iOS 11.0, *) {
    navigationItem.searchController = searchController
} else {
    tableView.tableHeaderView = searchController.searchBar
}

extension UISearchBar {
    func setDefaultSearchBar() {
        self.tintColor = UIColor.blue
        self.searchBarStyle = .minimal
        self.backgroundImage = UIImage(color: UIColor.clear)
        let searchBarTextField = self.value(forKey: "searchField") as! UITextField
        searchBarTextField.textColor = UIColor.white
        searchBarTextField.tintColor = UIColor.blue
        searchBarTextField = .dark
    }
}

However, the appearance of the search bar fails to update when running the same code on iOS 11.

iOS 10:

iOS 11:

Much of the attention to this question so far has focused on the text color of the search bar. I am looking at more than this - the background color, tint color, the search indicator, clear button color, etc.

Body:
To properly set the text typed into the search bar to white use (when using a dark field color):

searchController.searchBar.barStyle = .black

To set the textfield background color

if #available(iOS 11.0, *) {

        if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {
            if let backgroundview = textfield.subviews.first {

                // Background color
                backgroundview.backgroundColor = UIColor.white

                // Rounded corner
                backgroundview.layer.cornerRadius = 10;
                backgroundview.clipsToBounds = true;
            }
        }
    }

However using something like

textfield.textColor = UIColor.blue

in the above does not seem to work.


问:
Android studio 3 issue when trying "hello world"
I'm new to android development. Hope someone could help me out..

I'm trying Android Studio 3.0.1, and try to create a project as "Hello world". All steps are just follow the default setting.

But it failed when building the project. The error message says:

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
  Required by:
      project :app
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Connect to dl.google.com:443 [dl.google.com/127.0.1.4] failed: Connection refused: connect
  Connection refused: connect

I searched around in google and stackoverflow. There's some hint saying that in Android Studio 3.0+ I should modify build.gradle file with the repositories section and the dependencies  section: https://developer.android.com/topic/libraries/support-library/setup.html

```<code>allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
</code>```

And I did that.

Here's my top level build.gradle file:

```<code> // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

And here's my app/build.gradle file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.android.happybirthday"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:appcompat-v7:26.1.0'
}
</code>```

then I got the error message:

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
  Required by:
      project :app
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not get resource 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Could not GET 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Connect to jcenter.bintray.com:443 [jcenter.bintray.com/127.0.1.2] failed: Connection refused: connect
  Connection refused: connect

I'm using proxy connection but the network should be ok.

I do appreciate if anyone could give me some guide. Thanks.

Zong

答:
try to remove

```<code>  testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
</code>```

these line from your app/build.gradle file and then clean project -> rebuild
this may help

Body:
I'm new to android development. Hope someone could help me out..

I'm trying Android Studio 3.0.1, and try to create a project as "Hello world". All steps are just follow the default setting.

But it failed when building the project. The error message says:

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
  Required by:
      project :app
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Connect to dl.google.com:443 [dl.google.com/127.0.1.4] failed: Connection refused: connect
  Connection refused: connect

I searched around in google and stackoverflow. There's some hint saying that in Android Studio 3.0+ I should modify build.gradle file with the repositories section and the dependencies  section: https://developer.android.com/topic/libraries/support-library/setup.html

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

And I did that.

Here's my top level build.gradle file:

 // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
task clean(type: Delete) {
delete rootProject.buildDir
}

And here's my app/build.gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.android.happybirthday"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:appcompat-v7:26.1.0'
}

then I got the error message:

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
  Required by:
      project :app
  Could not resolve com.android.support:appcompat-v7:26.1.0.
  Could not get resource 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Could not GET 'https://jcenter.bintray.com/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
  Connect to jcenter.bintray.com:443 [jcenter.bintray.com/127.0.1.2] failed: Connection refused: connect
  Connection refused: connect

I'm using proxy connection but the network should be ok.

I do appreciate if anyone could give me some guide. Thanks.

Zong

Body:
try to remove

  testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

these line from your app/build.gradle file and then clean project -> rebuild
this may help


问:
Python: Access "field" in line
I have the following .txt-File (modified bash emboss-dreg report, the original report has seqtable format):

```<code>Start     End  Strand Pattern                                                     Sequence

  43392   43420       + regex:[T][G][A][TC][C][CTG]\D{15,17}[CA][G][T][AT][AT][CTA] TGATCGCACGCCGAATGGAAACACGTTTT

  52037   52064       + regex:[T][G][A][TC][C][CTG]\D{15,17}[CA][G][T][AT][AT][CTA] TGACCCTGCTTGGCGATCCCGGCGTTTC

 188334  188360       + regex:[T][G][A][TC][C][CTG]\D{15,17}[CA][G][T][AT][AT][CTA] TGATCGCGCAACTGCAGCGGGAGTTAC
</code>```

I would like to access the elements under "sequence" only, to compare them with some variables and delete the whole lines, if the comparison does not give the desired result (using Levenshtein distance for comparison).

But I can't even get started .... :(

I am searching for something like the linux -f option, to directly get to the right "field" in the line to do my comparison.

I came across re.split:

```<code>with open(textFile) as f:
    for line in f:
        cleaned=re.split(r'\t',line)
        print(cleaned)
</code>```

which results in:

```<code>['  Start     End  Strand Pattern                                                     Sequence\n']
['\n']
['  43392   43420       + regex:[T][G][A][TC][C][CTG]\\D{15,17}[CA][G][T][AT][AT][CTA] TGATCGCACGCCGAATGGAAACACGTTTT\n']
['\n']
['  52037   52064       + regex:[T][G][A][TC][C][CTG]\\D{15,17}[CA][G][T][AT][AT][CTA] TGACCCTGCTTGGCGATCCCGGCGTTTC\n']
['\n']
[' 188334  188360       + regex:[T][G][A][TC][C][CTG]\\D{15,17}[CA][G][T][AT][AT][CTA] TGATCGCGCAACTGCAGCGGGAGTTAC\n']
['\n']
</code>```

That is the closest I got to "split my lines into elements". I feel like totally going the wrong way, but searching Stack Overflow and google did not result in anything :(

I have never worked with seqtable-format before, so I tried to deal with it as .txt Maybe, there is another approach better for dealing with it?

Python is the main language I am learning, I am not so firm in Bash, but bash-answers for dealing with the issue would be ok for me, too.

I am thankful for any hint/link/help :)

答:
The format itself seems to be using multiple lines as delimiters while your r'\t' is not doing anything (you're instructing Python to split on a literal \t). Also, based on what you've pasted the data is not using a tab delimiter anyway, but a random number of whitespaces to pad the table.

To address both, you can read the file, treat the first line as a header (if you need it), then read the rest line by line, strip the trailing\leading whitespace, check if there is any data there and if there is - further split it on whitespace to get to your line elements:

```<code>with open("your_data", "r") as f:
    header = f.readline().split()  # read the first line as a header
    for line in f:  # read the rest of the file line-by-line
        line = line.strip()  # first clear out the whitespace
        if line:  # check if there is any content left or is it an empty line
            elements = line.split()  # split the data on whitespace to get your elements
            print(elements[-1])  # print the last element
</code>```

```
TGATCGCACGCCGAATGGAAACACGTTTT
TGACCCTGCTTGGCGATCCCGGCGTTTC
TGATCGCGCAACTGCAGCGGGAGTTAC
```

As a bonus, since you have the header, you can turn it into a map and then use 'proxied' named access to get the element you're looking for so you don't need to worry about the element position:

```<code>with open("your_data", "r") as f:
    # read the header and turn it into a value:index map
    header = {v: i for i, v in enumerate(f.readline().split())}
    for line in f:  # read the rest of the file line-by-line
        line = line.strip()  # first clear out the whitespace
        if line:  # check if there is any content left or is it an empty line
            elements = line.split()
            print(elements[header["Sequence"]])  # print the Sequence element
</code>```

You can also use a header map to turn your rows into dict structures for even easier access.

UPDATE: Here's how to create a header map and then use it to build a dict out of your lines:

```<code>with open("your_data", "r") as f:
    # read the header and turn it into an index:value map
    header = {i: v for i, v in enumerate(f.readline().split())}
    for line in f:  # read the rest of the file line-by-line
        line = line.strip()  # first clear out the whitespace
        if line:  # check if there is any content left or is it an empty line
            # split the line, iterate over it and use the header map to create a dict
            row = {header[i]: v for i, v in enumerate(line.split())}
            print(row["Sequence"])  # ... or you can append it to a list for later use
</code>```

As for how to 'delete' lines that you don't want for some reason, you'll have to create a temporary file, loop through your original file, compare your values, write the ones that you want to keep into the temporary file, delete the original file and finally rename the temporary file to match your original file, something like:

```<code>import shutil
from tempfile import NamedTemporaryFile

SOURCE_FILE = "your_data"  # path to the original file to process

def compare_func(seq):  # a simple comparison function for our sequence
    return not seq.endswith("TC")  # use Levenshtein distance or whatever you want instead

# open a temporary file for writing and our source file for reading
with NamedTemporaryFile(mode="w", delete=False) as t, open(SOURCE_FILE, "r") as f:
    header_line = f.readline()  # read the header
    t.write(header_line)  # write the header immediately to the temporary file
    header = {v: i for i, v in enumerate(header_line.split())}  # create a header map
    last_line = ""  # a var to store the whitespace to keep the same format
    for line in f:  # read the rest of the file line-by-line
        row = line.strip()  # first clear out the whitespace
        if row:  # check if there is any content left or is it an empty line
            elements = row.split()  # split the row into elements
            # now lets call our comparison function
            if compare_func(elements[header["Sequence"]]):  # keep the line if True
                t.write(last_line)  # write down the last whitespace to the temporary file
                t.write(line)  # write down the current line to the temporary file
        else:
            last_line = line  # store the whitespace for later use
shutil.move(t.name, SOURCE_FILE)  # finally, overwrite the source with the temporary file
</code>```

This will produce the same file sans the second row from your example since its sequence ends in a TC and our comp_function() returns False in that case.

For a bit less complexity, instead of using temporary files you can load your whole source file into the working memory and then just overwrite it, but that would work only for files that can fit your working memory while the above approach can work with files as large as your free storage space.

Title: Python: Access "field" in line

Body:
I have the following .txt-File (modified bash emboss-dreg report, the original report has seqtable format):

Start     End  Strand Pattern                                                     Sequence

  43392   43420       + regex:[T][G][A][TC][C][CTG]\D{15,17}[CA][G][T][AT][AT][CTA] TGATCGCACGCCGAATGGAAACACGTTTT

  52037   52064       + regex:[T][G][A][TC][C][CTG]\D{15,17}[CA][G][T][AT][AT][CTA] TGACCCTGCTTGGCGATCCCGGCGTTTC

 188334  188360       + regex:[T][G][A][TC][C][CTG]\D{15,17}[CA][G][T][AT][AT][CTA] TGATCGCGCAACTGCAGCGGGAGTTAC

I would like to access the elements under "sequence" only, to compare them with some variables and delete the whole lines, if the comparison does not give the desired result (using Levenshtein distance for comparison).

But I can't even get started .... :(

I am searching for something like the linux -f option, to directly get to the right "field" in the line to do my comparison.

I came across re.split:

with open(textFile) as f:
    for line in f:
        cleaned=re.split(r'\t',line)
        print(cleaned)

which results in:

['  Start     End  Strand Pattern                                                     Sequence\n']
['\n']
['  43392   43420       + regex:[T][G][A][TC][C][CTG]\\D{15,17}[CA][G][T][AT][AT][CTA] TGATCGCACGCCGAATGGAAACACGTTTT\n']
['\n']
['  52037   52064       + regex:[T][G][A][TC][C][CTG]\\D{15,17}[CA][G][T][AT][AT][CTA] TGACCCTGCTTGGCGATCCCGGCGTTTC\n']
['\n']
[' 188334  188360       + regex:[T][G][A][TC][C][CTG]\\D{15,17}[CA][G][T][AT][AT][CTA] TGATCGCGCAACTGCAGCGGGAGTTAC\n']
['\n']

That is the closest I got to "split my lines into elements". I feel like totally going the wrong way, but searching Stack Overflow and google did not result in anything :(

I have never worked with seqtable-format before, so I tried to deal with it as .txt Maybe, there is another approach better for dealing with it?

Python is the main language I am learning, I am not so firm in Bash, but bash-answers for dealing with the issue would be ok for me, too.

I am thankful for any hint/link/help :)

Body:
The format itself seems to be using multiple lines as delimiters while your r'\t' is not doing anything (you're instructing Python to split on a literal \t). Also, based on what you've pasted the data is not using a tab delimiter anyway, but a random number of whitespaces to pad the table.

To address both, you can read the file, treat the first line as a header (if you need it), then read the rest line by line, strip the trailing\leading whitespace, check if there is any data there and if there is - further split it on whitespace to get to your line elements:

with open("your_data", "r") as f:
    header = f.readline().split()  # read the first line as a header
    for line in f:  # read the rest of the file line-by-line
        line = line.strip()  # first clear out the whitespace
        if line:  # check if there is any content left or is it an empty line
            elements = line.split()  # split the data on whitespace to get your elements
            print(elements[-1])  # print the last element

TGATCGCACGCCGAATGGAAACACGTTTT
TGACCCTGCTTGGCGATCCCGGCGTTTC
TGATCGCGCAACTGCAGCGGGAGTTAC

As a bonus, since you have the header, you can turn it into a map and then use 'proxied' named access to get the element you're looking for so you don't need to worry about the element position:

with open("your_data", "r") as f:
    # read the header and turn it into a value:index map
    header = {v: i for i, v in enumerate(f.readline().split())}
    for line in f:  # read the rest of the file line-by-line
        line = line.strip()  # first clear out the whitespace
        if line:  # check if there is any content left or is it an empty line
            elements = line.split()
            print(elements[header["Sequence"]])  # print the Sequence element

You can also use a header map to turn your rows into dict structures for even easier access.

UPDATE: Here's how to create a header map and then use it to build a dict out of your lines:

with open("your_data", "r") as f:
    # read the header and turn it into an index:value map
    header = {i: v for i, v in enumerate(f.readline().split())}
    for line in f:  # read the rest of the file line-by-line
        line = line.strip()  # first clear out the whitespace
        if line:  # check if there is any content left or is it an empty line
            # split the line, iterate over it and use the header map to create a dict
            row = {header[i]: v for i, v in enumerate(line.split())}
            print(row["Sequence"])  # ... or you can append it to a list for later use

As for how to 'delete' lines that you don't want for some reason, you'll have to create a temporary file, loop through your original file, compare your values, write the ones that you want to keep into the temporary file, delete the original file and finally rename the temporary file to match your original file, something like:

import shutil
from tempfile import NamedTemporaryFile

SOURCE_FILE = "your_data"  # path to the original file to process

def compare_func(seq):  # a simple comparison function for our sequence
    return not seq.endswith("TC")  # use Levenshtein distance or whatever you want instead

# open a temporary file for writing and our source file for reading
with NamedTemporaryFile(mode="w", delete=False) as t, open(SOURCE_FILE, "r") as f:
    header_line = f.readline()  # read the header
    t.write(header_line)  # write the header immediately to the temporary file
    header = {v: i for i, v in enumerate(header_line.split())}  # create a header map
    last_line = ""  # a var to store the whitespace to keep the same format
    for line in f:  # read the rest of the file line-by-line
        row = line.strip()  # first clear out the whitespace
        if row:  # check if there is any content left or is it an empty line
            elements = row.split()  # split the row into elements
            # now lets call our comparison function
            if compare_func(elements[header["Sequence"]]):  # keep the line if True
                t.write(last_line)  # write down the last whitespace to the temporary file
                t.write(line)  # write down the current line to the temporary file
        else:
            last_line = line  # store the whitespace for later use
shutil.move(t.name, SOURCE_FILE)  # finally, overwrite the source with the temporary file

This will produce the same file sans the second row from your example since its sequence ends in a TC and our comp_function() returns False in that case.

For a bit less complexity, instead of using temporary files you can load your whole source file into the working memory and then just overwrite it, but that would work only for files that can fit your working memory while the above approach can work with files as large as your free storage space.


问:
Git alias on Windows: How to escape double quotes
I am on a Windows 10 Pro Machine and I am using Cmder with Git version 2.15.0.windows.1.

I want to set up an alias for the git log command with some pretty options. The command is:

```<code>log --pretty=format:"%C(yellow)%h%Cred%d %Creset%s%Cblue [%cn]" --decorate
</code>```

When I try to set the alias up by running this command:

```<code>git config --global alias.ls "log --pretty=format:"%C(yellow)%h%Cred%d %Creset%s%Cblue [%cn]" --decorate"
</code>```

It does not work, the alias is not registered. I suspect it is because I have double quotes within the command too.

I also tried wrapping it with single quotes ', but that does not work either.

How can I escape those double quotes within the command so that the alias does register?

答:
Use single quotes for the pretty=format string. </p>

```<code>git config --global alias.ls "log --pretty=format:'%C(yellow)%h%Cred%d %Creset%s%Cblue [%cn]' --decorate"
</code>```

Body:
I am on a Windows 10 Pro Machine and I am using Cmder with Git version 2.15.0.windows.1.

I want to set up an alias for the git log command with some pretty options. The command is:

log --pretty=format:"%C(yellow)%h%Cred%d %Creset%s%Cblue [%cn]" --decorate

When I try to set the alias up by running this command:

git config --global alias.ls "log --pretty=format:"%C(yellow)%h%Cred%d %Creset%s%Cblue [%cn]" --decorate"

It does not work, the alias is not registered. I suspect it is because I have double quotes within the command too.

I also tried wrapping it with single quotes ', but that does not work either.

How can I escape those double quotes within the command so that the alias does register?

Body:
Use single quotes for the pretty=format string.

git config --global alias.ls "log --pretty=format:'%C(yellow)%h%Cred%d %Creset%s%Cblue [%cn]' --decorate"


问:
Excel VBA - How to clear a dynamic range (from below header, to last row)
I have a loan amortization schedule that creates the amortization schedule depending on the periods, how can I clear the range, before running the loan amortization again? For example, if I run it for a 10 year period, then run it for a 5 year period, years 6-10 still show up because they haven't been cleared.

Here is my code:

```<code>outRow = 3
With Sheets("Loan")
lCol = .Cells(3, .Columns.Count).End(xlToLeft).Column
lrow = .Cells(.Rows.Count, lCol).End(xlUp).Row
End With

Sheets("Loan").Range(Cells(outRow, 5), Cells(Lastrow, lastCol)).ClearContents
</code>```

答:
If you add "+1" after .Row you will keep the headings in case the file is empty. [if it is empty and the code runs without "+1" it will erase the headings]</p>

```<code>Dim Lastrow As Long
Lastrow = Range("A" & Rows.Count).End(xlUp).Row +1
Range("A2:A" & Lastrow).Clear
</code>```

Body:
I have a loan amortization schedule that creates the amortization schedule depending on the periods, how can I clear the range, before running the loan amortization again? For example, if I run it for a 10 year period, then run it for a 5 year period, years 6-10 still show up because they haven't been cleared.

Here is my code:

outRow = 3
With Sheets("Loan")
lCol = .Cells(3, .Columns.Count).End(xlToLeft).Column
lrow = .Cells(.Rows.Count, lCol).End(xlUp).Row
End With

Sheets("Loan").Range(Cells(outRow, 5), Cells(Lastrow, lastCol)).ClearContents

Body:
If you add "+1" after .Row you will keep the headings in case the file is empty. [if it is empty and the code runs without "+1" it will erase the headings]

Dim Lastrow As Long
Lastrow = Range("A" & Rows.Count).End(xlUp).Row +1
Range("A2:A" & Lastrow).Clear


问:
How to get access to uiTableViewCell which are not selected in Swift 3?
So basically I know that I can get all the selected cells using "selectedIndexPathRows". But I want to change behavior of cells which are not selected. Also I want to know which cells are not selected on didSelect or didDeselect .
Basically, what I want to achieve is to get all the cells which are not selected and set their alpha to 0.5 and set 1.0 of only selected cells, how can I do that?
Any help would be appreciated.

答:
Easiest way to configure tableViewCell on select or deselect event.
Only override 'setSelected' method in subclass of UITableViewCell.</p>

```<code>override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    if selected{
        //configure on select
        //alpha = 1.0
    }else{
        //configure on deselect
        //alpha = 0.5
    }
}
</code>```

Body:
Easiest way to configure tableViewCell on select or deselect event.
Only override 'setSelected' method in subclass of UITableViewCell.

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    if selected{
        //configure on select
        //alpha = 1.0
    }else{
        //configure on deselect
        //alpha = 0.5
    }
}


问:
State machine and toggling states in a loop
I've got an application running on a BeagleBone Black controlling some hardware. The user interface consists of an LCD display and a rotary encoder switch with an integrated push button.

In terms of state transitions, all what the application does is to react to push button events to switch between them:

Initial state: "manual"

Push event: toggle state to next ("auto"), do auto actions

Push event: toggle state to next ("manual"), do manual actions

In summary, there are two states, and the trigger is the button push, which actually toggles between the two.

The current code is an infinite loop with an if ... else condition that executes either the "manual" mode or "auto" mode actions depending on the state. A delay is added at the end of the loop. The manual variable is updated (toggled) by an interrupt whenever a push button event is detected.

```<code>while True:
    # Toggle mode when the push button event is detected
    # It can also be detected asynchronously outside the loop,
    # but we'll keep it on the loop for a smaller example
    if gpio.event_detected(push_button):
        manual_mode = not manual_mode

    if manual_mode:
        # MANUAL MODE:
        do_user_input_actions()
    else:
        # AUTO mode
        do_automatic_actions()

   time.sleep(0.5)
</code>```

This construct is similar to the C equivalent that I've used a few times before. But I was wondering of a more object-oriented way of doing the same in Python.

Essentially, it seems that the logic would lend itself to using pytransitions, particularly if I need to add more states in the future, so I'm considering porting the code to it.

I can picture the two states and the transitions:

```<code>states = ['manual', 'sweep']
transitions = [['handle_manual_input', 'auto', 'manual'],
               ['run_auto_test', 'manual', 'auto']]
</code>```

However, I can't quite visualize what the proper way to implement the equivalent of my current infinite loop with the state check is in the pytranslations model.

Effectively, handling manual input should be done on each loop iteration, and not just on the transition from auto, and vice versa for running the auto mode.

I understand that the state machine should be left alone to just take care of the states and transitions for better code separation.

It's the model implementation that I can't quite picture: I'd welcome any guidance on how and where to run do_user_input_actions() and do_automatic_actions().

答:
If you are willing to (re-)enter states every cycle, this should do the trick:

```<code>from transitions import Machine
from random import choice

class Model(object):

    def on_enter_manual(self):
        # do_user_input_actions()
        print('manual')

    def on_enter_auto(self):
        # do_automatic_actions()
        print('auto')

    def event_detected(self):
        # return gpio.event_detected()
        # For simulation purposes randomise the return value
        return choice([True, False])

states = ['manual', 'auto']
transitions = [{'trigger': 'loop', 'source': ['manual', 'auto'],
                'dest': 'manual', 'conditions': 'event_detected'},
               {'trigger': 'loop', 'source': ['manual', 'auto'],
                'dest': 'auto'}]

model = Model()
machine = Machine(model=model, states=states,
                  transitions=transitions, initial='manual')

for i in range(10):
    model.loop()
</code>```

transitions processes possible transitions in the order they were added. This means that the first transition is executed when event_detected returns True. If this is not the case, the second transition will be chosen as it has no condition.

For this solution, some tweaks are possible:

a) You could replace source:[..] with source:'*' to allow a loop transitions from all states. If you want to add states in the future this might be useful, but it can also backfire if you plan to use more than one trigger.

b) In case do_user_input_actions, gpio.event_detected, do_automatic_actions are static methods, you can more or less omit the model by using the following transitions:

```<code>transitions = [{'trigger': 'loop', 'source': ['manual', 'auto'],
                'dest': 'manual', 'conditions': gpio.event_detected,
                'after': do_user_input_actions},
               {'trigger': 'loop', 'source': ['manual', 'auto'],
                'dest': 'auto', 'after': do_automatic_actions}]

machine = Machine(states=states, transitions=transitions, initial='manual')
</code>```

Note that I passed function references rather than strings. Strings are considered to be model functions while function references can originate from anywhere. Since our model would be more or less empty, we can use the Machine instance as model. This is only recommended when the behaviour is rather simple. A dedicated model makes handling complex configurations more maintainable. I passed the function callbacks to after, but in this scenario it does not matter whether it is executed before, during or after the state transition.

For the sake of completeness and since you explicitly mentioned you do not want to handle user input during transitions, I would suggest a Strategy Pattern approach where we create strategy objects which can be handled in the same way, but do different tasks.

Strategies are replaced whenever a state is changed. This time we need unless in the second transition to only go to 'auto' mode when no user input has been detected (unless is just the convenience counterpart of conditions). We also make use of Machine's keyword finalize_event which will always execute a function regardless of the success of a previous attempted transition. We could also just call Model.execute ourselves:

```<code>from transitions import Machine
from random import choice

class AutoStrategy(object):

    def execute(self):
        # do_automatic_actions()
        print('auto')

class UserInputStrategy(object):

    def execute(self):
        # do_user_input_actions()
        print('manual')

class Model(object):

    def __init__(self):
        self.strategy = UserInputStrategy()

    def execute(self):
        self.strategy.execute()

    def on_enter_manual(self):
        # We could use a singleton here if *Strategy is stateless
        self.strategy = UserInputStrategy()

    def on_enter_strategy(self):
        self.strategy = AutoStrategy()

    def event_detected(self):
        # return gpio.event_detected()
        # For simulation purposes, randomise the return value
        return choice([True, False])

states = ['manual', 'auto']
transitions = [{'trigger': 'loop', 'source': 'auto', 'dest': 'manual',
                'conditions': 'event_detected'},
               {'trigger': 'loop', 'source': 'manual', 'dest': 'auto',
                'unless': 'event_detected'}]

model = Model()
machine = Machine(model=model, states=states, transitions=transitions,
                  initial='manual', finalize_event='execute')

for i in range(10):
    model.loop()
</code>```

Body:
I've got an application running on a BeagleBone Black controlling some hardware. The user interface consists of an LCD display and a rotary encoder switch with an integrated push button.

In terms of state transitions, all what the application does is to react to push button events to switch between them:

Initial state: "manual"

Push event: toggle state to next ("auto"), do auto actions

Push event: toggle state to next ("manual"), do manual actions

In summary, there are two states, and the trigger is the button push, which actually toggles between the two.

The current code is an infinite loop with an if ... else condition that executes either the "manual" mode or "auto" mode actions depending on the state. A delay is added at the end of the loop. The manual variable is updated (toggled) by an interrupt whenever a push button event is detected.

while True:
    # Toggle mode when the push button event is detected
    # It can also be detected asynchronously outside the loop,
    # but we'll keep it on the loop for a smaller example
    if gpio.event_detected(push_button):
        manual_mode = not manual_mode

    if manual_mode:
        # MANUAL MODE:
        do_user_input_actions()
    else:
        # AUTO mode
        do_automatic_actions()

   time.sleep(0.5)

This construct is similar to the C equivalent that I've used a few times before. But I was wondering of a more object-oriented way of doing the same in Python.

Essentially, it seems that the logic would lend itself to using pytransitions, particularly if I need to add more states in the future, so I'm considering porting the code to it.

I can picture the two states and the transitions:

states = ['manual', 'sweep']
transitions = [['handle_manual_input', 'auto', 'manual'],
               ['run_auto_test', 'manual', 'auto']]

However, I can't quite visualize what the proper way to implement the equivalent of my current infinite loop with the state check is in the pytranslations model.

Effectively, handling manual input should be done on each loop iteration, and not just on the transition from auto, and vice versa for running the auto mode.

I understand that the state machine should be left alone to just take care of the states and transitions for better code separation.

It's the model implementation that I can't quite picture: I'd welcome any guidance on how and where to run do_user_input_actions() and do_automatic_actions().

Body:
If you are willing to (re-)enter states every cycle, this should do the trick:

from transitions import Machine
from random import choice

class Model(object):

    def on_enter_manual(self):
        # do_user_input_actions()
        print('manual')

    def on_enter_auto(self):
        # do_automatic_actions()
        print('auto')

    def event_detected(self):
        # return gpio.event_detected()
        # For simulation purposes randomise the return value
        return choice([True, False])

states = ['manual', 'auto']
transitions = [{'trigger': 'loop', 'source': ['manual', 'auto'],
                'dest': 'manual', 'conditions': 'event_detected'},
               {'trigger': 'loop', 'source': ['manual', 'auto'],
                'dest': 'auto'}]

model = Model()
machine = Machine(model=model, states=states,
                  transitions=transitions, initial='manual')

for i in range(10):
    model.loop()

transitions processes possible transitions in the order they were added. This means that the first transition is executed when event_detected returns True. If this is not the case, the second transition will be chosen as it has no condition.

For this solution, some tweaks are possible:

a) You could replace source:[..] with source:'*' to allow a loop transitions from all states. If you want to add states in the future this might be useful, but it can also backfire if you plan to use more than one trigger.

b) In case do_user_input_actions, gpio.event_detected, do_automatic_actions are static methods, you can more or less omit the model by using the following transitions:

transitions = [{'trigger': 'loop', 'source': ['manual', 'auto'],
                'dest': 'manual', 'conditions': gpio.event_detected,
                'after': do_user_input_actions},
               {'trigger': 'loop', 'source': ['manual', 'auto'],
                'dest': 'auto', 'after': do_automatic_actions}]

machine = Machine(states=states, transitions=transitions, initial='manual')

Note that I passed function references rather than strings. Strings are considered to be model functions while function references can originate from anywhere. Since our model would be more or less empty, we can use the Machine instance as model. This is only recommended when the behaviour is rather simple. A dedicated model makes handling complex configurations more maintainable. I passed the function callbacks to after, but in this scenario it does not matter whether it is executed before, during or after the state transition.

For the sake of completeness and since you explicitly mentioned you do not want to handle user input during transitions, I would suggest a Strategy Pattern approach where we create strategy objects which can be handled in the same way, but do different tasks.

Strategies are replaced whenever a state is changed. This time we need unless in the second transition to only go to 'auto' mode when no user input has been detected (unless is just the convenience counterpart of conditions). We also make use of Machine's keyword finalize_event which will always execute a function regardless of the success of a previous attempted transition. We could also just call Model.execute ourselves:

from transitions import Machine
from random import choice

class AutoStrategy(object):

    def execute(self):
        # do_automatic_actions()
        print('auto')

class UserInputStrategy(object):

    def execute(self):
        # do_user_input_actions()
        print('manual')

class Model(object):

    def __init__(self):
        self.strategy = UserInputStrategy()

    def execute(self):
        self.strategy.execute()

    def on_enter_manual(self):
        # We could use a singleton here if *Strategy is stateless
        self.strategy = UserInputStrategy()

    def on_enter_strategy(self):
        self.strategy = AutoStrategy()

    def event_detected(self):
        # return gpio.event_detected()
        # For simulation purposes, randomise the return value
        return choice([True, False])

states = ['manual', 'auto']
transitions = [{'trigger': 'loop', 'source': 'auto', 'dest': 'manual',
                'conditions': 'event_detected'},
               {'trigger': 'loop', 'source': 'manual', 'dest': 'auto',
                'unless': 'event_detected'}]

model = Model()
machine = Machine(model=model, states=states, transitions=transitions,
                  initial='manual', finalize_event='execute')

for i in range(10):
    model.loop()


问:
the sum of Big decimal values should be equal after division in java
I have 6 BigDecimals, let say

a,b,c,d,e,f and tot
The sum of all these values(a,b,c,d,e,f) are equal to tot
I am calculating average and storing in other variable of type BigDecimal, just say avgA, avgB, avgC, avgD, avgE, avgF and avgTot. now if I add all these

```<code>avgA, avgB, avgC, avgD, avgE, avgF
</code>```

this sum should be equal to avgTot

But sum of all the averages(avgA, avgB, avgC, avgD, avgE, avgF) is not equal to totAvg

here is sample code

```<code>BigDecimal avgA = a.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);
BigDecimal avgB = b.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);
BigDecimal avgTot = tot.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);

BigDecimal trimA = avgA.setScale(4, RoundingMode.CEILING);
BigDecimal trimB = avgB.setScale(4, RoundingMode.CEILING);
BigDecimal trimTot = avgTot.setScale(4, RoundingMode.CEILING);
</code>```

Sample Values:-

```<code>trimA 0.0004
trimB 0.0000
trimC 0.0022
trimD 0.0047
trimE 0.0000
trimF 0.0002
trimTot 0.0076
</code>```

The problem is sum(TrimA..F) is not equal to trimTot. I have to make sure that sum(TrimA..F) should be equal to trimTot

答:
It simply isn't the case for any rounding method that in general Round(A+B) = Round(A)+Round(B).

People bodge these problems at a high level of precision to minimize the incidence of visible rounding errors but that often doesn't work entirely.
Note: Joop Eggen has just posted such an answer. Please note I'm not using 'bodge' in a judgmental sense!

Without providing an explanation of why an impossible constraint is required it's difficult to give useful advice.

One obvious way is to define the average for A, B, C as A/3+B/3+C/3.
Another approach is to work through a calculation as rational numbers.
That means either keeping track of the numerator and denominator or using a specialised Rational class.

Body:
I have 6 BigDecimals, let say

a,b,c,d,e,f and tot
The sum of all these values(a,b,c,d,e,f) are equal to tot
I am calculating average and storing in other variable of type BigDecimal, just say avgA, avgB, avgC, avgD, avgE, avgF and avgTot. now if I add all these

avgA, avgB, avgC, avgD, avgE, avgF

this sum should be equal to avgTot

But sum of all the averages(avgA, avgB, avgC, avgD, avgE, avgF) is not equal to totAvg

here is sample code

BigDecimal avgA = a.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);
BigDecimal avgB = b.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);
BigDecimal avgTot = tot.divide(new BigDecimal(counter), 15,RoundingMode.CEILING);

BigDecimal trimA = avgA.setScale(4, RoundingMode.CEILING);
BigDecimal trimB = avgB.setScale(4, RoundingMode.CEILING);
BigDecimal trimTot = avgTot.setScale(4, RoundingMode.CEILING);

Sample Values:-

trimA 0.0004
trimB 0.0000
trimC 0.0022
trimD 0.0047
trimE 0.0000
trimF 0.0002
trimTot 0.0076

The problem is sum(TrimA..F) is not equal to trimTot. I have to make sure that sum(TrimA..F) should be equal to trimTot


问:
Open a html file using default web browser
I'm using this to get the path and executable of default web browser:

```<code>public static string DefaultWebBrowser
        {
            get
            {

                string path = @"\http\shell\open\command";

                using (RegistryKey reg = Registry.ClassesRoot.OpenSubKey(path))
                {
                    if (reg != null)
                    {
                        string webBrowserPath = reg.GetValue(String.Empty) as string;

                        if (!String.IsNullOrEmpty(webBrowserPath))
                        {
                            if (webBrowserPath.First() == '"')
                            {
                                return webBrowserPath.Split('"')[1];
                            }

                            return webBrowserPath.Split(' ')[0];
                        }
                    }

                    return null;
                }
            }
        }
</code>```

And:

```<code> protected static bool Run(string FileName, string Args)
        {
            try
            {
                Process proc = new Process();

                processInfo.FileName = FileName;
                 proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

                if(Args != null) proc.StartInfo.Arguments = Args;

                proc.Start();

                return true;
            }
            catch (Exception) { }

            return false;
        }
</code>```

Then I call the web browser: Run(DefaultWebBrowser, "foo.html")

The question is: the above function is calling Firefox and IE (the two web browsers installed on my pc) instead of Internet Explorer, the default web browser. I have no idea how to fix this.

EDIT

I have downloaded and installed the Google Chrome, set it as default web browser, but oddly the above error don't happens with it.

答:
Im using a code, where i look up for exe files first.
For example, if exsists chrome.exe (in its default path) else if exists firefox.exe or launcher.exe (for opera) etc... if doesnt any exists, try to run iexplore.exe with pathToHtmlFile parameter. This is my solution, where i use external config, where a set my browser, doesnt matter what is set default in OS.</p>

Body:
I'm using this to get the path and executable of default web browser:

public static string DefaultWebBrowser
        {
            get
            {

                string path = @"\http\shell\open\command";

                using (RegistryKey reg = Registry.ClassesRoot.OpenSubKey(path))
                {
                    if (reg != null)
                    {
                        string webBrowserPath = reg.GetValue(String.Empty) as string;

                        if (!String.IsNullOrEmpty(webBrowserPath))
                        {
                            if (webBrowserPath.First() == '"')
                            {
                                return webBrowserPath.Split('"')[1];
                            }

                            return webBrowserPath.Split(' ')[0];
                        }
                    }

                    return null;
                }
            }
        }

And:

 protected static bool Run(string FileName, string Args)
        {
            try
            {
                Process proc = new Process();

                processInfo.FileName = FileName;
                 proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

                if(Args != null) proc.StartInfo.Arguments = Args;

                proc.Start();

                return true;
            }
            catch (Exception) { }

            return false;
        }

Then I call the web browser: Run(DefaultWebBrowser, "foo.html")

The question is: the above function is calling Firefox and IE (the two web browsers installed on my pc) instead of Internet Explorer, the default web browser. I have no idea how to fix this.

EDIT

I have downloaded and installed the Google Chrome, set it as default web browser, but oddly the above error don't happens with it.


问:
How can I make an inline select in materializeCss
How can I make such a select??

tried to do display: inline but it did not work out

答:
Please do the following.

Change the HTML part
 to "
".

and use the css for inline

```<code>.input-field p, .input-field .select-wrapper {
  display: inline-block;
  clear: both;
  float: none;
}
</code>```

Body:
Please do the following.

Change the HTML part <div class="input-field col s1 inline"> to " <div class="input-field col s12 inline">".

and use the css for inline

.input-field p, .input-field .select-wrapper {
  display: inline-block;
  clear: both;
  float: none;
}