问:
Issue when trying to connect explorer with Hyperledger fabric network hosted on different machines
I am setting up explorer for fabric network which was running in some different machine(say IP 12.34.56.78),when i try to start the script start.sh from explorer i struck with this error.
Successfully connected on single instance(both explorer and fabric on a single machine) but facing error when trying to connect on different machines.

Here is the config.json file where i am changing parameters.

{
  "network-configs": {
    "network-1": {
      "version": "1.0",
      "clients": {
        "client-1": {
          "tlsEnable": true,
          "organization": "Org1MSP",
          "channel": "mychannel",
          "credentialStore": {
            "path": "./tmp/credentialStore_Org1/credential",
            "cryptoStore": {
              "path": "./tmp/credentialStore_Org1/crypto"
            }
          }
        }
      },
      "channels": {
        "mychannel": {
          "peers": {
            "peer0.org1.example.com": {}
          },
          "connection": {
            "timeout": {
              "peer": {
                "endorser": "6000",
                "eventHub": "6000",
                "eventReg": "6000"
              }
            }
          }
        }
      },
      "organizations": {
        "Org1MSP": {
          "mspid": "Org1MSP",
          "fullpath": false,
          "adminPrivateKey": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore"
          },
          "signedCert": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts"
          }
        },
        "Org2MSP": {
          "mspid": "Org2MSP",
          "adminPrivateKey": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/keystore"
          }
        },
        "OrdererMSP": {
          "mspid": "OrdererMSP",
          "adminPrivateKey": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore"
          }
        }
      },
      "peers": {
        "peer0.org1.example.com": {
          "tlsCACerts": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt"
          },
          "url": "grpcs://12.34.56.78:7051",
          "eventUrl": "grpcs://l12.34.56.78:7053",
          "grpcOptions": {
            "ssl-target-name-override": "peer0.org1.example.com"
          }
        },
        "peer1.org1.example.com": {
          "url": "grpcs://12.34.56.78:8051"
        },
        "peer0.org2.example.com": {
          "url": "grpcs://12.34.56.78:9051"
        },
        "peer1.org2.example.com": {
          "url": "grpcs://12.34.56.78:10051"
        }
      },
      "orderers": {
        "orderer.example.com": {
          "url": "grpcs://12.34.56.78:7050"
        }
      }
    },
    "network-2": {}
  },
  "configtxgenToolPath": "/home/dinesh/HyperExplorer/fabric-samples/bin",
  "license": "Apache-2.0"
}```

Error

(node:16024) DeprecationWarning: grpc.load: Use the @grpc/proto-loader
  module with grpc.loadPackageDefinition instead
  2019-05-28T13:26:18.102Z - error: [Remote.js]: Error: Failed to
  connect before the deadline URL:grpcs://localhost:7050
  <<<<<<<<<<<<<<<<<<<<<<<<<< Explorer Error >>>>>>>>>>>>>>>>>>>>> {
  Error: Failed to connect before the deadline
  URL:grpcs://localhost:7050
      at checkState (/home/dinesh/Music/blockchain-explorer-master/node_modules/grpc/src/client.js:720:16)
  connectFailed: true }

答:
Did you set the discovery options in your SDK?

Here the link to the discovery options in the official HL NodeJS Fabric SDK documentation.

https://fabric-sdk-node.github.io/release-1.4/module-fabric-network.Gateway.html#~DiscoveryOptions

Body:
I am setting up explorer for fabric network which was running in some different machine(say IP 12.34.56.78),when i try to start the script start.sh from explorer i struck with this error.
Successfully connected on single instance(both explorer and fabric on a single machine) but facing error when trying to connect on different machines.

Here is the config.json file where i am changing parameters.

{
  "network-configs": {
    "network-1": {
      "version": "1.0",
      "clients": {
        "client-1": {
          "tlsEnable": true,
          "organization": "Org1MSP",
          "channel": "mychannel",
          "credentialStore": {
            "path": "./tmp/credentialStore_Org1/credential",
            "cryptoStore": {
              "path": "./tmp/credentialStore_Org1/crypto"
            }
          }
        }
      },
      "channels": {
        "mychannel": {
          "peers": {
            "peer0.org1.example.com": {}
          },
          "connection": {
            "timeout": {
              "peer": {
                "endorser": "6000",
                "eventHub": "6000",
                "eventReg": "6000"
              }
            }
          }
        }
      },
      "organizations": {
        "Org1MSP": {
          "mspid": "Org1MSP",
          "fullpath": false,
          "adminPrivateKey": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore"
          },
          "signedCert": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts"
          }
        },
        "Org2MSP": {
          "mspid": "Org2MSP",
          "adminPrivateKey": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/keystore"
          }
        },
        "OrdererMSP": {
          "mspid": "OrdererMSP",
          "adminPrivateKey": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore"
          }
        }
      },
      "peers": {
        "peer0.org1.example.com": {
          "tlsCACerts": {
            "path": "/home/dinesh/HyperExplorer/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt"
          },
          "url": "grpcs://12.34.56.78:7051",
          "eventUrl": "grpcs://l12.34.56.78:7053",
          "grpcOptions": {
            "ssl-target-name-override": "peer0.org1.example.com"
          }
        },
        "peer1.org1.example.com": {
          "url": "grpcs://12.34.56.78:8051"
        },
        "peer0.org2.example.com": {
          "url": "grpcs://12.34.56.78:9051"
        },
        "peer1.org2.example.com": {
          "url": "grpcs://12.34.56.78:10051"
        }
      },
      "orderers": {
        "orderer.example.com": {
          "url": "grpcs://12.34.56.78:7050"
        }
      }
    },
    "network-2": {}
  },
  "configtxgenToolPath": "/home/dinesh/HyperExplorer/fabric-samples/bin",
  "license": "Apache-2.0"
}

Error

(node:16024) DeprecationWarning: grpc.load: Use the @grpc/proto-loader
  module with grpc.loadPackageDefinition instead
  2019-05-28T13:26:18.102Z - error: [Remote.js]: Error: Failed to
  connect before the deadline URL:grpcs://localhost:7050
  <<<<<<<<<<<<<<<<<<<<<<<<<< Explorer Error >>>>>>>>>>>>>>>>>>>>> {
  Error: Failed to connect before the deadline
  URL:grpcs://localhost:7050
      at checkState (/home/dinesh/Music/blockchain-explorer-master/node_modules/grpc/src/client.js:720:16)
  connectFailed: true }


来源: stackexchange

问:
Why does python manage.py runserver not work?
The command python manage.py runserver does not work when postgressql is the backend. There is no problem with the default sqllite

I tried with keeping my project both in the c and d drive but in both places I get the same error when I use postgressql as the backend. I have also ensure that the postgres server is on and not shut off.

In the django settings file this is the code

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'postgres',
        'PASSWORD': 'abc123',
        'HOST': '127.0.0.1',
        'PORT': '5432',
     }
 }
</code>```

the last 2-3 lines of the error in the command prompt are django.db.backends.postgressql isn't an available database backend. Try using mysql, oracle, sqllite3.

Error in detail

```<code>    Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\threading
.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\threading
.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\utils\autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\core\management\commands\runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\utils\autoreload.py", line 77, in raise_last_exception
    raise _exception[0](_exception[1]).with_traceback(_exception[2])
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\utils\autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\apps\registry.py", line 114, in populate
    app_config.import_models()
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\apps\config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\importlib
\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\contrib\auth\models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\contrib\auth\base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\models\base.py", line 117, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\models\base.py", line 321, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\models\options.py", line 204, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length(
))
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\utils.py", line 201, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\utils.py", line 125, in load_backend
    ) from e_user
django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql_psyc
opg' isn't an available database backend.
Try using 'django.db.backends.XXX', where XXX is one of:
    'mysql', 'oracle', 'sqlite3'
</code>```

答:
why you use this :

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'postgres',
        'PASSWORD': 'abc123',
        'HOST': '127.0.0.1',
        'PORT': '5432',
     }
 }
</code>```

you must set setting like this:

```<code>    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': '********',
        'HOST': 'localhost',
        'USER': '*******',
        'PASSWORD': '********'
    }
}
</code>```

in the name field, you must enter database name
in the user: PostgreSQL username
in the password: password username PostgreSQL

ContentLicense: CC BY-SA 4.0

Body:
The command python manage.py runserver does not work when postgressql is the backend. There is no problem with the default sqllite

I tried with keeping my project both in the c and d drive but in both places I get the same error when I use postgressql as the backend. I have also ensure that the postgres server is on and not shut off.

In the django settings file this is the code

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'postgres',
        'PASSWORD': 'abc123',
        'HOST': '127.0.0.1',
        'PORT': '5432',
     }
 }

the last 2-3 lines of the error in the command prompt are django.db.backends.postgressql isn't an available database backend. Try using mysql, oracle, sqllite3.

Error in detail

    Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\threading
.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\threading
.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\utils\autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\core\management\commands\runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\utils\autoreload.py", line 77, in raise_last_exception
    raise _exception[0](_exception[1]).with_traceback(_exception[2])
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\utils\autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\apps\registry.py", line 114, in populate
    app_config.import_models()
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\apps\config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\importlib
\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\contrib\auth\models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\contrib\auth\base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\models\base.py", line 117, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\models\base.py", line 321, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\models\options.py", line 204, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length(
))
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\utils.py", line 201, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Users\admin67\AppData\Local\Programs\Python\Python37-32\lib\site-pack
ages\django\db\utils.py", line 125, in load_backend
    ) from e_user
django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql_psyc
opg' isn't an available database backend.
Try using 'django.db.backends.XXX', where XXX is one of:
    'mysql', 'oracle', 'sqlite3'

Body:
why you use this :

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'postgres',
        'PASSWORD': 'abc123',
        'HOST': '127.0.0.1',
        'PORT': '5432',
     }
 }

you must set setting like this:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': '********',
        'HOST': 'localhost',
        'USER': '*******',
        'PASSWORD': '********'
    }
}

in the name field, you must enter database name
in the user: PostgreSQL username
in the password: password username PostgreSQL


问:
Mockito cannot mock this class: interface
I'm having an issue with mockito and powermock, I can mock an abstract class with a final static method with no problems. When trying to mock an Interface as with WebIServerSession I'm getting the stacktrace below. I've had a look at other issues in powermock github repo and it seems to be related with the jvm version. I've already upgraded to the latest 1.8 java version as stated in https://github.com/mockito/mockito/issues/636 and I'm still getting the same error. Might it be related with Powermock compatibility with Mockito 2?

```<code>import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

@BeforeMethod
public void setup() throws Exception {
    mockStatic(ResourceBundle.class);
    mockStatic(WebObjectsFactory.class);
    WebObjectsFactory webObjectsFactory = mock(WebObjectsFactory.class);
    WebIServerSession webIServerSession = mock(WebIServerSession.class);

    PowerMockito.when(WebObjectsFactory.getInstance()).thenReturn(webObjectsFactory);
    PowerMockito.when(webObjectsFactory.getIServerSession()).thenReturn(webIServerSession);
    whenNew(ThreadLocal.class).withNoArguments().thenReturn(errorContainer);

    MockitoAnnotations.initMocks(this);
}

@Test
public void shouldBeTrue() {
    assertTrue(true);
}
</code>```

Maven dependencies:

```<code><dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.8.9</version>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-core</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-testng</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-reflect</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

Stacktrace:

```<code>org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface com.microstrategy.web.objects.WebIServerSession.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.

Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.191-b12
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0_191-b12
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.14.1

Underlying exception : java.lang.IllegalArgumentException: Could not create type

    at com.myproject.SSOESMTest.setup(SSOESMTest.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:523)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.IllegalArgumentException: Could not create type
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:50)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:116)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
    ... 28 more
Caused by: java.lang.NoClassDefFoundError: com/microstrategy/utils/xml/SAXSupport
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.getDeclaredMethods(Class.java:1975)
    at net.bytebuddy.description.method.MethodList$ForLoadedMethods.<init>(MethodList.java:109)
    at net.bytebuddy.description.type.TypeDescription$ForLoadedType.getDeclaredMethods(TypeDescription.java:8426)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.getDeclaredMethods(TypeDescription.java:3654)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:634)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:567)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:465)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:463)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:198)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:189)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3394)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3583)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
    ... 39 more
Caused by: java.lang.ClassNotFoundException: com.microstrategy.utils.xml.SAXSupport
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 63 more

Test ignored.

===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 2
===============================================

Process finished with exit code 0
</code>```

答:
add </p>

```<code>@RunWith(MockitoJUnitRunner.class)
</code>```

Body:
I'm having an issue with mockito and powermock, I can mock an abstract class with a final static method with no problems. When trying to mock an Interface as with WebIServerSession I'm getting the stacktrace below. I've had a look at other issues in powermock github repo and it seems to be related with the jvm version. I've already upgraded to the latest 1.8 java version as stated in https://github.com/mockito/mockito/issues/636 and I'm still getting the same error. Might it be related with Powermock compatibility with Mockito 2?

import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

@BeforeMethod
public void setup() throws Exception {
    mockStatic(ResourceBundle.class);
    mockStatic(WebObjectsFactory.class);
    WebObjectsFactory webObjectsFactory = mock(WebObjectsFactory.class);
    WebIServerSession webIServerSession = mock(WebIServerSession.class);

    PowerMockito.when(WebObjectsFactory.getInstance()).thenReturn(webObjectsFactory);
    PowerMockito.when(webObjectsFactory.getIServerSession()).thenReturn(webIServerSession);
    whenNew(ThreadLocal.class).withNoArguments().thenReturn(errorContainer);

    MockitoAnnotations.initMocks(this);
}

@Test
public void shouldBeTrue() {
    assertTrue(true);
}

Maven dependencies:

<dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.8.9</version>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-core</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-testng</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-reflect</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Stacktrace:

org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface com.microstrategy.web.objects.WebIServerSession.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.

Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.191-b12
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0_191-b12
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.14.1

Underlying exception : java.lang.IllegalArgumentException: Could not create type

    at com.myproject.SSOESMTest.setup(SSOESMTest.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:523)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.IllegalArgumentException: Could not create type
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:50)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:116)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
    ... 28 more
Caused by: java.lang.NoClassDefFoundError: com/microstrategy/utils/xml/SAXSupport
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.getDeclaredMethods(Class.java:1975)
    at net.bytebuddy.description.method.MethodList$ForLoadedMethods.<init>(MethodList.java:109)
    at net.bytebuddy.description.type.TypeDescription$ForLoadedType.getDeclaredMethods(TypeDescription.java:8426)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.getDeclaredMethods(TypeDescription.java:3654)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:634)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:567)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:465)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:463)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:198)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:189)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3394)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3583)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
    ... 39 more
Caused by: java.lang.ClassNotFoundException: com.microstrategy.utils.xml.SAXSupport
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 63 more

Test ignored.

===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 2
===============================================

Process finished with exit code 0

Body:
add

@RunWith(MockitoJUnitRunner.class)


问:
Dynamic-height UICollectionView inside a dynamic-height UITableViewCell
I have a horizontal UICollectionView pinned to all edges of a UITableViewCell. Items in the collection view are dynamically sized, and I want to make the table view's height equal to that of the tallest collection view cell.

The views are structured as follows:

UITableView

UITableViewCell

UICollectionView

UICollectionViewCell

UICollectionViewCell

UICollectionViewCell

```<code>class TableViewCell: UITableViewCell {

    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: self.frame, collectionViewLayout: layout)
        return collectionView
    }()

    var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.estimatedItemSize = CGSize(width: 350, height: 20)
        layout.scrollDirection = .horizontal
        return layout
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let nib = UINib(nibName: String(describing: CollectionViewCell.self), bundle: nil)
        collectionView.register(nib, forCellWithReuseIdentifier: CollectionViewCellModel.identifier)

        addSubview(collectionView)

        // (using SnapKit)
        collectionView.snp.makeConstraints { (make) in
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

        collectionView.layoutIfNeeded()
        collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width , height: 1)

        return layout.collectionViewContentSize
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let spacing: CGFloat = 50
        layout.sectionInset = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: spacing)
        layout.minimumLineSpacing = spacing
    }
}

class OptionsCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        contentView.translatesAutoresizingMaskIntoConstraints = false

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

        return contentView.systemLayoutSizeFitting(CGSize(width: targetSize.width, height: 1))
    }
}

class CollectionViewFlowLayout: UICollectionViewFlowLayout {

    private var contentHeight: CGFloat = 500
    private var contentWidth: CGFloat = 200

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        if let attrs = super.layoutAttributesForElements(in: rect) {
           // perform some logic
           contentHeight = /* something */
           contentWidth = /* something */
           return attrs
        }
        return nil
    }

    override var collectionViewContentSize: CGSize {
        return CGSize(width: contentWidth, height: contentHeight)
    }
}
</code>```

In my UIViewController, I have tableView.estimatedRowHeight = 500 and tableView.rowHeight = UITableView.automaticDimension.

I'm trying to make the table view cell's size in systemLayoutSizeFitting equal to the collectionViewContentSize, but it's called before the layout has had a chance to set collectionViewContentSize to the correct value. Here's the order in which these methods are called:

```<code>cellForRowAt
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
**OptionsTableViewCell systemLayoutSizeFitting (200.0, 500.0) << incorrect/original value**
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
willDisplay cell
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
TableViewCell layoutSubviews() collectionViewContentSize.height:  500.0 << incorrect/original value
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewCell systemLayoutSizeFitting
CollectionViewCell systemLayoutSizeFitting
CollectionViewCell systemLayoutSizeFitting
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
TableViewCell layoutSubviews() collectionViewContentSize.height:  301.0 << correct height
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
TableViewCell layoutSubviews() collectionViewContentSize.height:  301.0 << correct height
</code>```

How can I make my table view cell's height equal to my collection view's tallest item, represented by the layout's collectionViewContentSize?

答:
I managed to achieve exactly what you want to do with a height constraint reference for the CollectionView (however I don't use SnapKit, neither programaticUI).

Here is how I did, it may help:

First I register a NSLayoutConstraint for the UICollectionView, which already has a topAnchor and a bottomAnchor equal to its superview

```<code>class ChatButtonsTableViewCell: UITableViewCell {

    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var buttonsCollectionView: UICollectionView!
    @IBOutlet weak var buttonsCollectionViewHeightConstraint: NSLayoutConstraint! // reference

}
</code>```

Then in my UITableViewDelegate implementation, on cellForRowAt, I set the height constraint's constant equal to the actuall collectionView frame like so :

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 // let item = items[indexPath.section]
     let item = groupedItems[indexPath.section][indexPath.row]
     let cell = tableView.dequeueReusableCell(withIdentifier: ChatButtonsTableViewCell.identifier, for: indexPath) as! ChatButtonsTableViewCell

     cell.chatMessage = nil // reusability
     cell.buttonsCollectionView.isUserInteractionEnabled = true
     cell.buttonsCollectionView.reloadData() // load actual content of embedded CollectionView
     cell.chatMessage = groupedItems[indexPath.section][indexPath.row] as? ChatMessageViewModelChoicesItem

     // >>> Compute actual height
     cell.layoutIfNeeded()
     let height: CGFloat = cell.buttonsCollectionView.collectionViewLayout.collectionViewContentSize.height
     cell.buttonsCollectionViewHeightConstraint.constant = height
     // <<<

     return cell

 }
</code>```

My assumption is that you could use this methodology to set you collectionView's height to the height of the biggest cell, replacing let height: CGFloat = cell.buttonsCollectionView.collectionViewLayout.collectionViewContentSize.height with the actual height you want.

Plus, if you are using an horizontal UICollectionView, my guess is that you don't even have to change this line, considering that the contentSize.height will be equal to your biggest cell height.

It works flawlessly for me, hope it helps

EDIT

Just thinking, you may need to place some layoutIfNeeded() and invalidateLayout() here and there. If it doesn't work straight away I can tell you where I put these.

EDIT 2

Also forgot to mention that I implemented willDisplay and estimatedHeightForRowAt.

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if let buttonCell = cell as? ChatButtonsTableViewCell {
        cellHeights[indexPath] = buttonCell.buttonsCollectionView.collectionViewLayout.collectionViewContentSize.height
    } else {
        cellHeights[indexPath] = cell.frame.size.height
    }
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return cellHeights[indexPath] ?? 70.0
}
</code>```

Body:
I have a horizontal UICollectionView pinned to all edges of a UITableViewCell. Items in the collection view are dynamically sized, and I want to make the table view's height equal to that of the tallest collection view cell.

The views are structured as follows:

UITableView

UITableViewCell

UICollectionView

UICollectionViewCell

UICollectionViewCell

UICollectionViewCell

class TableViewCell: UITableViewCell {

    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: self.frame, collectionViewLayout: layout)
        return collectionView
    }()

    var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.estimatedItemSize = CGSize(width: 350, height: 20)
        layout.scrollDirection = .horizontal
        return layout
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let nib = UINib(nibName: String(describing: CollectionViewCell.self), bundle: nil)
        collectionView.register(nib, forCellWithReuseIdentifier: CollectionViewCellModel.identifier)

        addSubview(collectionView)

        // (using SnapKit)
        collectionView.snp.makeConstraints { (make) in
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

        collectionView.layoutIfNeeded()
        collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width , height: 1)

        return layout.collectionViewContentSize
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let spacing: CGFloat = 50
        layout.sectionInset = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: spacing)
        layout.minimumLineSpacing = spacing
    }
}

class OptionsCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        contentView.translatesAutoresizingMaskIntoConstraints = false

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

        return contentView.systemLayoutSizeFitting(CGSize(width: targetSize.width, height: 1))
    }
}

class CollectionViewFlowLayout: UICollectionViewFlowLayout {

    private var contentHeight: CGFloat = 500
    private var contentWidth: CGFloat = 200

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        if let attrs = super.layoutAttributesForElements(in: rect) {
           // perform some logic
           contentHeight = /* something */
           contentWidth = /* something */
           return attrs
        }
        return nil
    }

    override var collectionViewContentSize: CGSize {
        return CGSize(width: contentWidth, height: contentHeight)
    }
}

In my UIViewController, I have tableView.estimatedRowHeight = 500 and tableView.rowHeight = UITableView.automaticDimension.

I'm trying to make the table view cell's size in systemLayoutSizeFitting equal to the collectionViewContentSize, but it's called before the layout has had a chance to set collectionViewContentSize to the correct value. Here's the order in which these methods are called:

cellForRowAt
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
**OptionsTableViewCell systemLayoutSizeFitting (200.0, 500.0) << incorrect/original value**
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
willDisplay cell
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
TableViewCell layoutSubviews() collectionViewContentSize.height:  500.0 << incorrect/original value
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewCell systemLayoutSizeFitting
CollectionViewCell systemLayoutSizeFitting
CollectionViewCell systemLayoutSizeFitting
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
TableViewCell layoutSubviews() collectionViewContentSize.height:  301.0 << correct height
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
TableViewCell layoutSubviews() collectionViewContentSize.height:  301.0 << correct height

How can I make my table view cell's height equal to my collection view's tallest item, represented by the layout's collectionViewContentSize?

Body:
I managed to achieve exactly what you want to do with a height constraint reference for the CollectionView (however I don't use SnapKit, neither programaticUI).

Here is how I did, it may help:

First I register a NSLayoutConstraint for the UICollectionView, which already has a topAnchor and a bottomAnchor equal to its superview

class ChatButtonsTableViewCell: UITableViewCell {

    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var buttonsCollectionView: UICollectionView!
    @IBOutlet weak var buttonsCollectionViewHeightConstraint: NSLayoutConstraint! // reference

}

Then in my UITableViewDelegate implementation, on cellForRowAt, I set the height constraint's constant equal to the actuall collectionView frame like so :

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 // let item = items[indexPath.section]
     let item = groupedItems[indexPath.section][indexPath.row]
     let cell = tableView.dequeueReusableCell(withIdentifier: ChatButtonsTableViewCell.identifier, for: indexPath) as! ChatButtonsTableViewCell

     cell.chatMessage = nil // reusability
     cell.buttonsCollectionView.isUserInteractionEnabled = true
     cell.buttonsCollectionView.reloadData() // load actual content of embedded CollectionView
     cell.chatMessage = groupedItems[indexPath.section][indexPath.row] as? ChatMessageViewModelChoicesItem

     // >>> Compute actual height
     cell.layoutIfNeeded()
     let height: CGFloat = cell.buttonsCollectionView.collectionViewLayout.collectionViewContentSize.height
     cell.buttonsCollectionViewHeightConstraint.constant = height
     // <<<

     return cell

 }

My assumption is that you could use this methodology to set you collectionView's height to the height of the biggest cell, replacing let height: CGFloat = cell.buttonsCollectionView.collectionViewLayout.collectionViewContentSize.height with the actual height you want.

Plus, if you are using an horizontal UICollectionView, my guess is that you don't even have to change this line, considering that the contentSize.height will be equal to your biggest cell height.

It works flawlessly for me, hope it helps

EDIT

Just thinking, you may need to place some layoutIfNeeded() and invalidateLayout() here and there. If it doesn't work straight away I can tell you where I put these.

EDIT 2

Also forgot to mention that I implemented willDisplay and estimatedHeightForRowAt.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if let buttonCell = cell as? ChatButtonsTableViewCell {
        cellHeights[indexPath] = buttonCell.buttonsCollectionView.collectionViewLayout.collectionViewContentSize.height
    } else {
        cellHeights[indexPath] = cell.frame.size.height
    }
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return cellHeights[indexPath] ?? 70.0
}


问:
What causes a SIGILL with an ILL_ILLTRP code on iOS?
I've received a crash report for my iOS application where the exception type is SIGILL with an exception code of ILL_ILLTRP, which I've never seen before.

The only information I can find about ILL_ILLTRP is in signal.h, where it says:

/*
 * When the signal is SIGILL or SIGFPE, si_addr contains the address of
 * the faulting instruction.
 * When the signal is SIGSEGV or SIGBUS, si_addr contains the address of
 * the faulting memory reference. Although for x86 there are cases of SIGSEGV
 * for which si_addr cannot be determined and is NULL.
 * If the signal is SIGCHLD, the si_pid field will contain the child process ID,
 *  si_status contains the exit value or signal and
 *  si_uid contains the real user ID of the process that sent the signal.
 */

/* Values for si_code */

/* Codes for SIGILL */
#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE)
#define ILL_NOOP        0       /* if only I knew... */
#endif
#define ILL_ILLOPC      1       /* [XSI] illegal opcode */
#define ILL_ILLTRP      2       /* [XSI] illegal trap */
#define ILL_PRVOPC      3       /* [XSI] privileged opcode */
#define ILL_ILLOPN      4       /* [XSI] illegal operand -NOTIMP */
#define ILL_ILLADR      5       /* [XSI] illegal addressing mode -NOTIMP */
#define ILL_PRVREG      6       /* [XSI] privileged register -NOTIMP */
#define ILL_COPROC      7       /* [XSI] coprocessor error -NOTIMP */
#define ILL_BADSTK      8       /* [XSI] internal stack error -NOTIMP */
```

<p>On iOS (and Swift or Obj-C), what could cause an "illegal trap" to occur?</p>

<p>For reference, here is the stack trace for the crashing thread:</p>

```Incident Identifier: A450C98F-DDB4-4593-9C93-B4C17D3EB4E4
CrashReporter Key:   DB1695E0-C812-4087-9567-D4BD5D4D491C
Hardware Model:      iPhone8,1
Code Type:       ARM-64
Parent Process:  ??? [1]

Date/Time:       2019-05-26T17:01:50Z
Launch Time:     2019-05-26T17:01:37Z
OS Version:      iPhone OS 12.1.2 (16C101)
Report Version:  104

Exception Type:  SIGILL
Exception Codes: ILL_ILLTRP at 0x100c3343c
Crashed Thread:  0

Thread 0 Crashed:
0   CocoaLumberjack                      0x0000000100c3343c CocoaLumberjack.asyncLoggingEnabled.unsafeMutableAddressor : Swift.Bool (CocoaLumberjack.swift:73)
1   XXXApp                               0x0000000100762d08 XXXApp.XXXAppNavigationContext.append(XXXApp.XXXAppNavigationPathComponent) -> () (XXXAppNavigationContext.swift:0)
2   XXXApp                               0x0000000100763a4c merged @objc XXXApp.XXXAppNavigationContext.append(XXXApp.XXXAppNavigationPathComponent) -> () + 44
3   XXXApp                               0x000000010071ae80 -[XXXAppTableViewController viewWillAppear:] (XXXAppTableViewController.m:35)
4   XXXApp                               0x0000000100708360 -[XXXAppGroupTableViewController viewWillAppear:] (XXXAppGroupTableViewController.m:83)
5   UIKitCore                            0x00000001b3224f28 -[UIViewController _setViewAppearState:isAnimating:] + 580
6   UIKitCore                            0x00000001b322560c -[UIViewController __viewWillAppear:] + 136
7   XXXApp                               0x00000001006d3ff8 -[XXXAppTabBarViewController sendAppearanceTransitionsToViewControllers:] (XXXAppTabBarViewController.m:441)
8   XXXApp                               0x00000001006d3d88 -[XXXAppTabBarViewController scrollViewDidScroll:] (XXXAppTabBarViewController.m:426)
9   XXXApp                               0x00000001006d1458 -[XXXAppTabBarViewController viewDidLayoutSubviews] (XXXAppTabBarViewController.m:159)
10  UIKitCore                            0x00000001b3c8f944 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1736
11  QuartzCore                           0x000000018ac4db74 -[CALayer layoutSublayers] + 180
12  QuartzCore                           0x000000018ac52b2c CA::Layer::layout_if_needed(CA::Transaction*) + 320
13  UIKitCore                            0x00000001b3c7acc8 -[UIView(Hierarchy) layoutBelowIfNeeded] + 544
14  UIKitCore                            0x00000001b318bd0c -[UINavigationController _layoutViewController:] + 1292
15  UIKitCore                            0x00000001b3186400 -[UINavigationController _layoutTopViewController] + 232
16  UIKitCore                            0x00000001b31845d0 -[UINavigationController navigationTransitionView:didEndTransition:fromView:toView:] + 776
17  UIKitCore                            0x00000001b3c4a7d4 -[UINavigationTransitionView _notifyDelegateTransitionDidStopWithContext:] + 416
18  UIKitCore                            0x00000001b3c4aa90 -[UINavigationTransitionView _cleanupTransition] + 584
19  UIKitCore                            0x00000001b3c58950 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 308
20  UIKitCore                            0x00000001b3c5438c +[UIViewAnimationState popAnimationState] + 332
21  UIKitCore                            0x00000001b3c4a518 -[UINavigationTransitionView transition:fromView:toView:] + 1860
22  UIKitCore                            0x00000001b318cb1c -[UINavigationController _startTransition:fromViewController:toViewController:] + 2652
23  UIKitCore                            0x00000001b318d0f8 -[UINavigationController _startDeferredTransitionIfNeeded:] + 1180
24  UIKitCore                            0x00000001b318e3f8 -[UINavigationController __viewWillLayoutSubviews] + 160
25  UIKitCore                            0x00000001b31705e8 -[UILayoutContainerView layoutSubviews] + 220
26  UIKitCore                            0x00000001b3c8f7dc -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1376
27  QuartzCore                           0x000000018ac4db74 -[CALayer layoutSublayers] + 180
28  QuartzCore                           0x000000018ac52b2c CA::Layer::layout_if_needed(CA::Transaction*) + 320
29  QuartzCore                           0x000000018abb144c CA::Context::commit_transaction(CA::Transaction*) + 336
30  QuartzCore                           0x000000018abdfd7c CA::Transaction::commit() + 604
31  UIKitCore                            0x00000001b380fa3c _afterCACommitHandler + 252
32  CoreFoundation                       0x00000001865e07cc __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 28
33  CoreFoundation                       0x00000001865db460 __CFRunLoopDoObservers + 408
34  CoreFoundation                       0x00000001865dba00 __CFRunLoopRun + 1260
35  CoreFoundation                       0x00000001865db1f0 CFRunLoopRunSpecific + 432
36  GraphicsServices                     0x0000000188854584 GSEventRunModal + 96
37  UIKitCore                            0x00000001b37e6d40 UIApplicationMain + 208
38  XXXApp                               0x00000001006c96e4 main (main.m:16)
39  libdyld.dylib                        0x000000018609abb4 start + 0
```

答:
I tried to understand what happened. I don’t have a solution, but a few ideas:

The stack trace (line 0) says the crash is in the CocoaLumberjack swift code at line 73, where a Bool var asyncLoggingEnabled should be accessed using an unsafeMutableAddressor.

Apparently, this is the instruction

```<code>public var asyncLoggingEnabled = true
</code>```

in this code at line 73.

I believe this var is accessed using an UnsafeMutablePointer (docs).  Here, the app is

... responsible for handling the life cycle of any memory you work with
  through unsafe pointers to avoid leaks or undefined behavior.

Particularly,

Many pointer operations must only be applied to pointers with memory
  in a specific state—you must keep track of the state of the memory you
  are working with and understand the changes to that state that
  different operations perform. Memory can be untyped and uninitialized,
  bound to a type and uninitialized, or bound to a type and initialized
  to a value. Finally, memory that was allocated previously may have
  been deallocated, leaving existing pointers referencing unallocated
  memory.

I believe that your app crashed because the pointer used to access asyncLoggingEnabled points to memory in an illegal state.

If this happens, a system trap should be executed to handle the situation, but it can only be executed if a trap handler for this type of exception has been installed. If this is not the case, an illegal trap (Exception Code: ILL_ILLTRP) is done that handles all not handled traps.

Probably, the memory could by chance also be in a legal state, depending on the execution history. Thus, the crash may happen or not.

To cut it short, I think this is a bug in CocoaLumberjack.

Body:
I've received a crash report for my iOS application where the exception type is SIGILL with an exception code of ILL_ILLTRP, which I've never seen before.

The only information I can find about ILL_ILLTRP is in signal.h, where it says:

/*
 * When the signal is SIGILL or SIGFPE, si_addr contains the address of
 * the faulting instruction.
 * When the signal is SIGSEGV or SIGBUS, si_addr contains the address of
 * the faulting memory reference. Although for x86 there are cases of SIGSEGV
 * for which si_addr cannot be determined and is NULL.
 * If the signal is SIGCHLD, the si_pid field will contain the child process ID,
 *  si_status contains the exit value or signal and
 *  si_uid contains the real user ID of the process that sent the signal.
 */

/* Values for si_code */

/* Codes for SIGILL */
#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE)
#define ILL_NOOP        0       /* if only I knew... */
#endif
#define ILL_ILLOPC      1       /* [XSI] illegal opcode */
#define ILL_ILLTRP      2       /* [XSI] illegal trap */
#define ILL_PRVOPC      3       /* [XSI] privileged opcode */
#define ILL_ILLOPN      4       /* [XSI] illegal operand -NOTIMP */
#define ILL_ILLADR      5       /* [XSI] illegal addressing mode -NOTIMP */
#define ILL_PRVREG      6       /* [XSI] privileged register -NOTIMP */
#define ILL_COPROC      7       /* [XSI] coprocessor error -NOTIMP */
#define ILL_BADSTK      8       /* [XSI] internal stack error -NOTIMP */

On iOS (and Swift or Obj-C), what could cause an "illegal trap" to occur?

For reference, here is the stack trace for the crashing thread:

Incident Identifier: A450C98F-DDB4-4593-9C93-B4C17D3EB4E4
CrashReporter Key:   DB1695E0-C812-4087-9567-D4BD5D4D491C
Hardware Model:      iPhone8,1
Code Type:       ARM-64
Parent Process:  ??? [1]

Date/Time:       2019-05-26T17:01:50Z
Launch Time:     2019-05-26T17:01:37Z
OS Version:      iPhone OS 12.1.2 (16C101)
Report Version:  104

Exception Type:  SIGILL
Exception Codes: ILL_ILLTRP at 0x100c3343c
Crashed Thread:  0

Thread 0 Crashed:
0   CocoaLumberjack                      0x0000000100c3343c CocoaLumberjack.asyncLoggingEnabled.unsafeMutableAddressor : Swift.Bool (CocoaLumberjack.swift:73)
1   XXXApp                               0x0000000100762d08 XXXApp.XXXAppNavigationContext.append(XXXApp.XXXAppNavigationPathComponent) -> () (XXXAppNavigationContext.swift:0)
2   XXXApp                               0x0000000100763a4c merged @objc XXXApp.XXXAppNavigationContext.append(XXXApp.XXXAppNavigationPathComponent) -> () + 44
3   XXXApp                               0x000000010071ae80 -[XXXAppTableViewController viewWillAppear:] (XXXAppTableViewController.m:35)
4   XXXApp                               0x0000000100708360 -[XXXAppGroupTableViewController viewWillAppear:] (XXXAppGroupTableViewController.m:83)
5   UIKitCore                            0x00000001b3224f28 -[UIViewController _setViewAppearState:isAnimating:] + 580
6   UIKitCore                            0x00000001b322560c -[UIViewController __viewWillAppear:] + 136
7   XXXApp                               0x00000001006d3ff8 -[XXXAppTabBarViewController sendAppearanceTransitionsToViewControllers:] (XXXAppTabBarViewController.m:441)
8   XXXApp                               0x00000001006d3d88 -[XXXAppTabBarViewController scrollViewDidScroll:] (XXXAppTabBarViewController.m:426)
9   XXXApp                               0x00000001006d1458 -[XXXAppTabBarViewController viewDidLayoutSubviews] (XXXAppTabBarViewController.m:159)
10  UIKitCore                            0x00000001b3c8f944 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1736
11  QuartzCore                           0x000000018ac4db74 -[CALayer layoutSublayers] + 180
12  QuartzCore                           0x000000018ac52b2c CA::Layer::layout_if_needed(CA::Transaction*) + 320
13  UIKitCore                            0x00000001b3c7acc8 -[UIView(Hierarchy) layoutBelowIfNeeded] + 544
14  UIKitCore                            0x00000001b318bd0c -[UINavigationController _layoutViewController:] + 1292
15  UIKitCore                            0x00000001b3186400 -[UINavigationController _layoutTopViewController] + 232
16  UIKitCore                            0x00000001b31845d0 -[UINavigationController navigationTransitionView:didEndTransition:fromView:toView:] + 776
17  UIKitCore                            0x00000001b3c4a7d4 -[UINavigationTransitionView _notifyDelegateTransitionDidStopWithContext:] + 416
18  UIKitCore                            0x00000001b3c4aa90 -[UINavigationTransitionView _cleanupTransition] + 584
19  UIKitCore                            0x00000001b3c58950 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 308
20  UIKitCore                            0x00000001b3c5438c +[UIViewAnimationState popAnimationState] + 332
21  UIKitCore                            0x00000001b3c4a518 -[UINavigationTransitionView transition:fromView:toView:] + 1860
22  UIKitCore                            0x00000001b318cb1c -[UINavigationController _startTransition:fromViewController:toViewController:] + 2652
23  UIKitCore                            0x00000001b318d0f8 -[UINavigationController _startDeferredTransitionIfNeeded:] + 1180
24  UIKitCore                            0x00000001b318e3f8 -[UINavigationController __viewWillLayoutSubviews] + 160
25  UIKitCore                            0x00000001b31705e8 -[UILayoutContainerView layoutSubviews] + 220
26  UIKitCore                            0x00000001b3c8f7dc -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1376
27  QuartzCore                           0x000000018ac4db74 -[CALayer layoutSublayers] + 180
28  QuartzCore                           0x000000018ac52b2c CA::Layer::layout_if_needed(CA::Transaction*) + 320
29  QuartzCore                           0x000000018abb144c CA::Context::commit_transaction(CA::Transaction*) + 336
30  QuartzCore                           0x000000018abdfd7c CA::Transaction::commit() + 604
31  UIKitCore                            0x00000001b380fa3c _afterCACommitHandler + 252
32  CoreFoundation                       0x00000001865e07cc __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 28
33  CoreFoundation                       0x00000001865db460 __CFRunLoopDoObservers + 408
34  CoreFoundation                       0x00000001865dba00 __CFRunLoopRun + 1260
35  CoreFoundation                       0x00000001865db1f0 CFRunLoopRunSpecific + 432
36  GraphicsServices                     0x0000000188854584 GSEventRunModal + 96
37  UIKitCore                            0x00000001b37e6d40 UIApplicationMain + 208
38  XXXApp                               0x00000001006c96e4 main (main.m:16)
39  libdyld.dylib                        0x000000018609abb4 start + 0

Body:
I tried to understand what happened. I don’t have a solution, but a few ideas:

The stack trace (line 0) says the crash is in the CocoaLumberjack swift code at line 73, where a Bool var asyncLoggingEnabled should be accessed using an unsafeMutableAddressor.

Apparently, this is the instruction

public var asyncLoggingEnabled = true

in this code at line 73.

I believe this var is accessed using an UnsafeMutablePointer (docs).  Here, the app is

... responsible for handling the life cycle of any memory you work with
  through unsafe pointers to avoid leaks or undefined behavior.

Particularly,

Many pointer operations must only be applied to pointers with memory
  in a specific state—you must keep track of the state of the memory you
  are working with and understand the changes to that state that
  different operations perform. Memory can be untyped and uninitialized,
  bound to a type and uninitialized, or bound to a type and initialized
  to a value. Finally, memory that was allocated previously may have
  been deallocated, leaving existing pointers referencing unallocated
  memory.

I believe that your app crashed because the pointer used to access asyncLoggingEnabled points to memory in an illegal state.

If this happens, a system trap should be executed to handle the situation, but it can only be executed if a trap handler for this type of exception has been installed. If this is not the case, an illegal trap (Exception Code: ILL_ILLTRP) is done that handles all not handled traps.

Probably, the memory could by chance also be in a legal state, depending on the execution history. Thus, the crash may happen or not.

To cut it short, I think this is a bug in CocoaLumberjack.


问:
Why i am not able to cast pointer to the class structure
I have a Geometry class

```<code>class Geometry
{
public:
    std::string stdstrType;
    bool bValid;
public:
    Geometry()

    Geometry( std::string strType , bool bValue )

    Geometry(const Geometry &g)

    ~Geometry()
    virtual void draw();
    bool isValid();
    void setValidState(bool bState);
    virtual void Init();
    std::string GetName();
};
</code>```

Which is the base class for Geometry objects like in this case for Sphere class

```<code>class Sph : public Geometry
{
public:
    Sph( float radius , float segments );
    ~Sph();
    void init();
    void CleanUp();
    void draw();

private:
    float fRadius, fSegments;
    bool isInited;
    unsigned int m_VAO, m_VBO;
    int iNumsToDraw;
    SumShader shader;
    bool isChanged;
};
</code>```

I have a Tree structure holding different Container objects and Geometry is a data type in the Container object.

```<code>class Container
{
private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry Geom;
}
</code>```

Since each item in the tree can hold a circle sphere or rectangle so I would like to use the draw function of geometry to draw the Geometry object types.
For this when I try to cast any Geometry Object type to Geometry I get an error.

```<code>Sph sphere(0.1 , 32);
Geometry *geom = &sphere;
Container cont("Sphere" , "SPHERE" , *geometry );
myModel->SetContainer(child, cont);
</code>```

The Constructor for Container

```<code> Container::Container( std::string strName, std::string strType, const
 Geometry& geometry) : Geom(geometry)
  {
     stdstrContainerName = strName;
     stdstrPluginType = strType;
  }

 void  TreeModel::SetContainer(const QModelIndex &index, Container Cont)
  {
    TreeItem *item = getItem(index);
    item->setContainer(Cont);
  }

  class TreeItem
   {
    public:
     // Functions here
   private:
     QList<TreeItem*> childItems;
     Container itemData;
     TreeItem* parentItem;
   };
</code>```

1) Is this the correct approach?

2) How can I cast the Geometry objects to the Geometry pointer?

答:
With

```<code>Sph sphere();
</code>```

You have declared a function wich return a Sphere object and take no parameters.

To declare an object to Sph you just simple write

Sph sphere; or Sph sphere{};

I guess you tried the first but it didn't compile, so you just changed the signature "until compiled".
You have declared a custom constructor, which means the compiler does not provide you anymore a default constructor so you can't declare a variable without calling the correct constructor (and in your case it wouldn't have sense).

In addition with

```<code>Geometry *geom = new Geometry;
geom = &sphere;
</code>```

you're creating a new pointer geometry than leaking it immediatly and reassigning to a sphere geometry which has no sense at all.

Moreover all your method are public in Geometry and this does not have sense (why putting bool valid public and then a getter?).

in addition class Container is holding an instance to a base class which will give you issues due to object slicing, you need to use a pointer or a reference.

for just answering to your question you should instance a sphere with

```<code>Geometr* geom = new Sphere(1, 5); // random numbers
</code>```

but the most genuine and honest thing I can tell is to rewrite everything from scratch and before that to study a little more trying with an easier example.

Body:
I have a Geometry class

class Geometry
{
public:
    std::string stdstrType;
    bool bValid;
public:
    Geometry()

    Geometry( std::string strType , bool bValue )

    Geometry(const Geometry &g)

    ~Geometry()
    virtual void draw();
    bool isValid();
    void setValidState(bool bState);
    virtual void Init();
    std::string GetName();
};

Which is the base class for Geometry objects like in this case for Sphere class

class Sph : public Geometry
{
public:
    Sph( float radius , float segments );
    ~Sph();
    void init();
    void CleanUp();
    void draw();

private:
    float fRadius, fSegments;
    bool isInited;
    unsigned int m_VAO, m_VBO;
    int iNumsToDraw;
    SumShader shader;
    bool isChanged;
};

I have a Tree structure holding different Container objects and Geometry is a data type in the Container object.

class Container
{
private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry Geom;
}

Since each item in the tree can hold a circle sphere or rectangle so I would like to use the draw function of geometry to draw the Geometry object types.
For this when I try to cast any Geometry Object type to Geometry I get an error.

Sph sphere(0.1 , 32);
Geometry *geom = &sphere;
Container cont("Sphere" , "SPHERE" , *geometry );
myModel->SetContainer(child, cont);

The Constructor for Container

 Container::Container( std::string strName, std::string strType, const
 Geometry& geometry) : Geom(geometry)
  {
     stdstrContainerName = strName;
     stdstrPluginType = strType;
  }

 void  TreeModel::SetContainer(const QModelIndex &index, Container Cont)
  {
    TreeItem *item = getItem(index);
    item->setContainer(Cont);
  }

  class TreeItem
   {
    public:
     // Functions here
   private:
     QList<TreeItem*> childItems;
     Container itemData;
     TreeItem* parentItem;
   };

1) Is this the correct approach?

2) How can I cast the Geometry objects to the Geometry pointer?

Body:
With

Sph sphere();

You have declared a function wich return a Sphere object and take no parameters.

To declare an object to Sph you just simple write

Sph sphere; or Sph sphere{};

I guess you tried the first but it didn't compile, so you just changed the signature "until compiled".
You have declared a custom constructor, which means the compiler does not provide you anymore a default constructor so you can't declare a variable without calling the correct constructor (and in your case it wouldn't have sense).

In addition with

Geometry *geom = new Geometry;
geom = &sphere;

you're creating a new pointer geometry than leaking it immediatly and reassigning to a sphere geometry which has no sense at all.

Moreover all your method are public in Geometry and this does not have sense (why putting bool valid public and then a getter?).

in addition class Container is holding an instance to a base class which will give you issues due to object slicing, you need to use a pointer or a reference.

for just answering to your question you should instance a sphere with

Geometr* geom = new Sphere(1, 5); // random numbers

but the most genuine and honest thing I can tell is to rewrite everything from scratch and before that to study a little more trying with an easier example.


问:
How to Comma separate multiple rows obtained from a SQL Query
```<code>Select s.FirstName, glTitle.LookupItem Title
    from ClientStaff cs
    left outer join Staff s on s.Id = cs.StaffId
    left outer join StaffTitle st on st.StaffId = s.Id
    left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
</code>```

It returns these rows:

As you can see, the first column has all same rows because one employee can have multiple titles.

How can I merge all of the titles for each employee into a comma separated value so that there is only one row per employee?

答:
I usually create SQL functions and call them from my queries. You can create a comma delimited list of values using a multitude of approaches, see http://blog.sqlauthority.com/2008/06/04/sql-server-create-a-comma-delimited-list-using-select-clause-from-table-column/, Can I Comma Delimit Multiple Rows Into One Column?. </p>

<p>In this case if you create a function, you can then call it from your SQL query. Something like: </p>

```<code>select s.FirstName, dbo.GetAllJobTitlesForStaff(s.Id) AS AllJobTitles
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Select s.FirstName, glTitle.LookupItem Title
    from ClientStaff cs
    left outer join Staff s on s.Id = cs.StaffId
    left outer join StaffTitle st on st.StaffId = s.Id
    left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId

It returns these rows:

As you can see, the first column has all same rows because one employee can have multiple titles.

How can I merge all of the titles for each employee into a comma separated value so that there is only one row per employee?

Body:
I usually create SQL functions and call them from my queries. You can create a comma delimited list of values using a multitude of approaches, see http://blog.sqlauthority.com/2008/06/04/sql-server-create-a-comma-delimited-list-using-select-clause-from-table-column/, Can I Comma Delimit Multiple Rows Into One Column?.

In this case if you create a function, you can then call it from your SQL query. Something like:

select s.FirstName, dbo.GetAllJobTitlesForStaff(s.Id) AS AllJobTitles
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId


问:
How to escape '>' character in markdown
I have for example this sintax >45 which markdown has transformed it in:

I use a markdown library and in

escape : /^\[\`*_{}[]()#+.!-]/

I try to add the > but not working

escape : /^\[\`*_{}[]()#+.!>-]/

I want the expression >45 still >45 after applying markdown.

Update with solution:

In markdown library I added followind code in blockquote function:

var myRegex = new RegExp("^>.+");
  if ( !block.match( /^>/m ) || block.match(myRegex))
        return undefined;

答:
The bit of code I assume you are referring to is line 796:

```<code>if ( text.match( /^\\[\\`\*_{}\[\]()#\+.!\-]/ ) )
</code>```

To escape the > character try changing it to:

```<code>if ( text.match( /^\\[\\`\*_{}\[\]()#\+.!\->]/ ) )
</code>```

That string there is a regex, you should probably learn about it, they are very useful.

But do that as a last resort, have you tried just typing:

```<code>\> text
</code>```

instead?

Title: How to escape '>' character in markdown

Body:
The bit of code I assume you are referring to is line 796:

if ( text.match( /^\\[\\`\*_{}\[\]()#\+.!\-]/ ) )

To escape the > character try changing it to:

if ( text.match( /^\\[\\`\*_{}\[\]()#\+.!\->]/ ) )

That string there is a regex, you should probably learn about it, they are very useful.

But do that as a last resort, have you tried just typing:

\> text

instead?


问:
How to cast object in object into Angular Class (Type)
How can I cast obj.category into Category type in example below?

I need this to set selected options in dropdown.

```<code>export class Category{
    id: number;
    name: string;

    constructor(obj: any) {
        this.id = obj.id;
        this.name = obj.name;
    }
}

export class Post {
    category: Category[];

    constructor(obj: any) {
        this.category = obj.category;
    }
}
</code>```

Category service looks like this:

```<code>getCategories(): Promise<Category[]> {
    return this.http.get(this.appConfig.apiEndpoint + 'categories/').toPromise()
  .then(response => response.json().map(obj => new Category(obj)))
  .catch(this.handleError);
}
</code>```

Api response:

```<code>[{"id":1,"name":"cat1"},{"id":2,"name":"cat2"}]
</code>```

Template:

```<code><select multiple name="category" [(ngModel)]="obj.post.category">
    <option  *ngFor="let category of categories" [ngValue] = "category">
       {{category.name}}
    </option>
</select>
</code>```

答: The keyword as allowed me to properly cast my object to desired class and fixed the error ´TS2322: Type '{}' is not assignable to type ...´. Thanks!

Body:
How can I cast obj.category into Category type in example below?

I need this to set selected options in dropdown.

export class Category{
    id: number;
    name: string;

    constructor(obj: any) {
        this.id = obj.id;
        this.name = obj.name;
    }
}

export class Post {
    category: Category[];

    constructor(obj: any) {
        this.category = obj.category;
    }
}

Category service looks like this:

getCategories(): Promise<Category[]> {
    return this.http.get(this.appConfig.apiEndpoint + 'categories/').toPromise()
  .then(response => response.json().map(obj => new Category(obj)))
  .catch(this.handleError);
}

Api response:

[{"id":1,"name":"cat1"},{"id":2,"name":"cat2"}]

Template:

<select multiple name="category" [(ngModel)]="obj.post.category">
    <option  *ngFor="let category of categories" [ngValue] = "category">
       {{category.name}}
    </option>
</select>


问:
Mobile automation using Appium and Selenium for Android
In mobile automation using Appium and Selenium WebDriver for Android mobile, what is the difference between  capabilities.setCapability(CapabilityType.VERSION, "4.2") and  capabilities.setCapability("version", "4.2")?

答: Both are same in first we are using "Version" library and in second e</p>