问:
Get values from a document recursively
I have the following structure of the MongoDB database record:

```<code>{
    "_id" : ObjectId("5dd569eb628243119cd933f5"),
    "Name" : "Parent555",
    "hash" : "Q2Nj1nGtGJCkHT6eygg1L0OrprQkhGd846fdd5",
    "child_info" : {
        "Name" : "Child_one",
        "hash" : "2ac616b42d846fdd52002dc9ad7d810f9f8ce9",
        "child_info" : {
            "Name" : "Child_two",
            "hash" : "5cd9119ae60a0a58d38999468648c371c50b7a"
        }
    }
}
</code>```

Is there a query to aggregate all hashes recursively from the record to make the result look like that?

```<code>{
    "Parent555":{
        "Q2Nj1nGtGJCkHT6eygg1L0OrprQkhGd846fdd5",
        "2ac616b42d846fdd52002dc9ad7d810f9f8ce9",
        "5cd9119ae60a0a58d38999468648c371c50b7a"
    }
}
</code>```

There might be 4 or 5 nested child, that's why I'm interested in a recursive way of doing it.

答:
Please consider my comment:

I think, if you will use this type of schema, then it will be difficult to store and retrieve documents. How about storing the documents with the fields parent, child? Something like this?

```<code>{
    "parentName" : "Parent555",
    "hash" : "Q2Nj1nGtGJCkHT6eygg1L0OrprQkhGd846fdd5",
    "childName" : "Child_one"
},
{
    "parentName" : "Child_one",
    "hash" : "2ac616b42d846fdd52002dc9ad7d810f9f8ce9",
    "childName" : "Child_two"
},
{
    "parentName" : "Child_two",
    "hash" : "5cd9119ae60a0a58d38999468648c371c50b7a"
}
</code>```

The above schema is somewhat easy for retrieving and storing queries, as we may not to keep on nesting. If, you are bound with your schema, then, this will be helpful for others.

Considering the above collection, $graphLookup will be very helpful:

db.collection.aggregate([
  {
    $graphLookup: {
      from: "collection",
      startWith: "$childName",
      connectFromField: "childName",
      connectToField: "parentName",
      as: "child_hash"
    }
  },
  {
    $match: {
      "parentName": "Parent555"
    }
  },
  {
    $project: {
      parentName: 1,
      hash: 1,
      child_hash: {
        $map: {
          input: "$child_hash",
          as: "c",
          in: "$$c.hash"
        }
      }
    }
  }
])
```

<p>Output:</p>

```{
  "_id": ObjectId("5a934e000102030405000000"),
  "child_hash": [
    "5cd9119ae60a0a58d38999468648c371c50b7a",
    "2ac616b42d846fdd52002dc9ad7d810f9f8ce9"
  ],
  "hash": "Q2Nj1nGtGJCkHT6eygg1L0OrprQkhGd846fdd5",
  "parentName": "Parent555"
}
```

MongoPlayGroundLink

Title: Get values from a document recursively

Body:
I have the following structure of the MongoDB database record:

{
    "_id" : ObjectId("5dd569eb628243119cd933f5"),
    "Name" : "Parent555",
    "hash" : "Q2Nj1nGtGJCkHT6eygg1L0OrprQkhGd846fdd5",
    "child_info" : {
        "Name" : "Child_one",
        "hash" : "2ac616b42d846fdd52002dc9ad7d810f9f8ce9",
        "child_info" : {
            "Name" : "Child_two",
            "hash" : "5cd9119ae60a0a58d38999468648c371c50b7a"
        }
    }
}

Is there a query to aggregate all hashes recursively from the record to make the result look like that?

{
    "Parent555":{
        "Q2Nj1nGtGJCkHT6eygg1L0OrprQkhGd846fdd5",
        "2ac616b42d846fdd52002dc9ad7d810f9f8ce9",
        "5cd9119ae60a0a58d38999468648c371c50b7a"
    }
}

There might be 4 or 5 nested child, that's why I'm interested in a recursive way of doing it.

Body:
Please consider my comment:

I think, if you will use this type of schema, then it will be difficult to store and retrieve documents. How about storing the documents with the fields parent, child? Something like this?

{
    "parentName" : "Parent555",
    "hash" : "Q2Nj1nGtGJCkHT6eygg1L0OrprQkhGd846fdd5",
    "childName" : "Child_one"
},
{
    "parentName" : "Child_one",
    "hash" : "2ac616b42d846fdd52002dc9ad7d810f9f8ce9",
    "childName" : "Child_two"
},
{
    "parentName" : "Child_two",
    "hash" : "5cd9119ae60a0a58d38999468648c371c50b7a"
}

The above schema is somewhat easy for retrieving and storing queries, as we may not to keep on nesting. If, you are bound with your schema, then, this will be helpful for others.

Considering the above collection, $graphLookup will be very helpful:

db.collection.aggregate([
  {
    $graphLookup: {
      from: "collection",
      startWith: "$childName",
      connectFromField: "childName",
      connectToField: "parentName",
      as: "child_hash"
    }
  },
  {
    $match: {
      "parentName": "Parent555"
    }
  },
  {
    $project: {
      parentName: 1,
      hash: 1,
      child_hash: {
        $map: {
          input: "$child_hash",
          as: "c",
          in: "$$c.hash"
        }
      }
    }
  }
])

Output:

{
  "_id": ObjectId("5a934e000102030405000000"),
  "child_hash": [
    "5cd9119ae60a0a58d38999468648c371c50b7a",
    "2ac616b42d846fdd52002dc9ad7d810f9f8ce9"
  ],
  "hash": "Q2Nj1nGtGJCkHT6eygg1L0OrprQkhGd846fdd5",
  "parentName": "Parent555"
}

MongoPlayGroundLink


来源: stackexchange

问:
java.lang.ClassNotFoundException: net.corda.testing.core.DummyCommandData
When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.

MetalContract

```<code>package com.template.contracts;

import com.template.states.MetalState;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.CommandData;
import net.corda.core.contracts.Contract;
import net.corda.core.contracts.ContractState;
import net.corda.core.identity.Party;
import net.corda.core.transactions.LedgerTransaction;
import org.jetbrains.annotations.NotNull;

import java.security.PublicKey;
import java.util.List;

// ************
// * Contract *
// ************
public class MetalContract implements Contract {
    // This is used to identify our contract when building a transaction.
    public static final String CID = "com.template.contracts.MetalContract";

    // A transaction is valid if the verify() function of the contract of all the transaction's input and output states
    // does not throw an exception.
    @Override
    public void verify(@NotNull LedgerTransaction tx) throws IllegalArgumentException{

        if (tx.getCommands().size() != 1)
            throw new IllegalArgumentException("Transaction must have one Command.");

        Command command = tx.getCommand(0);
        CommandData commandType = command.getValue();

        List<PublicKey> requiredSigners = command.getSigners();

        // -------------------------------- Issue Command Contract Rules ------------------------------------------

     if (commandType instanceof Issue) {
         // Issue transaction logic

         // Shape Rules

         if (tx.getInputs().size() != 0)
             throw new IllegalArgumentException("Issue cannot have inputs");

         if (tx.getOutputs().size() != 1)
             throw new IllegalArgumentException("Issue can only have one output");

         // Content Rules

         ContractState outputState = tx.getOutput(0);

         if (!(outputState instanceof MetalState))
             throw new IllegalArgumentException("Output must be a metal State");

         MetalState metalState = (MetalState) outputState;

         if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
             throw new IllegalArgumentException("Metal is not Gold or Silver");
         }

         // Signer Rules

         Party issuer = metalState.getIssuer();
         PublicKey issuersKey = issuer.getOwningKey();

         if (!(requiredSigners.contains(issuersKey)))
             throw new IllegalArgumentException("Issuer has to sign the issuance");

     }

        // -------------------------------- Transfer Command Contract Rules ------------------------------------------

       else if (commandType instanceof Transfer) {
            // Transfer transaction logic

            // Shape Rules

            if (tx.getInputs().size() != 1)
                throw new IllegalArgumentException("Transfer needs to have one input");

            if (tx.getOutputs().size() != 1)
                throw new IllegalArgumentException("Transfer can only have one output");

            // Content Rules

            ContractState inputState = tx.getInput(0);
            ContractState outputState = tx.getOutput(0);

            if (!(outputState instanceof MetalState))
                throw new IllegalArgumentException("Output must be a metal State");

            MetalState metalState = (MetalState) inputState;

            if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
                throw new IllegalArgumentException("Metal is not Gold or Silver");
            }

            // Signer Rules

            Party owner = metalState.getOwner();
            PublicKey ownersKey = owner.getOwningKey();

            if (!(requiredSigners.contains(ownersKey)))
                throw new IllegalArgumentException("Owner has to sign the transfer");

        }

       else  throw new IllegalArgumentException("Unrecognised command.");

    }

    // Used to indicate the transaction's intent.
    public static class Issue implements CommandData {}
    public static class Transfer implements CommandData {}
}

</code>```

ContractTests

```<code>package com.template.contracts;

import com.template.states.MetalState;
import com.template.contracts.MetalContract;
import net.corda.core.contracts.Contract;
import net.corda.core.identity.CordaX500Name;
import net.corda.testing.contracts.DummyState;
import net.corda.testing.core.DummyCommandData;
import net.corda.testing.core.TestIdentity;
import net.corda.testing.node.MockServices;
import org.junit.Test;

import static net.corda.testing.node.NodeTestUtils.transaction;

public class ContractTests {

    private final TestIdentity Mint = new TestIdentity (new CordaX500Name ("mint", "", "GB"));
    private final TestIdentity TraderA = new TestIdentity (new CordaX500Name ("traderA", "", "GB"));
    private final TestIdentity TraderB = new TestIdentity (new CordaX500Name ("traderB", "", "GB"));

    private final MockServices ledgerServices = new MockServices();

    private MetalState metalState = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
    private MetalState metalStateInput = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
    private MetalState metalStateOutput = new MetalState("Gold", 10, Mint.getParty(), TraderB.getParty());

    @Test
    public void metalContractImplementsContract() {
        assert (new MetalContract() instanceof Contract);
    }
    @Test
    public void MetalContractRequiresTheTransactionCommandToBeATransferCommand() {

        transaction(ledgerServices, tx -> {
            // Has wrong command, will fail
            tx.input(MetalContract.CID, metalStateInput);
            tx.output(MetalContract.CID, metalStateOutput);
            tx.command(TraderA.getPublicKey(), DummyCommandData.INSTANCE);
            tx.fails();
            return null;
        });
   }
</code>```

The Error is as following :

```<code>[WARN] 12:35:16,753 [main] contracts.AttachmentConstraint. - Found state com.template.contracts.MetalContract that is constrained by the insecure: AlwaysAcceptAttachmentConstraint.

net.corda.core.internal.TransactionDeserialisationException: Failed to deserialise group COMMANDS_GROUP at index 0 in transaction: Internal deserialization failure: java.lang.ClassNotFoundException: net.corda.testing.core.DummyCommandData

    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt:82)
    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt)
    at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
    at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
    at java.util.AbstractList$Itr.next(AbstractList.java:358)
    at net.corda.core.transactions.LedgerTransaction.createLtxForVerification(LedgerTransaction.kt:668)
    at net.corda.core.transactions.LedgerTransaction.access$createLtxForVerification(LedgerTransaction.kt:44)
    at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:154)
    at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:44)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder$withAttachmentsClassloaderContext$1.invoke(AttachmentsClassLoader.kt:345)
    at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext(AttachmentsClassLoader.kt:344)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext$default(AttachmentsClassLoader.kt:319)
    at net.corda.core.transactions.LedgerTransaction.internalPrepareVerify$core(LedgerTransaction.kt:146)
    at net.corda.core.transactions.LedgerTransaction.verify(LedgerTransaction.kt:136)
    at net.corda.core.transactions.TransactionBuilder.addMissingDependency(TransactionBuilder.kt:185)
    at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core(TransactionBuilder.kt:165)
    at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core$default(TransactionBuilder.kt:133)
    at net.corda.core.transactions.TransactionBuilder.toWireTransaction(TransactionBuilder.kt:130)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.toWireTransaction$test_utils(TestDSL.kt:131)
    at net.corda.testing.dsl.TestLedgerDSLInterpreter.recordTransactionWithTransactionMap(TestDSL.kt:298)
    at net.corda.testing.dsl.TestLedgerDSLInterpreter._unverifiedTransaction(TestDSL.kt:336)
    at net.corda.testing.dsl.TransactionDSL.input(TransactionDSLInterpreter.kt:150)
    at com.template.contracts.ContractTests.lambda$MetalContractRequiresTheTransactionCommandToBeATransferCommand$13(ContractTests.java:190)
    at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt:54)
    at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt)
    at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt:39)
    at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt)
    at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt:231)
    at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt)
    at net.corda.testing.common.internal.CommonSerializationTestHelpersKt.asContextEnv(CommonSerializationTestHelpers.kt:11)
    at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv(InternalSerializationTestHelpers.kt:33)
    at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv$default(InternalSerializationTestHelpers.kt:31)
    at net.corda.testing.internal.InternalTestUtilsKt.withTestSerializationEnvIfNotSet(InternalTestUtils.kt:231)
    at net.corda.testing.node.NodeTestUtils.ledger(NodeTestUtils.kt:36)
    at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt:53)
    at net.corda.testing.node.NodeTestUtils.transaction$default(NodeTestUtils.kt:51)
    at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt)
    at com.template.contracts.ContractTests.MetalContractRequiresTheTransactionCommandToBeATransferCommand(ContractTests.java:188)
    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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
    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 com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
Caused by: java.io.NotSerializableException: Internal deserialization failure: java.lang.ClassNotFoundException: net.corda.testing.core.DummyCommandData
    at net.corda.serialization.internal.amqp.DeserializationInput.des(DeserializationInput.kt:106)
    at net.corda.serialization.internal.amqp.DeserializationInput.deserialize(DeserializationInput.kt:119)
    at net.corda.serialization.internal.amqp.AbstractAMQPSerializationScheme.deserialize(AMQPSerializationScheme.kt:145)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1$1.invoke(SerializationScheme.kt:105)
    at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:105)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:73)
    at net.corda.core.serialization.SerializationFactory.asCurrent(SerializationAPI.kt:85)
    at net.corda.serialization.internal.SerializationFactoryImpl.deserialize(SerializationScheme.kt:105)
    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt:78)
    ... 65 more
Caused by: java.lang.ClassNotFoundException: net.corda.testing.core.DummyCommandData
    at java.lang.ClassLoader.findClass(ClassLoader.java:523)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at net.corda.serialization.internal.model.TypeIdentifier$Unparameterised.getLocalType(TypeIdentifier.kt:151)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:38)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:25)
    at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:38)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:25)
    at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:149)
    at kotlin.sequences.FilteringSequence$iterator$1.calcNext(Sequences.kt:109)
    at kotlin.sequences.FilteringSequence$iterator$1.hasNext(Sequences.kt:133)
    at kotlin.collections.MapsKt__MapsKt.putAll(Maps.kt:339)
    at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:504)
    at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:498)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader.load(TypeLoader.kt:45)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.reflect(RemoteSerializerFactory.kt:129)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.access$reflect(RemoteSerializerFactory.kt:47)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:71)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:47)
    at net.corda.serialization.internal.amqp.DefaultDescriptorBasedSerializerRegistry.getOrBuild(DescriptorBasedSerializerRegistry.kt:28)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.get(RemoteSerializerFactory.kt:66)
    at net.corda.serialization.internal.amqp.ComposedSerializerFactory.get(SerializerFactory.kt)
    at net.corda.serialization.internal.amqp.DeserializationInput.readObject(DeserializationInput.kt:172)
    at net.corda.serialization.internal.amqp.DeserializationInput.readObjectOrNull(DeserializationInput.kt:147)
    at net.corda.serialization.internal.amqp.DeserializationInput$deserialize$1.invoke(DeserializationInput.kt:124)
    at net.corda.serialization.internal.amqp.DeserializationInput.des(DeserializationInput.kt:99)
    ... 74 more
</code>```

build.gradle file

```<code>apply plugin: 'net.corda.plugins.cordapp'
apply plugin: 'net.corda.plugins.cordformation'

cordapp {
    targetPlatformVersion corda_platform_version
    minimumPlatformVersion corda_platform_version
    contract {
        name "Template CorDapp"
        vendor "Corda Open Source"
        licence "Apache License, Version 2.0"
        versionId 1
    }
}

sourceSets {
    main{
        java {
            srcDir 'src/main/java'
            java.outputDir = file('bin/main')
        }
    }
    test{
        java{
            srcDir 'src/test/java'
            java.outputDir = file('bin/test')
        }
    }
}

dependencies {
    // Corda dependencies.
    cordaCompile "$corda_release_group:corda-core:$corda_release_version"
    cordaRuntime "$corda_release_group:corda:$corda_release_version"
    testCompile "$corda_release_group:corda-node-driver:$corda_release_version"
}
</code>```

答:
This is a problem caused by your DummyCommandData.

The Command has to be defined inside your contract instead of creating another data class aside.

Try putting a command inside your contract.
ie.

```<code>public MetalContract extends Contract{

    public interface Commands extends CommandData {
        class Create implements Commands {}
    }
    //...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.

MetalContract

package com.template.contracts;

import com.template.states.MetalState;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.CommandData;
import net.corda.core.contracts.Contract;
import net.corda.core.contracts.ContractState;
import net.corda.core.identity.Party;
import net.corda.core.transactions.LedgerTransaction;
import org.jetbrains.annotations.NotNull;

import java.security.PublicKey;
import java.util.List;

// ************
// * Contract *
// ************
public class MetalContract implements Contract {
    // This is used to identify our contract when building a transaction.
    public static final String CID = "com.template.contracts.MetalContract";

    // A transaction is valid if the verify() function of the contract of all the transaction's input and output states
    // does not throw an exception.
    @Override
    public void verify(@NotNull LedgerTransaction tx) throws IllegalArgumentException{

        if (tx.getCommands().size() != 1)
            throw new IllegalArgumentException("Transaction must have one Command.");

        Command command = tx.getCommand(0);
        CommandData commandType = command.getValue();

        List<PublicKey> requiredSigners = command.getSigners();

        // -------------------------------- Issue Command Contract Rules ------------------------------------------

     if (commandType instanceof Issue) {
         // Issue transaction logic

         // Shape Rules

         if (tx.getInputs().size() != 0)
             throw new IllegalArgumentException("Issue cannot have inputs");

         if (tx.getOutputs().size() != 1)
             throw new IllegalArgumentException("Issue can only have one output");

         // Content Rules

         ContractState outputState = tx.getOutput(0);

         if (!(outputState instanceof MetalState))
             throw new IllegalArgumentException("Output must be a metal State");

         MetalState metalState = (MetalState) outputState;

         if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
             throw new IllegalArgumentException("Metal is not Gold or Silver");
         }

         // Signer Rules

         Party issuer = metalState.getIssuer();
         PublicKey issuersKey = issuer.getOwningKey();

         if (!(requiredSigners.contains(issuersKey)))
             throw new IllegalArgumentException("Issuer has to sign the issuance");

     }

        // -------------------------------- Transfer Command Contract Rules ------------------------------------------

       else if (commandType instanceof Transfer) {
            // Transfer transaction logic

            // Shape Rules

            if (tx.getInputs().size() != 1)
                throw new IllegalArgumentException("Transfer needs to have one input");

            if (tx.getOutputs().size() != 1)
                throw new IllegalArgumentException("Transfer can only have one output");

            // Content Rules

            ContractState inputState = tx.getInput(0);
            ContractState outputState = tx.getOutput(0);

            if (!(outputState instanceof MetalState))
                throw new IllegalArgumentException("Output must be a metal State");

            MetalState metalState = (MetalState) inputState;

            if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
                throw new IllegalArgumentException("Metal is not Gold or Silver");
            }

            // Signer Rules

            Party owner = metalState.getOwner();
            PublicKey ownersKey = owner.getOwningKey();

            if (!(requiredSigners.contains(ownersKey)))
                throw new IllegalArgumentException("Owner has to sign the transfer");

        }

       else  throw new IllegalArgumentException("Unrecognised command.");

    }

    // Used to indicate the transaction's intent.
    public static class Issue implements CommandData {}
    public static class Transfer implements CommandData {}
}

ContractTests

package com.template.contracts;

import com.template.states.MetalState;
import com.template.contracts.MetalContract;
import net.corda.core.contracts.Contract;
import net.corda.core.identity.CordaX500Name;
import net.corda.testing.contracts.DummyState;
import net.corda.testing.core.DummyCommandData;
import net.corda.testing.core.TestIdentity;
import net.corda.testing.node.MockServices;
import org.junit.Test;

import static net.corda.testing.node.NodeTestUtils.transaction;

public class ContractTests {

    private final TestIdentity Mint = new TestIdentity (new CordaX500Name ("mint", "", "GB"));
    private final TestIdentity TraderA = new TestIdentity (new CordaX500Name ("traderA", "", "GB"));
    private final TestIdentity TraderB = new TestIdentity (new CordaX500Name ("traderB", "", "GB"));

    private final MockServices ledgerServices = new MockServices();

    private MetalState metalState = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
    private MetalState metalStateInput = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
    private MetalState metalStateOutput = new MetalState("Gold", 10, Mint.getParty(), TraderB.getParty());

    @Test
    public void metalContractImplementsContract() {
        assert (new MetalContract() instanceof Contract);
    }
    @Test
    public void MetalContractRequiresTheTransactionCommandToBeATransferCommand() {

        transaction(ledgerServices, tx -> {
            // Has wrong command, will fail
            tx.input(MetalContract.CID, metalStateInput);
            tx.output(MetalContract.CID, metalStateOutput);
            tx.command(TraderA.getPublicKey(), DummyCommandData.INSTANCE);
            tx.fails();
            return null;
        });
   }

The Error is as following :

[WARN] 12:35:16,753 [main] contracts.AttachmentConstraint. - Found state com.template.contracts.MetalContract that is constrained by the insecure: AlwaysAcceptAttachmentConstraint.

net.corda.core.internal.TransactionDeserialisationException: Failed to deserialise group COMMANDS_GROUP at index 0 in transaction: Internal deserialization failure: java.lang.ClassNotFoundException: net.corda.testing.core.DummyCommandData

    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt:82)
    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt)
    at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
    at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
    at java.util.AbstractList$Itr.next(AbstractList.java:358)
    at net.corda.core.transactions.LedgerTransaction.createLtxForVerification(LedgerTransaction.kt:668)
    at net.corda.core.transactions.LedgerTransaction.access$createLtxForVerification(LedgerTransaction.kt:44)
    at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:154)
    at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:44)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder$withAttachmentsClassloaderContext$1.invoke(AttachmentsClassLoader.kt:345)
    at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext(AttachmentsClassLoader.kt:344)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext$default(AttachmentsClassLoader.kt:319)
    at net.corda.core.transactions.LedgerTransaction.internalPrepareVerify$core(LedgerTransaction.kt:146)
    at net.corda.core.transactions.LedgerTransaction.verify(LedgerTransaction.kt:136)
    at net.corda.core.transactions.TransactionBuilder.addMissingDependency(TransactionBuilder.kt:185)
    at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core(TransactionBuilder.kt:165)
    at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core$default(TransactionBuilder.kt:133)
    at net.corda.core.transactions.TransactionBuilder.toWireTransaction(TransactionBuilder.kt:130)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.toWireTransaction$test_utils(TestDSL.kt:131)
    at net.corda.testing.dsl.TestLedgerDSLInterpreter.recordTransactionWithTransactionMap(TestDSL.kt:298)
    at net.corda.testing.dsl.TestLedgerDSLInterpreter._unverifiedTransaction(TestDSL.kt:336)
    at net.corda.testing.dsl.TransactionDSL.input(TransactionDSLInterpreter.kt:150)
    at com.template.contracts.ContractTests.lambda$MetalContractRequiresTheTransactionCommandToBeATransferCommand$13(ContractTests.java:190)
    at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt:54)
    at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt)
    at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt:39)
    at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt)
    at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt:231)
    at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt)
    at net.corda.testing.common.internal.CommonSerializationTestHelpersKt.asContextEnv(CommonSerializationTestHelpers.kt:11)
    at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv(InternalSerializationTestHelpers.kt:33)
    at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv$default(InternalSerializationTestHelpers.kt:31)
    at net.corda.testing.internal.InternalTestUtilsKt.withTestSerializationEnvIfNotSet(InternalTestUtils.kt:231)
    at net.corda.testing.node.NodeTestUtils.ledger(NodeTestUtils.kt:36)
    at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt:53)
    at net.corda.testing.node.NodeTestUtils.transaction$default(NodeTestUtils.kt:51)
    at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt)
    at com.template.contracts.ContractTests.MetalContractRequiresTheTransactionCommandToBeATransferCommand(ContractTests.java:188)
    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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
    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 com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
Caused by: java.io.NotSerializableException: Internal deserialization failure: java.lang.ClassNotFoundException: net.corda.testing.core.DummyCommandData
    at net.corda.serialization.internal.amqp.DeserializationInput.des(DeserializationInput.kt:106)
    at net.corda.serialization.internal.amqp.DeserializationInput.deserialize(DeserializationInput.kt:119)
    at net.corda.serialization.internal.amqp.AbstractAMQPSerializationScheme.deserialize(AMQPSerializationScheme.kt:145)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1$1.invoke(SerializationScheme.kt:105)
    at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:105)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:73)
    at net.corda.core.serialization.SerializationFactory.asCurrent(SerializationAPI.kt:85)
    at net.corda.serialization.internal.SerializationFactoryImpl.deserialize(SerializationScheme.kt:105)
    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt:78)
    ... 65 more
Caused by: java.lang.ClassNotFoundException: net.corda.testing.core.DummyCommandData
    at java.lang.ClassLoader.findClass(ClassLoader.java:523)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at net.corda.serialization.internal.model.TypeIdentifier$Unparameterised.getLocalType(TypeIdentifier.kt:151)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:38)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:25)
    at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:38)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:25)
    at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:149)
    at kotlin.sequences.FilteringSequence$iterator$1.calcNext(Sequences.kt:109)
    at kotlin.sequences.FilteringSequence$iterator$1.hasNext(Sequences.kt:133)
    at kotlin.collections.MapsKt__MapsKt.putAll(Maps.kt:339)
    at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:504)
    at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:498)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader.load(TypeLoader.kt:45)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.reflect(RemoteSerializerFactory.kt:129)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.access$reflect(RemoteSerializerFactory.kt:47)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:71)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:47)
    at net.corda.serialization.internal.amqp.DefaultDescriptorBasedSerializerRegistry.getOrBuild(DescriptorBasedSerializerRegistry.kt:28)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.get(RemoteSerializerFactory.kt:66)
    at net.corda.serialization.internal.amqp.ComposedSerializerFactory.get(SerializerFactory.kt)
    at net.corda.serialization.internal.amqp.DeserializationInput.readObject(DeserializationInput.kt:172)
    at net.corda.serialization.internal.amqp.DeserializationInput.readObjectOrNull(DeserializationInput.kt:147)
    at net.corda.serialization.internal.amqp.DeserializationInput$deserialize$1.invoke(DeserializationInput.kt:124)
    at net.corda.serialization.internal.amqp.DeserializationInput.des(DeserializationInput.kt:99)
    ... 74 more

build.gradle file

apply plugin: 'net.corda.plugins.cordapp'
apply plugin: 'net.corda.plugins.cordformation'

cordapp {
    targetPlatformVersion corda_platform_version
    minimumPlatformVersion corda_platform_version
    contract {
        name "Template CorDapp"
        vendor "Corda Open Source"
        licence "Apache License, Version 2.0"
        versionId 1
    }
}

sourceSets {
    main{
        java {
            srcDir 'src/main/java'
            java.outputDir = file('bin/main')
        }
    }
    test{
        java{
            srcDir 'src/test/java'
            java.outputDir = file('bin/test')
        }
    }
}

dependencies {
    // Corda dependencies.
    cordaCompile "$corda_release_group:corda-core:$corda_release_version"
    cordaRuntime "$corda_release_group:corda:$corda_release_version"
    testCompile "$corda_release_group:corda-node-driver:$corda_release_version"
}

Body:
This is a problem caused by your DummyCommandData.

The Command has to be defined inside your contract instead of creating another data class aside.

Try putting a command inside your contract.
ie.

public MetalContract extends Contract{

    public interface Commands extends CommandData {
        class Create implements Commands {}
    }
    //...
}


问:
Javascript Object to Array
I'm having some problems with converting some JSON and I'm after some help.  This is my problem, I have JSON returned the following:

Example of the JSON recieved (from a CSV file):

```<code>[
    {
        "rating": "0",
        "title": "The Killing Kind",
        "author": "John Connolly",
        "type": "Book",
        "asin": "0340771224",
        "tags": "",
        "review": "i still haven't had time to read this one..."
    },
    {
        "rating": "0",
        "title": "The Third Secret",
        "author": "Steve Berry",
        "type": "Book",
        "asin": "0340899263",
        "tags": "",
        "review": "need to find time to read this book"
    },

    cut for brevity

]
</code>```

Now, this is a one dimensional array of objects, but I have a function that I need to pass this to that will ONLY take a multidimensional array.  There's nothing I can change on this.  I've been looking around the web for conversion and came across this code:

```<code>if (! obj.length) { return [];} // length must be set on the object, or it is not iterable
   var a = [];

   try {
       a = Array.prototype.slice.call(obj, n);
   }
   // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force
   catch(e) {
       Core.batch(obj, function(o, i) {
           if (n <= i) {
               a[i - n] = o;
           }
       });
   }

   return a;
</code>```

But my code keeps getting stuck on the "no object length" part.  When I iterate through each object, I get character by character.  Unfortunately, those field names (rating, title, author), etc are not set in stone and I can't access anything using the obj.Field notation.

I'm stuck on this; is there a way to convert those objects into arrays, or do I have to go back to the beginning and dump JSON?

答:
If I understand you correctly, there are two things you need to know to achieve this.

One is the fact that object.member can also be written as object["member"].  This means that you do not have to hard-code your property names into your object to array translator, but can treat them as strings.

The second is the for-in statement (see section 12.6.4). For an object, this loops through all of its members.

The following will result in innerArray being an array containing all of the values of all the members of the object

```<code>var innerArray = [];
for (property in object) {
    innerArray.push(object[property]);
}
</code>```

Using this knowledge, you can tailor the array to contain whatever information it is you need to extract from the json objects.

ContentLicense: CC BY-SA 3.0

Title: Javascript Object to Array

Body:
I'm having some problems with converting some JSON and I'm after some help.  This is my problem, I have JSON returned the following:

Example of the JSON recieved (from a CSV file):

[
    {
        "rating": "0",
        "title": "The Killing Kind",
        "author": "John Connolly",
        "type": "Book",
        "asin": "0340771224",
        "tags": "",
        "review": "i still haven't had time to read this one..."
    },
    {
        "rating": "0",
        "title": "The Third Secret",
        "author": "Steve Berry",
        "type": "Book",
        "asin": "0340899263",
        "tags": "",
        "review": "need to find time to read this book"
    },

    cut for brevity

]

Now, this is a one dimensional array of objects, but I have a function that I need to pass this to that will ONLY take a multidimensional array.  There's nothing I can change on this.  I've been looking around the web for conversion and came across this code:

if (! obj.length) { return [];} // length must be set on the object, or it is not iterable
   var a = [];

   try {
       a = Array.prototype.slice.call(obj, n);
   }
   // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force
   catch(e) {
       Core.batch(obj, function(o, i) {
           if (n <= i) {
               a[i - n] = o;
           }
       });
   }

   return a;

But my code keeps getting stuck on the "no object length" part.  When I iterate through each object, I get character by character.  Unfortunately, those field names (rating, title, author), etc are not set in stone and I can't access anything using the obj.Field notation.

I'm stuck on this; is there a way to convert those objects into arrays, or do I have to go back to the beginning and dump JSON?

Body:
If I understand you correctly, there are two things you need to know to achieve this.

One is the fact that object.member can also be written as object["member"].  This means that you do not have to hard-code your property names into your object to array translator, but can treat them as strings.

The second is the for-in statement (see section 12.6.4). For an object, this loops through all of its members.

The following will result in innerArray being an array containing all of the values of all the members of the object

var innerArray = [];
for (property in object) {
    innerArray.push(object[property]);
}

Using this knowledge, you can tailor the array to contain whatever information it is you need to extract from the json objects.


问:
SQL: display newest entry
I'm not really much of a developer, I only started self-learning VBA for Excel this year and I only started working with SQL two days ago...

That said: I'm trying to write a query that only shows the newest entry for each INVBTICKETNO based on ITTRANDATE but I can't seem to figure it out.

```<code>SELECT
  WHSNAME.WHSNNAME AS [Warehouse Name]
 ,VALID_BIN.BIN_TYPE AS T
 ,INVENTORY_BIN.INVBBINNO AS [Bin Number]
 ,INVENTORY_BIN.INVBITEMNO AS [Item Number]
 ,INVENTORY_ITEM_TAB.DESCR AS [Item Description]
 ,PRODUCT_CODE.DESCR AS [Product Code & Description]
 ,CUSTOMER.CSNAME AS [Customer Name]
 ,ORDERS.ORDER_NO AS [Oder No]
 ,INVENTORY_BIN.DATE_OF_INVENTORY AS [Date of Inventory]
 ,INVENTORY_BIN.INVBTICKETNO AS [Ticket No]
 ,INVENTORY_BIN.INVBQTYONHAND AS [Qty on Hand]
 ,ORDERS.QTY_ORDERED AS [Qty Ordered]
 ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT AS MSF
 ,INVENTORY_BIN.EXTENDED_CST AS [Valuation?]
 ,INVENTORY_TRAN.ITSOURCE AS Source
 ,INVENTORY_TRAN.ITCOMMENT AS Comment
 ,MAX(INVENTORY_TRAN.ITTRANDATE) AS [Trans Date]
 ,ORDERS.FOR_INVT_FLG AS Flag
 ,SALESAGENT.SANAME AS [Sales Agent]
 ,ORDERS.CUST_PO_NO AS [Customer PO No]
FROM dbo.INVENTORY_BIN INVENTORY_BIN
INNER JOIN dbo.INVENTORY_ITEM_TAB INVENTORY_ITEM_TAB
  ON INVENTORY_BIN.INVBITEMNO = INVENTORY_ITEM_TAB.ITEM_NO
INNER JOIN dbo.WHSNAME WHSNAME
  ON INVENTORY_BIN.INVBWHSNCODE = WHSNAME.WHSNCODE
INNER JOIN dbo.VALID_BIN VALID_BIN
  ON INVENTORY_BIN.INVBBINNO = VALID_BIN.BIN_ID
    AND INVENTORY_BIN.INVBWHSNCODE = VALID_BIN.WHSNCODE
LEFT OUTER JOIN dbo.INVENTORY_TRAN INVENTORY_TRAN
  ON INVENTORY_BIN.INVBTICKETNO = INVENTORY_TRAN.ITTICKETNO
    AND INVENTORY_BIN.DATE_LST_ACTIVITY < INVENTORY_TRAN.ITTRANDATE
LEFT OUTER JOIN dbo.CUSTOMER CUSTOMER
  ON INVENTORY_BIN.CSCODE = CUSTOMER.CSCODE
LEFT OUTER JOIN dbo.ORDERS ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
INNER JOIN dbo.PRODUCT_CODE PRODUCT_CODE
  ON INVENTORY_ITEM_TAB.PROD_CD = PRODUCT_CODE.PROD_CD
LEFT OUTER JOIN dbo.SALESAGENT SALESAGENT
  ON CUSTOMER.SACODE = SALESAGENT.SACODE
WHERE ORDERS.FOR_INVT_FLG = 'R'
GROUP BY INVENTORY_BIN.INVBITEMNO
        ,INVENTORY_BIN.INVBBINNO
        ,INVENTORY_BIN.INVBQTYONHAND
        ,INVENTORY_BIN.DATE_OF_INVENTORY
        ,INVENTORY_BIN.EXTENDED_CST
        ,INVENTORY_ITEM_TAB.DESCR
        ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT
        ,WHSNAME.WHSNNAME
        ,VALID_BIN.BIN_TYPE
        ,INVENTORY_TRAN.ITSOURCE
        ,CUSTOMER.CSNAME
        ,ORDERS.ORDER_NO
        ,ORDERS.CUST_PO_NO
        ,ORDERS.QTY_ORDERED
        ,PRODUCT_CODE.DESCR
        ,SALESAGENT.SANAME
        ,ORDERS.FOR_INVT_FLG
        ,INVENTORY_BIN.INVBTICKETNO
        ,INVENTORY_TRAN.ITCOMMENT
ORDER BY [Date of Inventory]
</code>```

答:
Replace

```<code>LEFT OUTER JOIN dbo.INVENTORY_TRAN INVENTORY_TRAN
  ON INVENTORY_BIN.INVBTICKETNO = INVENTORY_TRAN.ITTICKETNO
    AND INVENTORY_BIN.DATE_LST_ACTIVITY < INVENTORY_TRAN.ITTRANDATE
</code>```

then add the columns in a sub select, which determines the comment-row with the most recent date:

```<code>INNER JOIN (SELECT
   INVENTORY_TRAN.ITTICKETNO
   ,INVENTORY_TRAN.ITSOURCE AS [Source]
   ,INVENTORY_TRAN.ITCOMMENT AS [Comment]
   ,MAX(INVENTORY_TRAN.ITTRANDATE) [Trans Date]
FROM [INVENTORY_TRAN]
GROUP BY INVENTORY_TRAN.ITTICKETNO, INVENTORY_TRAN.ITSOURCE, INVENTORY_TRAN.ITCOMMENT
HAVING MAX(INVENTORY_TRAN.ITTRANDATE) = INVENTORY_TRAN.ITTRANDATE
) AS [sub_INVENTORY_TRAN] ON [INVENTORY_BIN].[INVBTICKETNO] = [sub_INVENTORY_TRAN].[ITTICKETNO]
</code>```

You also need to replace the selected columns with the new added through the sub select:

```<code>   ,[sub_INVENTORY_TRAN].[Source]
   ,[sub_INVENTORY_TRAN].[Comment]
   ,[sub_INVENTORY_TRAN].[Trans Date]
</code>```

Title: SQL: display newest entry

Body:
I'm not really much of a developer, I only started self-learning VBA for Excel this year and I only started working with SQL two days ago...

That said: I'm trying to write a query that only shows the newest entry for each INVBTICKETNO based on ITTRANDATE but I can't seem to figure it out.

SELECT
  WHSNAME.WHSNNAME AS [Warehouse Name]
 ,VALID_BIN.BIN_TYPE AS T
 ,INVENTORY_BIN.INVBBINNO AS [Bin Number]
 ,INVENTORY_BIN.INVBITEMNO AS [Item Number]
 ,INVENTORY_ITEM_TAB.DESCR AS [Item Description]
 ,PRODUCT_CODE.DESCR AS [Product Code & Description]
 ,CUSTOMER.CSNAME AS [Customer Name]
 ,ORDERS.ORDER_NO AS [Oder No]
 ,INVENTORY_BIN.DATE_OF_INVENTORY AS [Date of Inventory]
 ,INVENTORY_BIN.INVBTICKETNO AS [Ticket No]
 ,INVENTORY_BIN.INVBQTYONHAND AS [Qty on Hand]
 ,ORDERS.QTY_ORDERED AS [Qty Ordered]
 ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT AS MSF
 ,INVENTORY_BIN.EXTENDED_CST AS [Valuation?]
 ,INVENTORY_TRAN.ITSOURCE AS Source
 ,INVENTORY_TRAN.ITCOMMENT AS Comment
 ,MAX(INVENTORY_TRAN.ITTRANDATE) AS [Trans Date]
 ,ORDERS.FOR_INVT_FLG AS Flag
 ,SALESAGENT.SANAME AS [Sales Agent]
 ,ORDERS.CUST_PO_NO AS [Customer PO No]
FROM dbo.INVENTORY_BIN INVENTORY_BIN
INNER JOIN dbo.INVENTORY_ITEM_TAB INVENTORY_ITEM_TAB
  ON INVENTORY_BIN.INVBITEMNO = INVENTORY_ITEM_TAB.ITEM_NO
INNER JOIN dbo.WHSNAME WHSNAME
  ON INVENTORY_BIN.INVBWHSNCODE = WHSNAME.WHSNCODE
INNER JOIN dbo.VALID_BIN VALID_BIN
  ON INVENTORY_BIN.INVBBINNO = VALID_BIN.BIN_ID
    AND INVENTORY_BIN.INVBWHSNCODE = VALID_BIN.WHSNCODE
LEFT OUTER JOIN dbo.INVENTORY_TRAN INVENTORY_TRAN
  ON INVENTORY_BIN.INVBTICKETNO = INVENTORY_TRAN.ITTICKETNO
    AND INVENTORY_BIN.DATE_LST_ACTIVITY < INVENTORY_TRAN.ITTRANDATE
LEFT OUTER JOIN dbo.CUSTOMER CUSTOMER
  ON INVENTORY_BIN.CSCODE = CUSTOMER.CSCODE
LEFT OUTER JOIN dbo.ORDERS ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
INNER JOIN dbo.PRODUCT_CODE PRODUCT_CODE
  ON INVENTORY_ITEM_TAB.PROD_CD = PRODUCT_CODE.PROD_CD
LEFT OUTER JOIN dbo.SALESAGENT SALESAGENT
  ON CUSTOMER.SACODE = SALESAGENT.SACODE
WHERE ORDERS.FOR_INVT_FLG = 'R'
GROUP BY INVENTORY_BIN.INVBITEMNO
        ,INVENTORY_BIN.INVBBINNO
        ,INVENTORY_BIN.INVBQTYONHAND
        ,INVENTORY_BIN.DATE_OF_INVENTORY
        ,INVENTORY_BIN.EXTENDED_CST
        ,INVENTORY_ITEM_TAB.DESCR
        ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT
        ,WHSNAME.WHSNNAME
        ,VALID_BIN.BIN_TYPE
        ,INVENTORY_TRAN.ITSOURCE
        ,CUSTOMER.CSNAME
        ,ORDERS.ORDER_NO
        ,ORDERS.CUST_PO_NO
        ,ORDERS.QTY_ORDERED
        ,PRODUCT_CODE.DESCR
        ,SALESAGENT.SANAME
        ,ORDERS.FOR_INVT_FLG
        ,INVENTORY_BIN.INVBTICKETNO
        ,INVENTORY_TRAN.ITCOMMENT
ORDER BY [Date of Inventory]

Body:
Replace

LEFT OUTER JOIN dbo.INVENTORY_TRAN INVENTORY_TRAN
  ON INVENTORY_BIN.INVBTICKETNO = INVENTORY_TRAN.ITTICKETNO
    AND INVENTORY_BIN.DATE_LST_ACTIVITY < INVENTORY_TRAN.ITTRANDATE

then add the columns in a sub select, which determines the comment-row with the most recent date:

INNER JOIN (SELECT
   INVENTORY_TRAN.ITTICKETNO
   ,INVENTORY_TRAN.ITSOURCE AS [Source]
   ,INVENTORY_TRAN.ITCOMMENT AS [Comment]
   ,MAX(INVENTORY_TRAN.ITTRANDATE) [Trans Date]
FROM [INVENTORY_TRAN]
GROUP BY INVENTORY_TRAN.ITTICKETNO, INVENTORY_TRAN.ITSOURCE, INVENTORY_TRAN.ITCOMMENT
HAVING MAX(INVENTORY_TRAN.ITTRANDATE) = INVENTORY_TRAN.ITTRANDATE
) AS [sub_INVENTORY_TRAN] ON [INVENTORY_BIN].[INVBTICKETNO] = [sub_INVENTORY_TRAN].[ITTICKETNO]

You also need to replace the selected columns with the new added through the sub select:

   ,[sub_INVENTORY_TRAN].[Source]
   ,[sub_INVENTORY_TRAN].[Comment]
   ,[sub_INVENTORY_TRAN].[Trans Date]


问:
Sendgrid's links produce a can't establish a secure connection
We are using for few months now sendgrid's click tracking feature and since this morning some of our customers could not be redirected to our platform through Sendgrid generated links.

They have the error :

```<code>Safari can't establish a secure connection to the server "u6012831.ct.sendgrid.net"
</code>```

I cannot reproduce it on my side.

any ideas were it could come from and how to fix that permanently?

答:
We have the same problem. From our side when we test our newsletter (not made with a template from SendGrid but from our own cms / newsletter) we cannot reproduce the problem - besides of these facts:
-Thunderbird / Mac shows an similar info, but there you can click 'send it through SendGrid anyway' and it opens the link correctly
-Outlook / Windows - there when you allow downloading all the images, then it works too
-the link should be implemented into text, not shown as simple url. Implemented into text also Thunderbird of Mac works without any popup information.

On all other mail programs (on Mac, Windows, Android) from our side, it works fine. But some of our customers tells, that no link works on Windows / Outlook or Windows / Thunderbird or Android

Very strange!!
And the most annoying problem is that the support of SendGrid very often is absolutely not helpful. Some month go we contacted them and the solution (after waiting at least 2 Weeks of response!): you always can send it not via SendGrid. That may help. Thank you SendGrid!!

Body:
We are using for few months now sendgrid's click tracking feature and since this morning some of our customers could not be redirected to our platform through Sendgrid generated links.

They have the error :

Safari can't establish a secure connection to the server "u6012831.ct.sendgrid.net"

I cannot reproduce it on my side.

any ideas were it could come from and how to fix that permanently?


问:
Get Percentages of Tables with Group by
I am working on a prediction game for a local league.

A Match is defined by its SPIELTAG (playday) and its MATCH_NR.
A prediction has a Match and a result (ERGA, ERGB)

I have a Table like in this fiddle https://www.db-fiddle.com/f/o4NXPFfzod39LpMaTzqz3r/0

I got the output to count each result per gameday and per match.

```<code>| SPIELTAG | MATCH_NR | ERGA | ERGB | AMOUNT |
| -------- | -------- | ---- | ---- | ------ |
| 4        | 1        | 7    | 1    | 1      |
| 4        | 1        | 7    | 2    | 2      |
| 4        | 1        | 7    | 3    | 5      |
| 4        | 1        | 7    | 4    | 1      |
| 4        | 2        | 1    | 7    | 1      |
| 4        | 2        | 2    | 7    | 6      |
| 4        | 2        | 3    | 7    | 3      |
</code>```

What i am trying to achieve is, next to the amount column something like

```<code>| SPIELTAG | MATCH_NR | ERGA | ERGB | AMOUNT | PERC |
| -------- | -------- | ---- | ---- | ------ | ---- |
| 4        | 1        | 7    | 1    | 1      | 11.1%| => 1 / 9
| 4        | 1        | 7    | 2    | 2      | 22.2%| => 2 / 9
| 4        | 1        | 7    | 3    | 5      | 55.5%| => 5 / 9
| 4        | 1        | 7    | 4    | 1      | 11.1%| => 1 / 9
| 4        | 2        | 1    | 7    | 1      | 11.1%| => 1 / 9
| 4        | 2        | 2    | 7    | 5      | 55.5%| => 5 / 9
| 4        | 2        | 3    | 7    | 3      | 33.3%| => 3 / 9
</code>```

Where PERC is the percentage of picks per playday SPIELTAG. Basically how often is the Result, the tuple of (ERGA, ERGB) predicted for each match SPIELTAG, MATCH_NR.

I found a post where i can get the percentage over all picks but not restricted  on the gameday,match tuple.

An Example:
Match 1 (Spieltag 4, Match 1) has 9 Predictions.

1x:  7-1

2x: 7-2

5x: 7-3

1x: 7-4

__

9x -> ALL_COUNTS_PER_MATCH

So PERC should be something like 'AMOUNT' / ALL_COUNTS_PER_MATCH.

答:
I think you need another group by:

```<code>SELECT `t`.`SPIELTAG` AS `SPIELTAG`,
       `t`.`MATCH_NR` AS `MATCH_NR`,
       `t`.`TEAM_A`   AS `ERGA`,
       `t`.`TEAM_B`   AS `ERGB`,
       count(0)       AS `AMOUNT`,
       COUNT(0) / MAX(A.TOTAL_AMOUNT) -- MIN would also work
FROM `TIPPSPIEL_TIPP` `t`
         JOIN (
    -- Calculate the row count by each different spieltag & match_nr combination
    SELECT `t`.`SPIELTAG`,
           `t`.`MATCH_NR`,
           count(0) AS `TOTAL_AMOUNT`
    FROM `TIPPSPIEL_TIPP` `t`
    GROUP BY `t`.`SPIELTAG`, `t`.`MATCH_NR`
) A USING (SPIELTAG, MATCH_NR)
GROUP BY `t`.`SPIELTAG`, `t`.`MATCH_NR`, `t`.`TEAM_A`, `t`.`TEAM_B`
;
</code>```

https://www.db-fiddle.com/f/o4NXPFfzod39LpMaTzqz3r/3

Title: Get Percentages of Tables with Group by

Body:
I am working on a prediction game for a local league.

A Match is defined by its SPIELTAG (playday) and its MATCH_NR.
A prediction has a Match and a result (ERGA, ERGB)

I have a Table like in this fiddle https://www.db-fiddle.com/f/o4NXPFfzod39LpMaTzqz3r/0

I got the output to count each result per gameday and per match.

| SPIELTAG | MATCH_NR | ERGA | ERGB | AMOUNT |
| -------- | -------- | ---- | ---- | ------ |
| 4        | 1        | 7    | 1    | 1      |
| 4        | 1        | 7    | 2    | 2      |
| 4        | 1        | 7    | 3    | 5      |
| 4        | 1        | 7    | 4    | 1      |
| 4        | 2        | 1    | 7    | 1      |
| 4        | 2        | 2    | 7    | 6      |
| 4        | 2        | 3    | 7    | 3      |

What i am trying to achieve is, next to the amount column something like

| SPIELTAG | MATCH_NR | ERGA | ERGB | AMOUNT | PERC |
| -------- | -------- | ---- | ---- | ------ | ---- |
| 4        | 1        | 7    | 1    | 1      | 11.1%| => 1 / 9
| 4        | 1        | 7    | 2    | 2      | 22.2%| => 2 / 9
| 4        | 1        | 7    | 3    | 5      | 55.5%| => 5 / 9
| 4        | 1        | 7    | 4    | 1      | 11.1%| => 1 / 9
| 4        | 2        | 1    | 7    | 1      | 11.1%| => 1 / 9
| 4        | 2        | 2    | 7    | 5      | 55.5%| => 5 / 9
| 4        | 2        | 3    | 7    | 3      | 33.3%| => 3 / 9

Where PERC is the percentage of picks per playday SPIELTAG. Basically how often is the Result, the tuple of (ERGA, ERGB) predicted for each match SPIELTAG, MATCH_NR.

I found a post where i can get the percentage over all picks but not restricted  on the gameday,match tuple.

An Example:
Match 1 (Spieltag 4, Match 1) has 9 Predictions.

1x:  7-1

2x: 7-2

5x: 7-3

1x: 7-4

__

9x -> ALL_COUNTS_PER_MATCH

So PERC should be something like 'AMOUNT' / ALL_COUNTS_PER_MATCH.

Body:
I think you need another group by:

SELECT `t`.`SPIELTAG` AS `SPIELTAG`,
       `t`.`MATCH_NR` AS `MATCH_NR`,
       `t`.`TEAM_A`   AS `ERGA`,
       `t`.`TEAM_B`   AS `ERGB`,
       count(0)       AS `AMOUNT`,
       COUNT(0) / MAX(A.TOTAL_AMOUNT) -- MIN would also work
FROM `TIPPSPIEL_TIPP` `t`
         JOIN (
    -- Calculate the row count by each different spieltag & match_nr combination
    SELECT `t`.`SPIELTAG`,
           `t`.`MATCH_NR`,
           count(0) AS `TOTAL_AMOUNT`
    FROM `TIPPSPIEL_TIPP` `t`
    GROUP BY `t`.`SPIELTAG`, `t`.`MATCH_NR`
) A USING (SPIELTAG, MATCH_NR)
GROUP BY `t`.`SPIELTAG`, `t`.`MATCH_NR`, `t`.`TEAM_A`, `t`.`TEAM_B`
;

https://www.db-fiddle.com/f/o4NXPFfzod39LpMaTzqz3r/3


问:
Trying to play with the annotation and bubble callout on mkmapview
I am developing an application in iphone which deals with maps. I have many annotations. I need different images to be loaded in the callout bubble.It mean user can edit the callout it may be image and He also type text on callout bubble .How can I give give multiple action on the callout bubble .<br>
And most important think is that this annotation must drop on the map after clicking the save button. For Example I have two class (mapview And photoview),And in photoView i have three button (chooshphoto,takephoto,usephoto)when user take photo or browse for photo and he want use this photo.When he click on usephoto button the annotation must drop after that.And display onthe mapView. </p>

答:
The second half of your question isn't very clear but I'll try and answer the first.

The only real customisation you can apply to the callout view for an MKAnnotation is to set the Title, subtitle labels and the left/right calloutAccessoryViews. You can set the latter to images or callOutAccessoryViewIndicators, or another UIView but it can't be taller than 32 pixels.
MKAnnontationView documentation

That's really about it I'm afraid. For anything more advanced than that, you'll have to create a custom implementation. This blog post should be helpful, I plan on building something similar myself.

MKPinAnnontationView can be set to drop on the map as you describe so as long as you're happy with the Pin image for the annontation view itself, you can simply set it's animatesDrop property to YES and it will animate onto the map when it's added.

MKPinAnnontationView documentation

EDIT: I think this is what you want;-

In your mapView controller, define a property to hold the object you want to animate.

```<code>@interface MyMapViewController {

    Photo *photoToAnimate;

}
@property (nonatomic, retain) Photo *photoToAnimate;

@end
</code>```

Then in your implementation file, add the following to ViewDidAppear

```<code>-(void)ViewDidAppear {
     ...
     if (photoToAnimate) {
         [mapView addAnnotation:photoToAnimate];
         self.photoToAnimate = nil; // reset it for the next time
     }
     ...
 }
</code>```

Then in your PhotoViewController, simply set the property on the button press

```<code>-(void)usePhotoAction {
    ...
    mapViewController.photoToAnimate = photo;
    ...
 }
</code>```

At least that's the really simple hacky way of what I was trying to describe in the comments. ViewDidAppear will fire when the MapView re-appears and it will add the pin to itself accordingly. If you need to add more than one pin, use an array to store them and iterate through the array.

There might be better patterns for this but in short, your MapView needs to get hold of the object you want to drop somehow and then not actually do anything with it until ViewDidAppear is called.

Body:
I am developing an application in iphone which deals with maps. I have many annotations. I need different images to be loaded in the callout bubble.It mean user can edit the callout it may be image and He also type text on callout bubble .How can I give give multiple action on the callout bubble .

And most important think is that this annotation must drop on the map after clicking the save button. For Example I have two class (mapview And photoview),And in photoView i have three button (chooshphoto,takephoto,usephoto)when user take photo or browse for photo and he want use this photo.When he click on usephoto button the annotation must drop after that.And display onthe mapView.

Body:
The second half of your question isn't very clear but I'll try and answer the first.

The only real customisation you can apply to the callout view for an MKAnnotation is to set the Title, subtitle labels and the left/right calloutAccessoryViews. You can set the latter to images or callOutAccessoryViewIndicators, or another UIView but it can't be taller than 32 pixels.
MKAnnontationView documentation

That's really about it I'm afraid. For anything more advanced than that, you'll have to create a custom implementation. This blog post should be helpful, I plan on building something similar myself.

MKPinAnnontationView can be set to drop on the map as you describe so as long as you're happy with the Pin image for the annontation view itself, you can simply set it's animatesDrop property to YES and it will animate onto the map when it's added.

MKPinAnnontationView documentation

EDIT: I think this is what you want;-

In your mapView controller, define a property to hold the object you want to animate.

@interface MyMapViewController {

    Photo *photoToAnimate;

}
@property (nonatomic, retain) Photo *photoToAnimate;

@end

Then in your implementation file, add the following to ViewDidAppear

-(void)ViewDidAppear {
     ...
     if (photoToAnimate) {
         [mapView addAnnotation:photoToAnimate];
         self.photoToAnimate = nil; // reset it for the next time
     }
     ...
 }

Then in your PhotoViewController, simply set the property on the button press

-(void)usePhotoAction {
    ...
    mapViewController.photoToAnimate = photo;
    ...
 }

At least that's the really simple hacky way of what I was trying to describe in the comments. ViewDidAppear will fire when the MapView re-appears and it will add the pin to itself accordingly. If you need to add more than one pin, use an array to store them and iterate through the array.

There might be better patterns for this but in short, your MapView needs to get hold of the object you want to drop somehow and then not actually do anything with it until ViewDidAppear is called.


问:
How to fix this code? It does not scale my images
I have this piece of code. It doesn't scale my images to this size.
Height and width doesn't work. Why?

in style.css i have this line:

```<code>.gallery-popup .image-container img{width: 100%; height: auto; display: block;}

<div class="trace">
                  <img src="img/content/Imagesall/13347.jpg" height="250" width="250" alt="" />
                        <div class="tagline">
                            <div class="content">
                                <div class="title">TITLE</div>
                                <div class="description">TEXT</div>
                            </div>
                        </div>
                    </div>

<div class="overflow">
                <div class="swiper-container" data-autoplay="0" data-loop="1" data-speed="500" data-center="0" data-slides-per-view="1">
                    <div class="swiper-w">
                        <div class="swiper-s">
                            <div class="image-container">
                                <img src="img/content/Imagesall/13347.jpg" height="250" width="250" alt="" />
                                <div class="description">
                                    <div class="title">titletext</div>
                                    <div class="text">texttexttext.</div>
                                </div>
                            </div>
                        </div>
</code>```

答:
Without any css to look in is this the responsive css for  images. Give the img a width and set the height to auto. You do not have to use the height and width in the html, use the css to give a width only

```<code><div class="trace">
  <img src="img/content/Imagesall/13347.jpg" alt="" />

.trace img {
  width: ...;  /* use for example px or % */
  max-width: 100%;
  height: auto; /* this line to preserve width:height ratio */
  border: 0; /* remove default border of img */
}
</code>```

Body:
I have this piece of code. It doesn't scale my images to this size.
Height and width doesn't work. Why?

in style.css i have this line:

.gallery-popup .image-container img{width: 100%; height: auto; display: block;}

TITLE

TEXT

titletext

texttexttext.

Body:
Without any css to look in is this the responsive css for <img> images. Give the img a width and set the height to auto. You do not have to use the height and width in the html, use the css to give a width only

<div class="trace">
  <img src="img/content/Imagesall/13347.jpg" alt="" />

.trace img {
  width: ...;  /* use for example px or % */
  max-width: 100%;
  height: auto; /* this line to preserve width:height ratio */
  border: 0; /* remove default border of img */
}


问:
Linking two (or more) UISegmented Controls
I'm trying to get the answer from my first segmented control to then automatically select the answer to the second (and more) segmented controls, if the selected answer is No.

So Question1 segmented control (Yes, No, N/A), if No is selected, then make answer to Question2 (and Q3,Q4 etc) segmented control to N/A.
I can get it to work on Question1 alone, ie press No but changes to N/A on Question1, but I want it to leave Question1 as No, but then change Question2 etc to N/A.

I tried changing sender to Question2, but that doesn't work.

```<code>        @IBOutlet weak var Queston2: UISegmentedControl! //Will need to add same for Q3 etc

        @IBAction func Question1(_ sender: UISegmentedControl) {

            if sender.selectedSegmentIndex == 0 {
            //Do stuff
            }

            else if sender.selectedSegmentIndex == 1 {

                sender.selectedSegmentIndex = 2                  // Change button to 'N/A', works for this question, but i want it to change Question2, not Question1.

         @IBAction func Question2(_ sender: UISegmentedControl) { // generally repeats as Question1 above.
</code>```

I've found a few similar answers, but they seem far more complicated than I think I need.

答:
This is basically what you could do:

```<code>class ArrayOfSegsViewController: UIViewController {

    @IBOutlet var q1SegControl: UISegmentedControl!
    @IBOutlet var q2SegControl: UISegmentedControl!
    @IBOutlet var q3SegControl: UISegmentedControl!
    @IBOutlet var q4SegControl: UISegmentedControl!
    @IBOutlet var q5SegControl: UISegmentedControl!

    @IBAction func q1SegControlChangeed(_ sender: UISegmentedControl) {

        if sender.selectedSegmentIndex == 0 {
            // do stuff
        } else if sender.selectedSegmentIndex == 1 {
            // set all others to "N/A"
            [q2SegControl, q3SegControl, q4SegControl, q5SegControl].forEach {
                $0.selectedSegmentIndex = 2
            }
        } else {
            // do stuff
        }

    }

}
</code>```

In the == 1 block, you create an array of the other segmented controls and loop through, saying "for each control, set the selected segment index to 2."

Side notes: use

```<code>lowerCaseFirstChar
</code>```

for variables and function names. Use

```<code>UpperCaseFirstChar
</code>```

for classes / structs / enums / etc.

Body:
I'm trying to get the answer from my first segmented control to then automatically select the answer to the second (and more) segmented controls, if the selected answer is No.

So Question1 segmented control (Yes, No, N/A), if No is selected, then make answer to Question2 (and Q3,Q4 etc) segmented control to N/A.
I can get it to work on Question1 alone, ie press No but changes to N/A on Question1, but I want it to leave Question1 as No, but then change Question2 etc to N/A.

I tried changing sender to Question2, but that doesn't work.

        @IBOutlet weak var Queston2: UISegmentedControl! //Will need to add same for Q3 etc

        @IBAction func Question1(_ sender: UISegmentedControl) {

            if sender.selectedSegmentIndex == 0 {
            //Do stuff
            }

            else if sender.selectedSegmentIndex == 1 {

                sender.selectedSegmentIndex = 2                  // Change button to 'N/A', works for this question, but i want it to change Question2, not Question1.

         @IBAction func Question2(_ sender: UISegmentedControl) { // generally repeats as Question1 above.

I've found a few similar answers, but they seem far more complicated than I think I need.

Body:
This is basically what you could do:

class ArrayOfSegsViewController: UIViewController {

    @IBOutlet var q1SegControl: UISegmentedControl!
    @IBOutlet var q2SegControl: UISegmentedControl!
    @IBOutlet var q3SegControl: UISegmentedControl!
    @IBOutlet var q4SegControl: UISegmentedControl!
    @IBOutlet var q5SegControl: UISegmentedControl!

    @IBAction func q1SegControlChangeed(_ sender: UISegmentedControl) {

        if sender.selectedSegmentIndex == 0 {
            // do stuff
        } else if sender.selectedSegmentIndex == 1 {
            // set all others to "N/A"
            [q2SegControl, q3SegControl, q4SegControl, q5SegControl].forEach {
                $0.selectedSegmentIndex = 2
            }
        } else {
            // do stuff
        }

    }

}

In the == 1 block, you create an array of the other segmented controls and loop through, saying "for each control, set the selected segment index to 2."

Side notes: use

lowerCaseFirstChar

for variables and function names. Use

UpperCaseFirstChar

for classes / structs / enums / etc.


问:
jQuery code - IE8 problem
I have this code that changes input fields name attribute value, works great in all major browsers except IE8, IE7 and IE6. For IE the name just stay name="participant_name[{i}]", should be name="participant_name[1]".

```<code>var i = 1;
var input_name = null;
$('.dubl input').each(function () {
   var new_input_name = $(this).attr('name').substring(0, $(this).attr('name').indexOf('['));
   if (input_name !== new_input_name) {
       input_name = new_input_name;
       i = 1;
   }
   $(this).attr('name', input_name + '[' + i + ']');
   i++;
});
</code>```

HTML

```<code><input type="text" name="participant_name[{i}]">
</code>```

答: If this is not the only place in your project where you need to do such replacements on the client, maybe it's worth looking at a templating library, e.g., jQuery Templates. </p>

Title: jQuery code - IE8 problem

Body:
I have this code that changes input fields name attribute value, works great in all major browsers except IE8, IE7 and IE6. For IE the name just stay name="participant_name[{i}]", should be name="participant_name[1]".

var i = 1;
var input_name = null;
$('.dubl input').each(function () {
   var new_input_name = $(this).attr('name').substring(0, $(this).attr('name').indexOf('['));
   if (input_name !== new_input_name) {
       input_name = new_input_name;
       i = 1;
   }
   $(this).attr('name', input_name + '[' + i + ']');
   i++;
});

HTML

<input type="text" name="participant_name[{i}]">


问:
SSL3_READ_BYTES:tlsv1 alert internal error, secure sockets, OpenSSL, C++, getting HTTPS page
I want to write a simple application, which grabs the content of the HTTPS page: https://httpbin.org/html.

I know how to access its insecure (HTTP) version (http://httpbin.org/html), I just need to send a request using sockets:

```<code>std::stringstream ss;
ss << "GET /html HTTP/1.1" << "\r\n"
<< "Host: httpbin.org\r\n"
<< "Connection: close"
<< "\r\n\r\n";
std::string request = ss.str();

// socket creation, connect

send(sock, request.c_str(), request.size(), 0);
</code>```

And it works. However, when using secure sockets (#include <openssl/ssl.h>) I got the following error: error:14094438:SSL routines:SSL3_READ_BYTES:tlsv1 alert internal error when trying result = SSL_connect(ssl);

Here's the code:

```<code>#include <sys/stat.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <string>
#include <iostream>
#include <sstream>

int main(int argc, char **argv)
{
    int    sock;
    char   buff[1024];

    struct sockaddr_in  address;
    struct hostent     *host = NULL;

    std::string servername = "httpbin.org";

    if (!inet_aton(servername.c_str(), &address.sin_addr))
        if (host = gethostbyname(servername.c_str()))
            address.sin_addr = *(struct in_addr*)host->h_addr;
        else
            return -1;

    address.sin_port   = htons(443);
    address.sin_family = AF_INET;

    std::stringstream ss;
    ss << "GET /html HTTP/1.1" << "\r\n"
    << "Host: httpbin.org\r\n"
    << "Connection: close"
    << "\r\n\r\n";
    std::string request = ss.str();

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) != -1)
    {
        if (connect(sock, (struct sockaddr *)&address, sizeof(struct sockaddr_in)) != -1)
        {
            SSL_library_init();
            OpenSSL_add_all_algorithms();
            SSL_load_error_strings();
            SSL_CTX *ctx = SSL_CTX_new(TLSv1_2_method());
            if (!ctx)
                return -1;

            int result = -1;
            SSL *ssl = SSL_new(ctx);
            SSL_set_fd(ssl, sock);
            result = SSL_connect(ssl);

            if (result == 0)
            {
                long error = ERR_get_error();
                const char* error_str = ERR_error_string(error, NULL);
                printf("%s\n", error_str);
                return 0;
            }

            SSL_write(ssl, request.c_str(), request.size());
            SSL_read(ssl, buff, 1024);
            printf("%s\n", buff);
            memset(buff, 0, 1024);

            SSL_free(ssl);
            SSL_CTX_free(ctx);
            close(sock);
        }
    }

    return 0;
}
</code>```

答:
This error is generated for a handshake failure, which is caused by a miss-match between what the client offers and what the server accepts.

For some situations, openssl will do a pretty good job of negotiating a working set between the client and server. For other situations, it's a hard failure and you will need to ammend your code. I have seen this error generated due to:

Protocol and cipher missmatch

```<code>SSL_set_min_proto_version()
SSL_set_max_proto_version()
SSL_set_cipher_list()
</code>```

SNI required by the server but not offered by the client

```<code>SSL_set_tlsext_host_name()
</code>```

Reused session offered by client but sessions not implemented on server

```<code>SSL_set_session()
</code>```

Body:
I want to write a simple application, which grabs the content of the HTTPS page: https://httpbin.org/html.

I know how to access its insecure (HTTP) version (http://httpbin.org/html), I just need to send a request using sockets:

std::stringstream ss;
ss << "GET /html HTTP/1.1" << "\r\n"
<< "Host: httpbin.org\r\n"
<< "Connection: close"
<< "\r\n\r\n";
std::string request = ss.str();

// socket creation, connect

send(sock, request.c_str(), request.size(), 0);

And it works. However, when using secure sockets (#include <openssl/ssl.h>) I got the following error: error:14094438:SSL routines:SSL3_READ_BYTES:tlsv1 alert internal error when trying result = SSL_connect(ssl);

Here's the code:

#include <sys/stat.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <string>
#include <iostream>
#include <sstream>

int main(int argc, char **argv)
{
    int    sock;
    char   buff[1024];

    struct sockaddr_in  address;
    struct hostent     *host = NULL;

    std::string servername = "httpbin.org";

    if (!inet_aton(servername.c_str(), &address.sin_addr))
        if (host = gethostbyname(servername.c_str()))
            address.sin_addr = *(struct in_addr*)host->h_addr;
        else
            return -1;

    address.sin_port   = htons(443);
    address.sin_family = AF_INET;

    std::stringstream ss;
    ss << "GET /html HTTP/1.1" << "\r\n"
    << "Host: httpbin.org\r\n"
    << "Connection: close"
    << "\r\n\r\n";
    std::string request = ss.str();

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) != -1)
    {
        if (connect(sock, (struct sockaddr *)&address, sizeof(struct sockaddr_in)) != -1)
        {
            SSL_library_init();
            OpenSSL_add_all_algorithms();
            SSL_load_error_strings();
            SSL_CTX *ctx = SSL_CTX_new(TLSv1_2_method());
            if (!ctx)
                return -1;

            int result = -1;
            SSL *ssl = SSL_new(ctx);
            SSL_set_fd(ssl, sock);
            result = SSL_connect(ssl);

            if (result == 0)
            {
                long error = ERR_get_error();
                const char* error_str = ERR_error_string(error, NULL);
                printf("%s\n", error_str);
                return 0;
            }

            SSL_write(ssl, request.c_str(), request.size());
            SSL_read(ssl, buff, 1024);
            printf("%s\n", buff);
            memset(buff, 0, 1024);

            SSL_free(ssl);
            SSL_CTX_free(ctx);
            close(sock);
        }
    }

    return 0;
}

Body:
This error is generated for a handshake failure, which is caused by a miss-match between what the client offers and what the server accepts.

For some situations, openssl will do a pretty good job of negotiating a working set between the client and server. For other situations, it's a hard failure and you will need to ammend your code. I have seen this error generated due to:

Protocol and cipher missmatch

SSL_set_min_proto_version()
SSL_set_max_proto_version()
SSL_set_cipher_list()

SNI required by the server but not offered by the client

SSL_set_tlsext_host_name()

Reused session offered by client but sessions not implemented on server

SSL_set_session()


问:
Flutter, dart index
I have an index value in my project, but when I run the application, the index value starts at 0. I want it to start as 1, what should I do?</p>

```<code>tabBuilder: (BuildContext context, int index) {
return CupertinoTabView(
builder: (BuildContext context){
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Page 1 of tab $index'),
backgroundColor: Colors.blue,
),
</code>```

答:
Array starts at 0 in dart.
if you want your UI to display 1 at first position or add 1 to every position then you can use index+1

```<code>tabBuilder: (BuildContext context, int index) {
return CupertinoTabView(
builder: (BuildContext context){
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Page 1 of tab ${index+1}'), // add +1 to your index here
backgroundColor: Colors.blue,
),
</code>```

Title: Flutter, dart index

Body:
I have an index value in my project, but when I run the application, the index value starts at 0. I want it to start as 1, what should I do?

tabBuilder: (BuildContext context, int index) {
return CupertinoTabView(
builder: (BuildContext context){
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Page 1 of tab $index'),
backgroundColor: Colors.blue,
),

Body:
Array starts at 0 in dart.
if you want your UI to display 1 at first position or add 1 to every position then you can use index+1

tabBuilder: (BuildContext context, int index) {
return CupertinoTabView(
builder: (BuildContext context){
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Page 1 of tab ${index+1}'), // add +1 to your index here
backgroundColor: Colors.blue,
),


问:
HttpContext.Current not recognized by Visual Studio [ ASP.NET MVC ]
I'm working on an ASP.NET MVC project, exactly on a void method in a Controller, and I need to use HttpContext.Current.Request.Cookies but Visual Studio recognized Current as an error, and not shown ( Current ) in the Intilisense.

This is my method :

```<code>public void User_Access_Validation()
{

            var T_8 = HttpContext.Current.Request.Cookies["T_8"];
            var T_5 = HttpContext.Current.Request.Cookies["T_5"];
            var T_T = HttpContext.Current.Request.Cookies["T_T"];

            HttpContext.Current.Request.Cookie

            if (T_8 == null || T_5 == null || T_T == null)
            {
                response.Redirect("/Login");
            }
}
</code>```

So please any help ?

答: As vivek nuna Mentioned in his answer, you need to use System.Web.HttpContext.Current.Cookies["xxx"] when you need to work with Current in your case.

Body:
I'm working on an ASP.NET MVC project, exactly on a void method in a Controller, and I need to use HttpContext.Current.Request.Cookies but Visual Studio recognized Current as an error, and not shown ( Current ) in the Intilisense.

This is my method :

public void User_Access_Validation()
{

            var T_8 = HttpContext.Current.Request.Cookies["T_8"];
            var T_5 = HttpContext.Current.Request.Cookies["T_5"];
            var T_T = HttpContext.Current.Request.Cookies["T_T"];

            HttpContext.Current.Request.Cookie

            if (T_8 == null || T_5 == null || T_T == null)
            {
                response.Redirect("/Login");
            }
}

So please any help ?


问:
Make Special Characters Appear Bold
I have text that contains non-alphanumeric characters that I want to appear as bold.

```<code><span style="font-weight:bold">+/-</span>
</code>```

However, I guess because of the simplicity of the characters making them bold does not really do anything as they look the same as the adjacent non-bold characters. I'm using the default font so is it possible the font does not have a bold representation for non-alphanumerics? How can I get these characters to appear as bold? TIA.

答:
You could use the  tag. Something like that.

```<code><b>+/-</b>
</code>```

It may solve the problem.

Title: Make Special Characters Appear Bold

Body:
I have text that contains non-alphanumeric characters that I want to appear as bold.

+/-

However, I guess because of the simplicity of the characters making them bold does not really do anything as they look the same as the adjacent non-bold characters. I'm using the default font so is it possible the font does not have a bold representation for non-alphanumerics? How can I get these characters to appear as bold? TIA.

Body:
You could use the <b> tag. Something like that.

<b>+/-</b>

It may solve the problem.


问:
Limiting PHP's file access according to logged-in user's access permissions
I have a PHP web application (running on Apache/Linux) that, among other things, allows some browsing of local files on the web server. Since Apache is running as a special "www" user, PHP has access to everything that "www" can access, whichever user is logged into the application. </p>

<p>What is the best way to limit the access to files according to the Unix filesystem privileges for the logged-in user? Ideally, I could spawn off a new process with user ID being the logged in user, but I'm not sure if that's possible. Alternatively, is there a standard PHP library somewhere that will do the permission checking and access the files? </p>

答:
I don't get what you mean because the user that access the files is the PHP users, not a generic user that request your page (you are not connecting to your server with SSH)

You may want to implement an ACL on top of your application to manage this rights.

And of course Zend has the solution: http://framework.zend.com/manual/en/zend.acl.html

Body:
I have a PHP web application (running on Apache/Linux) that, among other things, allows some browsing of local files on the web server. Since Apache is running as a special "www" user, PHP has access to everything that "www" can access, whichever user is logged into the application.

What is the best way to limit the access to files according to the Unix filesystem privileges for the logged-in user? Ideally, I could spawn off a new process with user ID being the logged in user, but I'm not sure if that's possible. Alternatively, is there a standard PHP library somewhere that will do the permission checking and access the files?


问:
P5.js how to do 8 directional lerp color/color change?
A last issue i have in this code is that i am not sure how to create color change effect as 8 directional.
I can only map a mouseX to make it lerpColor horizontally or vertically .
But how do i make it work through moving both mouseX and mouseY?

I had it in shift_Color method within the class. I tried to state that within a certain dist(), lerpColor. But now it only showing black color rather than the changing color effect.

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);
  //background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  background(backCol);
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.gap = 110
    this.shift1 = color(96);
    this.shift2 = color(244);
  }

  update() {
    this.shape();
    this.shift_Color();
  }

  shape() {
    push();
    stroke(this.stroke);
    //fill(this.shift1);
    this.shift_Color();
    translate(this.x - width / 2, this.y - height / 2, 0);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.shift1 = color(96);
      this.shift2 = color(244);
      this.shiftX = map(mouseX - width/2,this.gap,distance,0,1.0);
      this.change = lerpColor(this.shift1, this.shift2, this.shiftX);
      fill(this.change);
    } else {
      fill(this.shift1);
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.attract = atan2(mouseY - this.y, mouseX - this.x);
      rotateX(this.attract);
      rotateY(this.attract);
    } else {
      rotateX(millis() / 1000);
      rotateY(millis() / 1000);
    }
  }
}```

答:
If I understood your question properly, there are two problems in your code.

The first is the fact that because you are trying to map the distance between mouse and the cube to number between 0 and 1, you should write lerpColor(this.shift2, this.shift1, this.shiftX) instead of lerpColor(this.shift1, this.shift2, this.shiftX), since this.shift2 is the lighter color and will be the inner color.

Another problem is when mapping the change variable, change should be calculated based on the distance between mouse and the cube (which is the distance variable), not mouseX or mouseY. Solution is to simply do map(distance, 0, this.gap, 0, 1);.

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  background(backCol);
  noFill();

  for (let cube of cubes) {
    cube.update();
  }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.gap = 110
    this.shift1 = color(96);
    this.shift2 = color(244);
  }

  update() {
    this.shape();
    this.shift_Color();
  }

  shape() {
    push();
    stroke(this.stroke);
    //fill(this.shift1);
    this.shift_Color();
    translate(this.x - width / 2, this.y - height / 2, 0);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.shiftX = map(distance, 0, this.gap, 0, 1);
      // this.shiftX = map(mouseX - width/2,this.gap,distance,0,1.0);
      this.change = lerpColor(this.shift2, this.shift1, this.shiftX);
      // this.change = lerpColor(this.shift1, this.shift2, this.shiftX);
      fill(this.change);
    } else {
      fill(this.shift1);
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.attract = atan2(mouseY - this.y, mouseX - this.x);
      rotateX(this.attract);
      rotateY(this.attract);
    } else {
      rotateX(millis() / 1000);
      rotateY(millis() / 1000);
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script></code>```

I also modified some of your code. Like the line

```<code>this.shift1 = color(96);
this.shift2 = color(244);
</code>```

which is not needed currently since neither of these variable changes during execution.

Body:
If I understood your question properly, there are two problems in your code.

The first is the fact that because you are trying to map the distance between mouse and the cube to number between 0 and 1, you should write lerpColor(this.shift2, this.shift1, this.shiftX) instead of lerpColor(this.shift1, this.shift2, this.shiftX), since this.shift2 is the lighter color and will be the inner color.

Another problem is when mapping the change variable, change should be calculated based on the distance between mouse and the cube (which is the distance variable), not mouseX or mouseY. Solution is to simply do map(distance, 0, this.gap, 0, 1);.

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  background(backCol);
  noFill();

  for (let cube of cubes) {
    cube.update();
  }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.gap = 110
    this.shift1 = color(96);
    this.shift2 = color(244);
  }

  update() {
    this.shape();
    this.shift_Color();
  }

  shape() {
    push();
    stroke(this.stroke);
    //fill(this.shift1);
    this.shift_Color();
    translate(this.x - width / 2, this.y - height / 2, 0);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.shiftX = map(distance, 0, this.gap, 0, 1);
      // this.shiftX = map(mouseX - width/2,this.gap,distance,0,1.0);
      this.change = lerpColor(this.shift2, this.shift1, this.shiftX);
      // this.change = lerpColor(this.shift1, this.shift2, this.shiftX);
      fill(this.change);
    } else {
      fill(this.shift1);
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.gap) {
      this.attract = atan2(mouseY - this.y, mouseX - this.x);
      rotateX(this.attract);
      rotateY(this.attract);
    } else {
      rotateX(millis() / 1000);
      rotateY(millis() / 1000);
    }
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

I also modified some of your code. Like the line

this.shift1 = color(96);
this.shift2 = color(244);

which is not needed currently since neither of these variable changes during execution.


问:
How can I get a value from an observer inside another?
How do I make this line return a value in the subscribe ? It is returning an observable instead:

```<code>let test = undefined;
of(test, this.myService.whatever(var1, var2))
    .pipe(
        first(n=>!!n)
    ).subscribe(result=>console.log(result)); // returns Observable, should return value.
</code>```

myservice.whatever returns an observable. I want to make it resolve inside pipe. Something like this:

```<code>let test = undefined;
of(test, this.myService.whatever(var1, var2))
    .pipe(
        first(n=>!!n),
        getValueFromObserver() // if it's an observer get the value
    ).subscribe(result=>console.log(result));
</code>```

Is this possible ?
What I'm trying to do is check inside the observer's sequence if a local variable has a value and if it doesn't, then get the value from the backend. I want to make this because the real code is far more complex and the result of this observable will be forkJoined with other observers.

答:
haven't fully tested but theoretically, you can check instanceof

```<code>let test = undefined;
of(test, this.myService.whatever(var1, var2))
    .pipe(
        first(n => !!n),
        switchMap(value => value instanceof Observable ? value : of(value))
    ).subscribe(result => console.log(result));
</code>```

Body:
How do I make this line return a value in the subscribe ? It is returning an observable instead:

let test = undefined;
of(test, this.myService.whatever(var1, var2))
    .pipe(
        first(n=>!!n)
    ).subscribe(result=>console.log(result)); // returns Observable, should return value.

myservice.whatever returns an observable. I want to make it resolve inside pipe. Something like this:

let test = undefined;
of(test, this.myService.whatever(var1, var2))
    .pipe(
        first(n=>!!n),
        getValueFromObserver() // if it's an observer get the value
    ).subscribe(result=>console.log(result));

Is this possible ?
What I'm trying to do is check inside the observer's sequence if a local variable has a value and if it doesn't, then get the value from the backend. I want to make this because the real code is far more complex and the result of this observable will be forkJoined with other observers.

Body:
haven't fully tested but theoretically, you can check instanceof

let test = undefined;
of(test, this.myService.whatever(var1, var2))
    .pipe(
        first(n => !!n),
        switchMap(value => value instanceof Observable ? value : of(value))
    ).subscribe(result => console.log(result));


问:
Gcloud Firestore emulators lost the data when restart
I'm using firestore emulator for my python project.

I start it using this command.

gcloud beta emulators firestore start --host-port=localhost:8080

After saving docs and doing other stuff if I close the firestore and run it again it will lose
all data. I want firestore keep data until I clear data myself, is it possible ?

答:
It sounds like you're looking for:

emulators:export to export data from the emulator

the --import flag to pass the exported data to the emulator on startup

Also see the Firestore documentation on exporting and importing emulator data.