问:
Apache Ignite: How do I fix the "Unknown pair" error when using a StreamReceiver?
How do I fix the following serialization error when using a DataStreamer with a StreamReceiver? I am guessing that it is not able to find the class when deserializing the RowStreamReceiver.

Error: SEVERE: Failure in Java callback class org.apache.ignite.IgniteException: Platform error:Apache.Ignite.Core.Binary.BinaryObjectException: Unknown pair [platformId=1, typeId=113114]

I'm using Apache Ignite 2.0, and I am trying to employ the same kind of code demonstrated in this test:
https://github.com/apache/ignite/blob/master/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Dataload/DataStreamerTest.cs#L436

I've tried adding the assembly to the configuration, but that didn't seem to help. config.Assemblies.Add(typeof(RowStreamReceiver).Assembly.FullName);

Here's the relevant code:

DataStreamer:

```<code>using (var ds = m_ignite.GetDataStreamer<string, IBinaryObject>(CacheName)) {
    ds.AllowOverwrite = true;
    ds.Receiver = new RowStreamReceiver(); // If I comment this out, the error goes away
    Parallel.ForEach(rows.Select((r, i) => new KeyValuePair<long, string>(i, r)), r => {
        var pair = BuildRow(r.Key, r.Value);
        ds.AddData(pair);
    });
}
</code>```

StreamReceiver:

```<code>[Serializable]
public class RowStreamReceiver : IStreamReceiver<string, IBinaryObject> {
    public void Receive(ICache<string, IBinaryObject> cache, ICollection<ICacheEntry<string, IBinaryObject>> entries) {
        var bin = cache.Ignite.GetBinary();
        cache.PutAll(entries.ToDictionary(x => x.Key, x => {
            var builder = bin.GetBuilder(x.Value);
            SetColumnFields(builder);
            return builder.Build();
        }));
    }

    private static void SetColumnFields(IBinaryObjectBuilder builder) {
        /* logic to set fields */
    }
}
</code>```

Stack Trace:

```<code>Jul 07, 2017 11:25:22 AM java.util.logging.LogManager$RootLogger log
SEVERE: Failure in Java callback class org.apache.ignite.IgniteException: Platform error:Apache.Ignite.Core.Binary.BinaryObjectException: Unknown pair [platformId=1, typeId=113114] ---> Apache.Ignite.Core.Common.JavaException: class org.apache.ignite.binary.BinaryObjectException: Unknown pair [platformId=1, typeId=113114]
        at org.apache.ignite.internal.processors.platform.binary.PlatformBinaryProcessor.processInStreamOutStream(PlatformBinaryProcessor.java:119)
        at org.apache.ignite.internal.processors.platform.PlatformTargetProxyImpl.inStreamOutStream(PlatformTargetProxyImpl.java:155)
        at org.apache.ignite.internal.processors.platform.callback.PlatformCallbackUtils.inLongLongLongObjectOutLong(Native Method)
        at org.apache.ignite.internal.processors.platform.callback.PlatformCallbackGateway.dataStreamerStreamReceiverInvoke(PlatformCallbackGateway.java:464)
        at org.apache.ignite.internal.processors.platform.datastreamer.PlatformStreamReceiverImpl.receive(PlatformStreamReceiverImpl.java:100)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamerUpdateJob.call(DataStreamerUpdateJob.java:137)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.localUpdate(DataStreamProcessor.java:382)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.processRequest(DataStreamProcessor.java:301)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.access$000(DataStreamProcessor.java:58)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor$1.onMessage(DataStreamProcessor.java:88)
        at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1257)
        at org.apache.ignite.internal.managers.communication.GridIoManager.processRegularMessage0(GridIoManager.java:885)
        at org.apache.ignite.internal.managers.communication.GridIoManager.access$2100(GridIoManager.java:114)
        at org.apache.ignite.internal.managers.communication.GridIoManager$7.run(GridIoManager.java:802)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.ClassNotFoundException: Unknown pair [platformId=1, typeId=113114]
        at org.apache.ignite.internal.MarshallerContextImpl.getClassName(MarshallerContextImpl.java:385)
        at org.apache.ignite.internal.processors.platform.binary.PlatformBinaryProcessor.processInStreamOutStream(PlatformBinaryProcessor.java:113)
        ... 16 more

   --- End of inner exception stack trace ---    at Apache.Ignite.Core.Impl.Unmanaged.UnmanagedCallbacks.Error(Void* target, Int32 errType, SByte* errClsChars, Int32 errClsCharsLen, SByte* errMsgChars, Int32 errMsgCharsLen, SByte* stackTraceChars, Int32 stackTraceCharsLen, Void* errData, Int32 errDataLen)    at Apache.Ignite.Core.Impl.Unmanaged.IgniteJniNativeMethods.TargetInStreamOutStream(Void* ctx, Void* target, Int32 opType, Int64 inMemPtr, Int64 outMemPtr)    at Apache.Ignite.Core.Impl.PlatformTarget.DoOutInOp[TR](Int32 type, Action`1 outAction, Func`2 inAction)    at Apache.Ignite.Core.Impl.Binary.BinaryProcessor.GetType(Int32 id)    at Apache.Ignite.Core.Impl.Binary.Marshaller.GetDescriptor(Boolean userType, Int32 typeId, Boolean requiresType)    at Apache.Ignite.Core.Impl.Binary.BinaryReader.ReadFullObject[T](Int32 pos)    at Apache.Ignite.Core.Impl.Binary.BinaryReader.TryDeserialize[T](T& res)  at Apache.Ignite.Core.Impl.Binary.BinaryReader.Deserialize[T]()    at Apache.Ignite.Core.Impl.Binary.BinaryReader.ReadBinaryObject[T](Boolean do Detach)    at Apache.Ignite.Core.Impl.Binary.BinaryReader.TryDeserialize[T](T& res)  at Apache.Ignite.Core.Impl.Binary.BinaryReader.Deserialize[T]()    at Apache.Ignite.Core.Impl.Datastream.StreamReceiverHolder.InvokeReceiver[TK, TV](IStreamReceiver`2 receiver, Ignite grid, IUnmanagedTarget cache, IBinaryStream stream, Boolean keepBinary)    at Apache.Ignite.Core.Impl.Datastream.StreamReceiverHolder.Receive(Ignite grid, IUnmanagedTarget cache, IBinaryStream stream, Boolean keepBinary)    at Apache.Ignite.Core.Impl.Unmanaged.UnmanagedCallbacks.DataStreamerStreamReceiverInvoke(Int64 memPtr, Int64 unused, Int64 unused1, Void* cache)    at Apache.Ignite.Core.Impl.Unmanaged.UnmanagedCallbacks.InLongLongLongObjectOutLong(Void* target, Int32 type, Int64 val1, Int64 val2, Int64 val3, Void* arg)
        at org.apache.ignite.internal.processors.platform.PlatformProcessorImpl.loggerLog(PlatformProcessorImpl.java:497)
        at org.apache.ignite.internal.processors.platform.callback.PlatformCallbackUtils.inLongLongLongObjectOutLong(Native Method)
        at org.apache.ignite.internal.processors.platform.callback.PlatformCallbackGateway.dataStreamerStreamReceiverInvoke(PlatformCallbackGateway.java:464)
        at org.apache.ignite.internal.processors.platform.datastreamer.PlatformStreamReceiverImpl.receive(PlatformStreamReceiverImpl.java:100)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamerUpdateJob.call(DataStreamerUpdateJob.java:137)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.localUpdate(DataStreamProcessor.java:382)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.processRequest(DataStreamProcessor.java:301)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.access$000(DataStreamProcessor.java:58)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor$1.onMessage(DataStreamProcessor.java:88)
        at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1257)
        at org.apache.ignite.internal.managers.communication.GridIoManager.processRegularMessage0(GridIoManager.java:885)
        at org.apache.ignite.internal.managers.communication.GridIoManager.access$2100(GridIoManager.java:114)
        at org.apache.ignite.internal.managers.communication.GridIoManager$7.run(GridIoManager.java:802)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:748)
</code>```

答:
typeId=113114 is for Row class name. Looks like somewhere in RowStreamReceiver you try to deserialize such an object, but a class can't be found.

Can you attach the debugger to the server node and see where the exception is thrown?

Body:
How do I fix the following serialization error when using a DataStreamer with a StreamReceiver? I am guessing that it is not able to find the class when deserializing the RowStreamReceiver.

Error: SEVERE: Failure in Java callback class org.apache.ignite.IgniteException: Platform error:Apache.Ignite.Core.Binary.BinaryObjectException: Unknown pair [platformId=1, typeId=113114]

I'm using Apache Ignite 2.0, and I am trying to employ the same kind of code demonstrated in this test:
https://github.com/apache/ignite/blob/master/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Dataload/DataStreamerTest.cs#L436

I've tried adding the assembly to the configuration, but that didn't seem to help. config.Assemblies.Add(typeof(RowStreamReceiver).Assembly.FullName);

Here's the relevant code:

DataStreamer:

using (var ds = m_ignite.GetDataStreamer<string, IBinaryObject>(CacheName)) {
    ds.AllowOverwrite = true;
    ds.Receiver = new RowStreamReceiver(); // If I comment this out, the error goes away
    Parallel.ForEach(rows.Select((r, i) => new KeyValuePair<long, string>(i, r)), r => {
        var pair = BuildRow(r.Key, r.Value);
        ds.AddData(pair);
    });
}

StreamReceiver:

[Serializable]
public class RowStreamReceiver : IStreamReceiver<string, IBinaryObject> {
    public void Receive(ICache<string, IBinaryObject> cache, ICollection<ICacheEntry<string, IBinaryObject>> entries) {
        var bin = cache.Ignite.GetBinary();
        cache.PutAll(entries.ToDictionary(x => x.Key, x => {
            var builder = bin.GetBuilder(x.Value);
            SetColumnFields(builder);
            return builder.Build();
        }));
    }

    private static void SetColumnFields(IBinaryObjectBuilder builder) {
        /* logic to set fields */
    }
}

Stack Trace:

Jul 07, 2017 11:25:22 AM java.util.logging.LogManager$RootLogger log
SEVERE: Failure in Java callback class org.apache.ignite.IgniteException: Platform error:Apache.Ignite.Core.Binary.BinaryObjectException: Unknown pair [platformId=1, typeId=113114] ---> Apache.Ignite.Core.Common.JavaException: class org.apache.ignite.binary.BinaryObjectException: Unknown pair [platformId=1, typeId=113114]
        at org.apache.ignite.internal.processors.platform.binary.PlatformBinaryProcessor.processInStreamOutStream(PlatformBinaryProcessor.java:119)
        at org.apache.ignite.internal.processors.platform.PlatformTargetProxyImpl.inStreamOutStream(PlatformTargetProxyImpl.java:155)
        at org.apache.ignite.internal.processors.platform.callback.PlatformCallbackUtils.inLongLongLongObjectOutLong(Native Method)
        at org.apache.ignite.internal.processors.platform.callback.PlatformCallbackGateway.dataStreamerStreamReceiverInvoke(PlatformCallbackGateway.java:464)
        at org.apache.ignite.internal.processors.platform.datastreamer.PlatformStreamReceiverImpl.receive(PlatformStreamReceiverImpl.java:100)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamerUpdateJob.call(DataStreamerUpdateJob.java:137)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.localUpdate(DataStreamProcessor.java:382)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.processRequest(DataStreamProcessor.java:301)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.access$000(DataStreamProcessor.java:58)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor$1.onMessage(DataStreamProcessor.java:88)
        at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1257)
        at org.apache.ignite.internal.managers.communication.GridIoManager.processRegularMessage0(GridIoManager.java:885)
        at org.apache.ignite.internal.managers.communication.GridIoManager.access$2100(GridIoManager.java:114)
        at org.apache.ignite.internal.managers.communication.GridIoManager$7.run(GridIoManager.java:802)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.ClassNotFoundException: Unknown pair [platformId=1, typeId=113114]
        at org.apache.ignite.internal.MarshallerContextImpl.getClassName(MarshallerContextImpl.java:385)
        at org.apache.ignite.internal.processors.platform.binary.PlatformBinaryProcessor.processInStreamOutStream(PlatformBinaryProcessor.java:113)
        ... 16 more

   --- End of inner exception stack trace ---    at Apache.Ignite.Core.Impl.Unmanaged.UnmanagedCallbacks.Error(Void* target, Int32 errType, SByte* errClsChars, Int32 errClsCharsLen, SByte* errMsgChars, Int32 errMsgCharsLen, SByte* stackTraceChars, Int32 stackTraceCharsLen, Void* errData, Int32 errDataLen)    at Apache.Ignite.Core.Impl.Unmanaged.IgniteJniNativeMethods.TargetInStreamOutStream(Void* ctx, Void* target, Int32 opType, Int64 inMemPtr, Int64 outMemPtr)    at Apache.Ignite.Core.Impl.PlatformTarget.DoOutInOp[TR](Int32 type, Action`1 outAction, Func`2 inAction)    at Apache.Ignite.Core.Impl.Binary.BinaryProcessor.GetType(Int32 id)    at Apache.Ignite.Core.Impl.Binary.Marshaller.GetDescriptor(Boolean userType, Int32 typeId, Boolean requiresType)    at Apache.Ignite.Core.Impl.Binary.BinaryReader.ReadFullObject[T](Int32 pos)    at Apache.Ignite.Core.Impl.Binary.BinaryReader.TryDeserialize[T](T& res)  at Apache.Ignite.Core.Impl.Binary.BinaryReader.Deserialize[T]()    at Apache.Ignite.Core.Impl.Binary.BinaryReader.ReadBinaryObject[T](Boolean do Detach)    at Apache.Ignite.Core.Impl.Binary.BinaryReader.TryDeserialize[T](T& res)  at Apache.Ignite.Core.Impl.Binary.BinaryReader.Deserialize[T]()    at Apache.Ignite.Core.Impl.Datastream.StreamReceiverHolder.InvokeReceiver[TK, TV](IStreamReceiver`2 receiver, Ignite grid, IUnmanagedTarget cache, IBinaryStream stream, Boolean keepBinary)    at Apache.Ignite.Core.Impl.Datastream.StreamReceiverHolder.Receive(Ignite grid, IUnmanagedTarget cache, IBinaryStream stream, Boolean keepBinary)    at Apache.Ignite.Core.Impl.Unmanaged.UnmanagedCallbacks.DataStreamerStreamReceiverInvoke(Int64 memPtr, Int64 unused, Int64 unused1, Void* cache)    at Apache.Ignite.Core.Impl.Unmanaged.UnmanagedCallbacks.InLongLongLongObjectOutLong(Void* target, Int32 type, Int64 val1, Int64 val2, Int64 val3, Void* arg)
        at org.apache.ignite.internal.processors.platform.PlatformProcessorImpl.loggerLog(PlatformProcessorImpl.java:497)
        at org.apache.ignite.internal.processors.platform.callback.PlatformCallbackUtils.inLongLongLongObjectOutLong(Native Method)
        at org.apache.ignite.internal.processors.platform.callback.PlatformCallbackGateway.dataStreamerStreamReceiverInvoke(PlatformCallbackGateway.java:464)
        at org.apache.ignite.internal.processors.platform.datastreamer.PlatformStreamReceiverImpl.receive(PlatformStreamReceiverImpl.java:100)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamerUpdateJob.call(DataStreamerUpdateJob.java:137)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.localUpdate(DataStreamProcessor.java:382)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.processRequest(DataStreamProcessor.java:301)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.access$000(DataStreamProcessor.java:58)
        at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor$1.onMessage(DataStreamProcessor.java:88)
        at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1257)
        at org.apache.ignite.internal.managers.communication.GridIoManager.processRegularMessage0(GridIoManager.java:885)
        at org.apache.ignite.internal.managers.communication.GridIoManager.access$2100(GridIoManager.java:114)
        at org.apache.ignite.internal.managers.communication.GridIoManager$7.run(GridIoManager.java:802)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:748)


来源: stackexchange

问:
MaskedEditValidator baloon tooltip - AJAX Control Toolkit
I'm using MaskedEditValidator for validating Date input. I want to show balloon like tool tip instead of the normal message in red color which is creating alignment problems everywhere.

I have to stick to MaskedEditValidator as lot of implementation is already done around it.

AJAX Control ToolKit Version : 3.5.40412.0

答:
You can use the ValidatorCallout extender for that purpose:</p>

```<code><ajaxToolkit:MaskedEditValidator ID="YourMaskedEditValidator" runat="server"
    ControlExtender="YourMaskedEditExtender"
    ControlToValidate="YourMaskedTextBox" Display="None" />

<ajaxToolkit:ValidatorCalloutExtender ID="YourMaskedEditCallout" runat="server"
    TargetControlID="YourMaskedEditValidator" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can use the ValidatorCallout extender for that purpose:

<ajaxToolkit:MaskedEditValidator ID="YourMaskedEditValidator" runat="server"
    ControlExtender="YourMaskedEditExtender"
    ControlToValidate="YourMaskedTextBox" Display="None" />

<ajaxToolkit:ValidatorCalloutExtender ID="YourMaskedEditCallout" runat="server"
    TargetControlID="YourMaskedEditValidator" />


问:
ETABS 2016 VBA SetOConcrete_1 assigns only the last Fc value for all definitions
I'm working on an Excel VBA module that supplies certain data to ETABS 2016, part of the code is to define multiple material properties through using API methods SetMaterial and SetOConcrete_1.
The effective part of the code is this

```<code>    'Values:-
    'Val(0)=label, Val(1)=Fc', Val(2)=E, Vals(3)=StrainAtFc, Val(4)=UltimateStrain, Val(5)=PoisonRatio, Val(6)=Thermal Coef
    'Val(7) = UnitWeight
    For i = 0 To iCount - 1
    .
    .
    SOME LONG CODE TO RETRIEVE DATA TO A DYNAMIC ARRAY OF VARIANTS CALLED "VAL"
    .
    .
    With myModel.PropMaterial
    MsgBox Val(0) & " " & Val(1) & " " & i 'debug line to display input values for label and FC'
    ret = .SetMaterial(Val(0), eMatType_Concrete)
    ret = .SetOConcrete_1(Val(0), Val(1), False, 0, 2, 4, Val(3), Val(4), -0.1)
    ret = .SetWeightAndMass(Val(0), 1, Val(7))
    ret = .SetMPIsotropic(Val(0), Val(2), Val(5), Val(6))
    End With
    Next i
</code>```

I've even added a debugging part to display the values of interest, per one definition, two definitions, and so on, this part is

```<code>    'Debugging part
     If i >= 0 Then
         On Error GoTo 0
         Err.Raise (2)
     End If
    'End of Debugging part
</code>```

and then, I change i >= 0 to i >= 1 and to i >= 2 to display the needed number of iterations .

The debugging part always displays the correct and needed values of Val(0)(the material's Name) and Val(1)(the material's Fc) for every iteration,
for example, the values for every iteration are:-

1- Iteration no.1: Val(0) = "C35", Val(1) = 35000, i = 0

2- Iteration no.2: Val(0) = "C37", Val(1) = 37000, i = 1

3- Iteration no.3: Val(0) = "C38", Val(1) = 38000, i = 2

and Then, what happens in ETABS is the following:-

1- With i >= 0 I get one iteration and one material definition of "C35", "C35" has Fc = 35MPa [Correct Result]

2- With i >= 1 I get two iterations and two material definitions of "C35" and "C37", but all of them have Fc = 37 MPa [Wrong Result]

3- With i >= 2 I get three iterations and three material definitions of "C35", "C37" and "C38", but all of them have Fc = 38 MPa [Wrong Result]

So, How Can the supplied values of the material's name and Fc to SetOConcrete_1 be different at every iteration and ETABS just ignores all that work and just supplies only the last Fc value to all materials?!

答:
Is the ETABS API taking the value you supply it as a reference? That's what it seems like based on your explanation.

```<code>Public Sub Temp()
    'In order to use early-binding Dictionary you need to set a
    'reference in Tools>References>"Microsoft Scripting Runtime"
    Dim foo As Dictionary
    Set foo = New Dictionary

    Dim bar As Range
    Set bar = ActiveSheet.Range("A1")

    bar.Value2 = "Original"

    foo.Add "1", bar.Value2
    foo.Add "2", bar

    bar.Value2 = "Changed"

    Debug.Print foo("1")
    Debug.Print foo("2")
End Sub
</code>```

If you go through this example you'll notice that when an item is added with .Value2, value type, it doesn't change. When it's fed in as a Range, reference type, it will change.

You may have a different outcome if you extract each value in the Val variable into their respective type before feeding them in.

```<code>Dim label As String
label = Val(0)

Dim Fc As Long
Fc = Val(1)

Dim strainAtFc As Long
strainAtFc = Val(3)

Dim ultimateStrain As Long
ultimateStrain = Val(4)

Dim poisonRatio As Long
poisonRatio = Val(5)

Dim thermalCoefficient As Long
thermalCoefficient = Val(6)

Dim unitWeight As Long
unitWeight = Val(7)
</code>```

***Note that Val is also a member of VBA.Conversion and could cause issues if it isn't Dimd.

ContentLicense: CC BY-SA 3.0

Body:
I'm working on an Excel VBA module that supplies certain data to ETABS 2016, part of the code is to define multiple material properties through using API methods SetMaterial and SetOConcrete_1.
The effective part of the code is this

    'Values:-
    'Val(0)=label, Val(1)=Fc', Val(2)=E, Vals(3)=StrainAtFc, Val(4)=UltimateStrain, Val(5)=PoisonRatio, Val(6)=Thermal Coef
    'Val(7) = UnitWeight
    For i = 0 To iCount - 1
    .
    .
    SOME LONG CODE TO RETRIEVE DATA TO A DYNAMIC ARRAY OF VARIANTS CALLED "VAL"
    .
    .
    With myModel.PropMaterial
    MsgBox Val(0) & " " & Val(1) & " " & i 'debug line to display input values for label and FC'
    ret = .SetMaterial(Val(0), eMatType_Concrete)
    ret = .SetOConcrete_1(Val(0), Val(1), False, 0, 2, 4, Val(3), Val(4), -0.1)
    ret = .SetWeightAndMass(Val(0), 1, Val(7))
    ret = .SetMPIsotropic(Val(0), Val(2), Val(5), Val(6))
    End With
    Next i

I've even added a debugging part to display the values of interest, per one definition, two definitions, and so on, this part is

    'Debugging part
     If i >= 0 Then
         On Error GoTo 0
         Err.Raise (2)
     End If
    'End of Debugging part

and then, I change i >= 0 to i >= 1 and to i >= 2 to display the needed number of iterations .

The debugging part always displays the correct and needed values of Val(0)(the material's Name) and Val(1)(the material's Fc) for every iteration,
for example, the values for every iteration are:-

1- Iteration no.1: Val(0) = "C35", Val(1) = 35000, i = 0

2- Iteration no.2: Val(0) = "C37", Val(1) = 37000, i = 1

3- Iteration no.3: Val(0) = "C38", Val(1) = 38000, i = 2

and Then, what happens in ETABS is the following:-

1- With i >= 0 I get one iteration and one material definition of "C35", "C35" has Fc = 35MPa [Correct Result]

2- With i >= 1 I get two iterations and two material definitions of "C35" and "C37", but all of them have Fc = 37 MPa [Wrong Result]

3- With i >= 2 I get three iterations and three material definitions of "C35", "C37" and "C38", but all of them have Fc = 38 MPa [Wrong Result]

So, How Can the supplied values of the material's name and Fc to SetOConcrete_1 be different at every iteration and ETABS just ignores all that work and just supplies only the last Fc value to all materials?!

Body:
Is the ETABS API taking the value you supply it as a reference? That's what it seems like based on your explanation.

Public Sub Temp()
    'In order to use early-binding Dictionary you need to set a
    'reference in Tools>References>"Microsoft Scripting Runtime"
    Dim foo As Dictionary
    Set foo = New Dictionary

    Dim bar As Range
    Set bar = ActiveSheet.Range("A1")

    bar.Value2 = "Original"

    foo.Add "1", bar.Value2
    foo.Add "2", bar

    bar.Value2 = "Changed"

    Debug.Print foo("1")
    Debug.Print foo("2")
End Sub

If you go through this example you'll notice that when an item is added with .Value2, value type, it doesn't change. When it's fed in as a Range, reference type, it will change.

You may have a different outcome if you extract each value in the Val variable into their respective type before feeding them in.

Dim label As String
label = Val(0)

Dim Fc As Long
Fc = Val(1)

Dim strainAtFc As Long
strainAtFc = Val(3)

Dim ultimateStrain As Long
ultimateStrain = Val(4)

Dim poisonRatio As Long
poisonRatio = Val(5)

Dim thermalCoefficient As Long
thermalCoefficient = Val(6)

Dim unitWeight As Long
unitWeight = Val(7)

***Note that Val is also a member of VBA.Conversion and could cause issues if it isn't Dimd.


问:
External API async call with callback
I use Angular with Spring for internal API communication. Now I need to call external api to get some data. That external API provides callback feature, so I trigger call from Angular, call Spring rest method which, at the end, calls external API.
On the other hand I get data on my callback methods (Spring rest also), but I dont know how to transfer those data back to Angular. </p>

<p>Is websocket the only option? </p>

答:
If internal API calls are longer than the allowable client timeout, then you will need to find a WebSocket or WebSocket-like alternative. The alternative to WebSockets is to use long-polling (good example with source code here), which is essentially having the client repeatedly make requests until the original task is completed and the data can be sent. Either way, you'll need to use a pub/sub mechanism of some sort to handle multiple users, which is where things can get complicated.

Pub/sub can be complicated and I don't have an example on-hand, but essentially you must (1) have the client subscribe to a channel using a unique identifier (you can do this with CometD via a service channel), (2) evaluate the response, (3) publish the response to the client's subscribed channel, and finally (4) close the channel when it's no longer in use.

I've had some luck with CometD as a library to simplify pub/sub channel management, and it provides a good abstraction for asynchronous communication, although I haven't tried it with Spring and it might be heavy for what you want to do.

Another option that I'm less familiar with is to use Spring with STOMP. This seems to come recommended by others. Spring does provide ways to send messages to single users using STOMP: Sending message to specific user on Spring Websocket

I'd recommend following the above STOMP example.

Additional STOMP resources:

Getting Started with WebSockets (Spring)

Enable STOMP Over WebSocket

Angular2 with Stomp.js

As a side note, throttling may be necessary here, too, as with any time that you can spawn long-running threads from clients.

If you choose not to use STOMP or CometD, then a lighter solution could be to roll your own pub/sub for this single case using Spring's DeferredResult (as in Roger Hughes example), tying the subscription request to the long-poll request via a UUID token, which might also be the session ID if you choose to disallow concurrent requests per user. On subscription, the system can associate the request with a UUID and return this UUID to the client. The client can then make long-poll requests (again, as in Roger Hughes example) but with the UUID attached. The server can wait until the request for the given UUID has completed and then return the result to the client via the client's active long-poll request.

Channel management (i.e., request/UUID-tracking) can be done by clearing the channel on DeferredResult result retrieval and removing orphan channels with a separate thread acting as a GC -- or, perhaps better yet, automatically clearing orphan channels by removing them on DeferredResult completion/timeout if no active listeners exist. If you opt for the latter option, you will want to make sure that the client won't have any delay between its long-poll requests so that the DeferredResult doesn't unintentionally complete with no listeners.

Title: External API async call with callback

Body:
I use Angular with Spring for internal API communication. Now I need to call external api to get some data. That external API provides callback feature, so I trigger call from Angular, call Spring rest method which, at the end, calls external API.
On the other hand I get data on my callback methods (Spring rest also), but I dont know how to transfer those data back to Angular.

Is websocket the only option?


问:
Delete user from MySQL table if no other users exist with similar traits
I have the following table called tbl_test in a MySQL database :

```<code>+------+------------+------------+
| name | fav_color  | dob        |
+======+============+============+
| jane | blue       | 1996-07-07 |
+------+------------+------------+
| jane | pink       | 1996-07-07 |
+------+------------+------------+
| jane | pink       | 2016-07-07 |
+------+------------+------------+
| joe  | pink       | 2001-07-07 |
+------+------------+------------+
| john | red        | 1997-07-07 |
+------+------------+------------+
</code>```

In English, here's what I want to accomplish:

delete all users with dob < 2001-01-01 but keep a user if there exists another user with the same name AND fav_color whose dob >= 2001-01-01.

So in this example, the jane whose favorite color is blue and john would be deleted.

So far, I've tried:

```<code>DELETE FROM tbl_test
WHERE dob < '2000-01-01' AND name, fav_color NOT IN
(SELECT T.name, T.fav_color FROM
(SELECT name, fav_color FROM tbl_test WHERE dob >= '2000-01-01') T);
</code>```

But MySQL throws a syntax error when I enter this command. Any tips for how I can achieve this?

答:
MySQL doesn't let you refer to the table being deleted in the rest of the statement.  So:

```<code>DELETE t
    FROM tbl_test t LEFT JOIN
         (SELECT t2.name, t2.fav_color
          FROM tbl_test t2
          WHERE dob >= '2000-01-01'
         ) tt
         ON t.name = tt.name AND t.fav_color = tt.fav_color
    WHERE t.dob < '2000-01-01' AND tt.name IS NULL;
</code>```

Your method is very reasonable.  And, you do have some other syntax errors (such as the first argument to NOT IN should have parentheses).  Even if you fix those, though, you'll have a problem with the query.

Body:
I have the following table called tbl_test in a MySQL database :

+------+------------+------------+
| name | fav_color  | dob        |
+======+============+============+
| jane | blue       | 1996-07-07 |
+------+------------+------------+
| jane | pink       | 1996-07-07 |
+------+------------+------------+
| jane | pink       | 2016-07-07 |
+------+------------+------------+
| joe  | pink       | 2001-07-07 |
+------+------------+------------+
| john | red        | 1997-07-07 |
+------+------------+------------+

In English, here's what I want to accomplish:

delete all users with dob < 2001-01-01 but keep a user if there exists another user with the same name AND fav_color whose dob >= 2001-01-01.

So in this example, the jane whose favorite color is blue and john would be deleted.

So far, I've tried:

DELETE FROM tbl_test
WHERE dob < '2000-01-01' AND name, fav_color NOT IN
(SELECT T.name, T.fav_color FROM
(SELECT name, fav_color FROM tbl_test WHERE dob >= '2000-01-01') T);

But MySQL throws a syntax error when I enter this command. Any tips for how I can achieve this?

Body:
MySQL doesn't let you refer to the table being deleted in the rest of the statement.  So:

DELETE t
    FROM tbl_test t LEFT JOIN
         (SELECT t2.name, t2.fav_color
          FROM tbl_test t2
          WHERE dob >= '2000-01-01'
         ) tt
         ON t.name = tt.name AND t.fav_color = tt.fav_color
    WHERE t.dob < '2000-01-01' AND tt.name IS NULL;

Your method is very reasonable.  And, you do have some other syntax errors (such as the first argument to NOT IN should have parentheses).  Even if you fix those, though, you'll have a problem with the query.


问:
How do you stop injection in this PHP/PDO
So I have look at so many post, web sites and video and now I am so confused!  I can't seem to get it right.
How do you stop injection in this PHP/PDO.  I have this code that works, but it allows injection.

```<code>//*THIS WORKS BUT ALLOWS INJECTION
//*

//The variable $word comes from another php file where the search is created.
public function getAllCards($word) {

    $sql = "SELECT * FROM carddbtable WHERE businessNameDB='".$word."'";

foreach ($this->conn->query($sql) as $row) {

    echo json_encode($row)."<br>"."<br>";
}

$db = null;
}
</code>```

With this new code I am trying to remove the variable  "$word"  from the   "SELECT * FROM "  statement
to stop the injection and add the  "prepare"   and the  error checking and the   "execute" statement,  but I can't get it right. How would I do this?     FYI this is a GoDaddy shared server.

```<code>//Getting the search "word" from the GetCards.php
 public function getAllCards($word) {

    //Empty var to store all returned info from db
    $returnArray = array();

    // sql statement to be executed
    $sql = "SELECT * FROM carddbtable WHERE businessNameDB=':word";

    // prepare to be executed
    $statement = $this->conn->prepare($sql);

    // error occurred
    if (!$statement) {
        throw new Exception($statement->error);
    }

    // execute statement
    $statement->execute( :word => '$word' );

//run the query
foreach ($this->conn->query($statement) as $row) {

echo json_encode($row)."<br>"."<br>";

}

    // store all appended $rows in $returnArray to be sent to app
    $returnArray[] = $row;
}
</code>```

答:
I got this working</p>

```<code>//*FUNCTION TO GET CARD FROM SEARCH WORD CALLED FROM GetCards.php
public function getAllCards($word) {

//Connect to db using the PDO not PHP
$db = new PDO('mysql:host=localhost;dbname=xxxx', 'xxxx', 'xxxx');

//Here we prepare the SELECT statement from the search word place holder :word
$sql = $db->prepare('SELECT * FROM carddbtable WHERE businessNameDB=:word');

//We execute the $sql with the search word variable"$word"
$sql->execute([':word' => $word]);

//Looping through the results
foreach ($sql as $row)

//Print to screen
echo json_encode($row). "<br>"."<br>";
}
</code>```

Body:
So I have look at so many post, web sites and video and now I am so confused!  I can't seem to get it right.
How do you stop injection in this PHP/PDO.  I have this code that works, but it allows injection.

//*THIS WORKS BUT ALLOWS INJECTION
//*

//The variable $word comes from another php file where the search is created.
public function getAllCards($word) {

    $sql = "SELECT * FROM carddbtable WHERE businessNameDB='".$word."'";

foreach ($this->conn->query($sql) as $row) {

    echo json_encode($row)."
"."
";
}

$db = null;
}

With this new code I am trying to remove the variable  "$word"  from the   "SELECT * FROM "  statement
to stop the injection and add the  "prepare"   and the  error checking and the   "execute" statement,  but I can't get it right. How would I do this?     FYI this is a GoDaddy shared server.

//Getting the search "word" from the GetCards.php
 public function getAllCards($word) {

    //Empty var to store all returned info from db
    $returnArray = array();

    // sql statement to be executed
    $sql = "SELECT * FROM carddbtable WHERE businessNameDB=':word";

    // prepare to be executed
    $statement = $this->conn->prepare($sql);

    // error occurred
    if (!$statement) {
        throw new Exception($statement->error);
    }

    // execute statement
    $statement->execute( :word => '$word' );

//run the query
foreach ($this->conn->query($statement) as $row) {

echo json_encode($row)."
"."
";

}

    // store all appended $rows in $returnArray to be sent to app
    $returnArray[] = $row;
}

Body:
I got this working

//*FUNCTION TO GET CARD FROM SEARCH WORD CALLED FROM GetCards.php
public function getAllCards($word) {

//Connect to db using the PDO not PHP
$db = new PDO('mysql:host=localhost;dbname=xxxx', 'xxxx', 'xxxx');

//Here we prepare the SELECT statement from the search word place holder :word
$sql = $db->prepare('SELECT * FROM carddbtable WHERE businessNameDB=:word');

//We execute the $sql with the search word variable"$word"
$sql->execute([':word' => $word]);

//Looping through the results
foreach ($sql as $row)

//Print to screen
echo json_encode($row). "<br>"."<br>";
}


问:
ComboBox doesn't show with bootstrap
I'm trying to build a form containing a ComboBox [ZK component] but I can't get it to to show.

here's the code :

```<code> <h:form class="form form-vb">
    <h:div class="input-group">
        <h:label for="ZipCode">
                Code ZIP :
            </h:label>
            <combobox
              sclass="form-control"
              width="100%"
              id="ZipCode"
              model="@bind(vm.ZipCodeList)"
              selectedItem="@bind(vm.zipcode)" autodrop="true"
                                            autocomplete="true"
                                            value="@load(ZipCode.name)">
                                            <template name="model">
                                                <comboitem
                                            value="@bind(each.zipcode)" />
                                            </template>
                                        </combobox>
                                    </h:div>
</h:form>
</code>```

答:
The problem is the surrounding  tag. If you remove it you get the combo.

```<code><zk xmlns:h="http://www.w3.org/1999/xhtml">
    <style src="css/home/bootstrap.css" />
    <window border="normal" title="hello" apply="pkg$.TestComposer">
        <div>Welcome to ZK Fiddle , run it right now!</div>
        <h:form class="form form-vb">
            <h:div class="input-group">
                <h:label for="ZipCode">
                    Code ZIP :
                </h:label>
                <combobox
                        sclass="form-control"
                        width="100%"
                        id="ZipCode"
                        model="@bind(vm.ZipCodeList)"
                        selectedItem="@bind(vm.zipcode)"
                        autodrop="true"
                        autocomplete="true"
                        value="@load(ZipCode.name)">
                    <template name="model">
                        <comboitem value="@bind(each.zipcode)" />
                    </template>
                </combobox>
            </h:div>
        </h:form>
        <button id="btn" label="Click Me To Evalute Event Binding With Composer"/>
    </window>
</zk>
</code>```

Demo: http://zkfiddle.org/sample/af6lv3/1-Another-new-ZK-fiddle

Title: ComboBox doesn't show with bootstrap

Body:
I'm trying to build a form containing a ComboBox [ZK component] but I can't get it to to show.

here's the code :

 <h:form class="form form-vb">
    <h:div class="input-group">
        <h:label for="ZipCode">
                Code ZIP :
            </h:label>
            <combobox
              sclass="form-control"
              width="100%"
              id="ZipCode"
              model="@bind(vm.ZipCodeList)"
              selectedItem="@bind(vm.zipcode)" autodrop="true"
                                            autocomplete="true"
                                            value="@load(ZipCode.name)">
                                            <template name="model">
                                                <comboitem
                                            value="@bind(each.zipcode)" />
                                            </template>
                                        </combobox>
                                    </h:div>
</h:form>

Body:
The problem is the surrounding <html> tag. If you remove it you get the combo.

<zk xmlns:h="http://www.w3.org/1999/xhtml">
    <style src="css/home/bootstrap.css" />
    <window border="normal" title="hello" apply="pkg$.TestComposer">
        <div>Welcome to ZK Fiddle , run it right now!</div>
        <h:form class="form form-vb">
            <h:div class="input-group">
                <h:label for="ZipCode">
                    Code ZIP :
                </h:label>
                <combobox
                        sclass="form-control"
                        width="100%"
                        id="ZipCode"
                        model="@bind(vm.ZipCodeList)"
                        selectedItem="@bind(vm.zipcode)"
                        autodrop="true"
                        autocomplete="true"
                        value="@load(ZipCode.name)">
                    <template name="model">
                        <comboitem value="@bind(each.zipcode)" />
                    </template>
                </combobox>
            </h:div>
        </h:form>
        <button id="btn" label="Click Me To Evalute Event Binding With Composer"/>
    </window>
</zk>

Demo: http://zkfiddle.org/sample/af6lv3/1-Another-new-ZK-fiddle


问:
List<T> add method in C#
As I know. List Add method works as below.

```<code>List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
</code>```

If I designed the data structure as this

```<code>List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}
</code>```

Does the List Add method works or not if I add different types members in the same function.

答: There's no point using a generic list with object as the type parameter, might as well use a System.Collections.ArrayList.</p>

Title: List<T> add method in C#

Body:
As I know. List Add method works as below.

List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");

If I designed the data structure as this

List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}

Does the List Add method works or not if I add different types members in the same function.


答:
I am not sure if this is exactly what you want, but your use of IN is not correct. I think you want to use EXIST (or in this case NOT EXIST)

```<code>DELETE FROM tbl_test
WHERE dob < '2000-01-01'
AND NOT EXIST(
    SELECT null FROM tbl_test as tt
    WHERE tt.name = tbl_test.name
        AND tt.fav_color = tbl_test.fav_color
        AND dob >= '2000-01-01'
)
</code>```

Title: Delete user from MySQL table if no other users exist with similar traits

Body:
I am not sure if this is exactly what you want, but your use of IN is not correct. I think you want to use EXIST (or in this case NOT EXIST)

DELETE FROM tbl_test
WHERE dob < '2000-01-01'
AND NOT EXIST(
    SELECT null FROM tbl_test as tt
    WHERE tt.name = tbl_test.name
        AND tt.fav_color = tbl_test.fav_color
        AND dob >= '2000-01-01'
)


问:
Using python to run command line actions
I am writing a program to constantly change my IP address. I have learned that methods from the subprocess module can be useful to write in the command line (such as subclass.Popen). In OS X, how can I put a function into python code to execute into the command line? In my case, I need (sudo ipconfig set en0 DHCP && sudo ipconfig set en1 DHCP) executed in my python code.

答:
subprocess.Popen("sudo command", shell=True)

Should work for your case


问:
UITableView is under the TabBar
I have a custom UITableView with custom cells (70px height for each cell).

I have also a 49px UITabBar, but it's hides the tableView.

I've tried to add this line to the TableView awakeFromNib method but it didn't work:

```<code>self.commentsTableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0)
</code>```

Any idea how can I solve this?

Thanks!

答:
Try this</p>

```<code>self.commentsTableView.contentInset = UIEdgeInsetsMake(49, 0, 0, 0)
self.commentsTableView.setContentOffset(CGPoint.init(x: 0, y: -49), animated: false)
</code>```

Title: UITableView is under the TabBar

Body:
I have a custom UITableView with custom cells (70px height for each cell).

I have also a 49px UITabBar, but it's hides the tableView.

I've tried to add this line to the TableView awakeFromNib method but it didn't work:

self.commentsTableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0)

Any idea how can I solve this?

Thanks!

Body:
Try this

self.commentsTableView.contentInset = UIEdgeInsetsMake(49, 0, 0, 0)
self.commentsTableView.setContentOffset(CGPoint.init(x: 0, y: -49), animated: false)


问:
bootstrap not loading on angular partial page
I have this issue with a couple different pages I've been working on. I'll provide a simple example. I'm not very comfortable with front-end work so apologies if my html page is hard to read.

I have an angular single-page application with a header bar that takes up 100px and then partial pages are routed below it.

my index.html

```<code><html>
<head>
  <base href="/">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.8.5/css/selectize.default.css">
  <!--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.8.5/css/selectize.bootstrap3.css">-->
  <link rel="stylesheet" type="text/css" href="./stylesheets/style.css">
  <link rel="stylesheet" type="text/css" href="./stylesheets/index.css">
</head>

<body data-ng-app="angulobby" data-ng-controller="indexController">
<div id="container">
  <header>
    <nav class="navbar navbar-default">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="/">AnguLobby Prototype</a>
        </div>
        <ul class="nav navbar-nav navbar-right">
          <li><a href="/"><i class="fa fa-home"></i> Home</a></li>
          <li><a href="/login"><i class="fa fa-shield"></i> Login</a></li>
          <li><a href="/register"><i class="fa fa-comment"></i> Register</a></li>
          <div ng-controller="logoutController">
            <a ng-click='logout()' class="btn btn-default">Logout</a>
          </div>
        </ul>
      </div>
    </nav>
  </header>
  <!--injected views go here-->
  <div id="ng-view" ng-view></div>
</div>
<script src="https://use.fontawesome.com/7222f42b52.js"></script>
<script src="./socket.io/socket.io.js"></script>
<script src="./main.js"></script>

<!--expose angular controllers-->
<script src="controllers/home.js"></script>
<script src="controllers/index.js"></script>
<script src="controllers/login.js"></script>
<script src="controllers/logout.js"></script>
<script src="controllers/register.js"></script>
<script src="controllers/select-params.js"></script>
<script src="controllers/queueTimer.js"></script>
<script src="controllers/lobby.js"></script>

<!--expose angular services-->
<script src="./services/auth.js"></script>
<script src="./services/gamelist.js"></script>
<script src="./services/queue.js"></script>
<script src="./services/socket.js"></script>
<script src="./services/lobby.js"></script>
</body>
</html>
</code>```

and index.css

```<code>html, body {
  height: 100%;
}
#container {
  height:100%;
  display:flex;
  flex-flow:column;
}

#ng-view {
  overflow: hidden;
}

header {
  height: 100px;
}
</code>```

and then for instance if I have a simple partial page that I would like to inject into ng-view:

lobby.html

```<code><head>
  <link rel="stylesheet" type="text/css" href="../stylesheets/lobby.css">

</head>

<div id="lobby-container" class="container">
  <div class="container">
    <div class="row">
      <div id="chat" class="col-md-2">
      </div>
      <div id="users" class="col-md-2"></div>
    </div>
  </div>
  <script
    src="https://code.jquery.com/jquery-3.2.1.min.js"
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
    crossorigin="anonymous"></script>
  <script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
    integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
    crossorigin="anonymous">
  </script>
</div>
</code>```

and lobby.css

```<code>#lobby-container {
  background-color: greenyellow;
  height: 100%;
  width: 100%;
}

#chat {
  background-color: grey;
  height: 100%;
}

#users {
  background-color: darkblue;
  height: 100%;
}
</code>```

When I load the partial page on it's own, no bootstrap is executed.It shows two divs without the col class attributed.

But, when I build the project, the bootstrap is loaded.

I understand that the general problem is that the partial views only get the bootstrap added from index.html when angular actually injects them into ng-view. What I would like to do is be able to preview each partial page and have bootstrap loaded already without having to build the project each time. I am using the webstorm IDE if that matters.

答:
Okay, just figured it out. I had added the bootstrap.js file but forgot to add the bootstrap.css file. Adding
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

to the  of lobby.html fixed the problem.

Body:
I have this issue with a couple different pages I've been working on. I'll provide a simple example. I'm not very comfortable with front-end work so apologies if my html page is hard to read.

I have an angular single-page application with a header bar that takes up 100px and then partial pages are routed below it.

my index.html

  <base href="/">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.8.5/css/selectize.default.css">

  <link rel="stylesheet" type="text/css" href="./stylesheets/style.css">
  <link rel="stylesheet" type="text/css" href="./stylesheets/index.css">

          AnguLobby Prototype

 Home

 Login

 Register

            Logout

and index.css

html, body {
  height: 100%;
}
#container {
  height:100%;
  display:flex;
  flex-flow:column;
}

#ng-view {
  overflow: hidden;
}

header {
  height: 100px;
}

and then for instance if I have a simple partial page that I would like to inject into ng-view:

lobby.html

  <link rel="stylesheet" type="text/css" href="../stylesheets/lobby.css">

and lobby.css

#lobby-container {
  background-color: greenyellow;
  height: 100%;
  width: 100%;
}

#chat {
  background-color: grey;
  height: 100%;
}

#users {
  background-color: darkblue;
  height: 100%;
}

When I load the partial page on it's own, no bootstrap is executed.It shows two divs without the col class attributed.

But, when I build the project, the bootstrap is loaded.

I understand that the general problem is that the partial views only get the bootstrap added from index.html when angular actually injects them into ng-view. What I would like to do is be able to preview each partial page and have bootstrap loaded already without having to build the project each time. I am using the webstorm IDE if that matters.

Body:
Okay, just figured it out. I had added the bootstrap.js file but forgot to add the bootstrap.css file. Adding
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

to the <head> of lobby.html fixed the problem.


问:
How to escape quotations marks in a hyperlink
The link I must get to must be http://localhost:8088/imageInfo.php?id=4

 I started with this and no matter how I tried to escape I couldn't do it so any help would be appreciated

```<code>."<a href='imageInfo.php?id=<?php echo $image_id;?>'>".
</code>```

答:
Is this snippet perhaps part of a larger line of code?  Something like this?:

```<code>echo "some string" . "<a href='imageInfo.php?id=<?php echo $image_id;?>'>" . "another string";
</code>```

If so then the problem has nothing to do with the quotes, the problem is that you're echoing PHP code as a string to the response.  The browser isn't going to know what to do with that PHP code.  Instead, just concatenate the values you have into a single string.  Something like:

```<code>echo 'some string<a href="imageInfo.php?id=' . $image_id . '">another string';
</code>```

(Note that I also swapped single quotes and double quotes so that the resulting HTML is using double quotes.  While either one works, technically HTML attributes should be double-quoted.)

Basically, you don't need to embed PHP code in PHP code.  You're already in the context of executing PHP, just execute the code right there.

Body:
The link I must get to must be http://localhost:8088/imageInfo.php?id=4

 I started with this and no matter how I tried to escape I couldn't do it so any help would be appreciated

."<a href='imageInfo.php?id=<?php echo $image_id;?>'>".

Body:
Is this snippet perhaps part of a larger line of code?  Something like this?:

echo "some string" . "<a href='imageInfo.php?id=<?php echo $image_id;?>'>" . "another string";

If so then the problem has nothing to do with the quotes, the problem is that you're echoing PHP code as a string to the response.  The browser isn't going to know what to do with that PHP code.  Instead, just concatenate the values you have into a single string.  Something like:

echo 'some string<a href="imageInfo.php?id=' . $image_id . '">another string';

(Note that I also swapped single quotes and double quotes so that the resulting HTML is using double quotes.  While either one works, technically HTML attributes should be double-quoted.)

Basically, you don't need to embed PHP code in PHP code.  You're already in the context of executing PHP, just execute the code right there.


问:
Difference between plt.close() and plt.clf()
In matplotlib.pyplot, what is the difference between plt.clf() and plt.close()? Will they function the same way?

I am running a loop where at the end of each iteration I am producing a figure and saving the plot. On first couple tries the plot was retaining the old figures in every subsequent plot. I'm looking for, individual plots for each iteration without the old figures, does it matter which one I use? The calculation I'm running takes a very long time and it would be very time consuming to test it out.

答:
plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

plt.close() closes a window, which will be the current window, if not specified otherwise.

ContentLicense: CC BY-SA 4.0


问:
Windows 10 Creators Update changes the style of PropertyGrid control
I just upgraded some systems to Windows 10 Creators Update and I noticed that the windows forms PropertyGrid control changed its default visual style for headers and bar margins to dark gray, like so:

<img src="https://i.stack.imgur.com/2I2Vst.png" alt="PropertyGrid new style">

And as mostly happens with unexpected visual changes, users are not happy. Is there a way to revert back to the old default or maybe override the default style?

答:
We are reverting header color to InactiveBorder in the default windows theme in the next release of the .Net Framework, which most likely will be included in the Windows 10 Fall Creators Update. The reason this change was introduced, was that the foreground and background colors were not contrasting enough in one of the High Contrast themes, this is why we are reverting to the previously used color only in the default theme.
For your reference, internal work item number, that will be also mentioned in release notes for .Net Framework 4.7.1, is 407249.

Thank you, Tanya


问:
Expression For Last Day of January in Current Year
I want to know what expression what I use to find specifically the last day of the month of January for the current year. Can anybody help me with this specific expression in SSRS? Trying to use for a parameter value.

Thanks!

答:
That can be as simple as something like this:

```<code>=CDate("1/31/" & DatePart(DateInterval.Year, Today))
</code>```

You may need to change this a bit depending on the date format of where you live. This one above would be fine anywhere in the US.

```<code>=CDate("31/01/" & DatePart(DateInterval.Year, Today))
</code>```

This one could be best for Europe.

```<code>=CDate(DatePart(DateInterval.Year, Today) & "-01-31")
</code>```

Above works, too.

Play around with the idea. Hope this helps.

Body:
That can be as simple as something like this:

=CDate("1/31/" & DatePart(DateInterval.Year, Today))

You may need to change this a bit depending on the date format of where you live. This one above would be fine anywhere in the US.

=CDate("31/01/" & DatePart(DateInterval.Year, Today))

This one could be best for Europe.

=CDate(DatePart(DateInterval.Year, Today) & "-01-31")

Above works, too.

Play around with the idea. Hope this helps.


问:
Somebody Has used the lepton-NodeJs for compression JPGs
I want compress some JPGs for update to the DB, this code is the only thing I found with documentation but I do not see what it is that needs to be uploaded to the database I know it's the file.lep but I do not know where to take it. https://github.com/whitef0x0/node-lepton

答:
Read the documentation:

These functions takes a callback that returns an error object and the output in form of a binary file blob.

The data parameter is exactly what you're looking for.


问:
Html table to csv table with image
How to export this html table  in to  CSV
example table:

i want this table to be exported to  csv  .so how to achieve using JQUERY?

```<code><html>
<body bgcolor="cyan">

<table border="1" align="center" >
 <br><a href="imp2.csv">Click Here To View In CSV format</a><img src="up.jpg"  align="middle" width="39" height="32" />
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Month</th>

    <th>Savings</th>

  </tr>
</table>

</body>
</html>
</code>```

Thanks
Joseph

答: CSV stands for Comma Seperated Values. It is just text seperated with commas(,). No way to give formatting to it for default application.</p>

Title: Html table to csv table with image

Body:
How to export this html table  in to  CSV
example table:

i want this table to be exported to  csv  .so how to achieve using JQUERY?

Click Here To View In CSV format

    ID
    Name
    Month

    Savings

Thanks
Joseph


问:
STM32F4 (Nucleo-F446RE CooCOX) basic GPIO
I just started programming the Nucleo-F446RE (Based on the STM32F446RE MCU).

I can't seem to get a pin to go active, I'm trying to just toggle a GPIO using the following code:

```<code>//*****************************************************************************
#include "stm32f446xx.h"
#include "stm32f4xx_hal.h"
//! \file main.c
//! \brief main application
//! \version 1.0.0.0
//! \date $Creat_time$
//! \author $Creat_author$
//! \copy
//!
//! Copyright (c) 2014 CooCox.  All rights reserved.
//
//! \addtogroup project
//! @{
//! \addtogroup main
//! @{
//*****************************************************************************

int main(void)

__HAL_RCC_GPIOA_CLK_ENABLE();
     GPIO_InitTypeDef GPIO_InitTypeDefStruct;

     GPIO_InitTypeDefStruct.Pin = GPIO_PIN_1;
     GPIO_InitTypeDefStruct.Speed = GPIO_SPEED_LOW;
     GPIO_InitTypeDefStruct.Pull = GPIO_PULLUP;
     GPIO_InitTypeDefStruct.Mode = GPIO_MODE_OUTPUT_PP;

    HAL_GPIO_Init(GPIOA, &GPIO_InitTypeDefStruct);

    while(1)

    {
        HAL_GPIO_TogglePin(&GPIO_InitTypeDefStruct,GPIO_PIN_1);

    }
</code>```

It doesn't seem to work though..I've gone through the header file and c file of the GPIO which explains how to go about setting the pin, although even following this to the bone, it just stays low. Where am I going wrong?

Thanks in advance for any help

答:
The

    HAL_GPIO_TogglePin(&GPIO_InitTypeDefStruct,GPIO_PIN_1);

should have been

```<code>HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_1);
</code>```

Body:
I just started programming the Nucleo-F446RE (Based on the STM32F446RE MCU).

I can't seem to get a pin to go active, I'm trying to just toggle a GPIO using the following code:

//*****************************************************************************
#include "stm32f446xx.h"
#include "stm32f4xx_hal.h"
//! \file main.c
//! \brief main application
//! \version 1.0.0.0
//! \date $Creat_time$
//! \author $Creat_author$
//! \copy
//!
//! Copyright (c) 2014 CooCox.  All rights reserved.
//
//! \addtogroup project
//! @{
//! \addtogroup main
//! @{
//*****************************************************************************

int main(void)

__HAL_RCC_GPIOA_CLK_ENABLE();
     GPIO_InitTypeDef GPIO_InitTypeDefStruct;

     GPIO_InitTypeDefStruct.Pin = GPIO_PIN_1;
     GPIO_InitTypeDefStruct.Speed = GPIO_SPEED_LOW;
     GPIO_InitTypeDefStruct.Pull = GPIO_PULLUP;
     GPIO_InitTypeDefStruct.Mode = GPIO_MODE_OUTPUT_PP;

    HAL_GPIO_Init(GPIOA, &GPIO_InitTypeDefStruct);

    while(1)

    {
        HAL_GPIO_TogglePin(&GPIO_InitTypeDefStruct,GPIO_PIN_1);

    }

It doesn't seem to work though..I've gone through the header file and c file of the GPIO which explains how to go about setting the pin, although even following this to the bone, it just stays low. Where am I going wrong?

Thanks in advance for any help

Body:
The

    HAL_GPIO_TogglePin(&GPIO_InitTypeDefStruct,GPIO_PIN_1);

should have been

HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_1);


问:
Loop inside React JSX
I'm trying to do something like the following in React JSX (where ObjectRow is a separate component):

```<code><tbody>
    for (var i=0; i < numrows; i++) {
        <ObjectRow/>
    }
</tbody>
</code>```

I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times).

答:
When I want to add a certain number of components, I use a helper function.

Define a function that returns JSX:

```<code>const myExample = () => {
    let myArray = []
    for(let i = 0; i<5;i++) {
        myArray.push(<MyComponent/>)
    }
    return myArray
}

//... in JSX

<tbody>
    {myExample()}
</tbody>
</code>```

Title: Loop inside React JSX

Body:
I'm trying to do something like the following in React JSX (where ObjectRow is a separate component):

    for (var i=0; i < numrows; i++) {
        <ObjectRow/>
    }

I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times).

Body:
When I want to add a certain number of components, I use a helper function.

Define a function that returns JSX:

const myExample = () => {
    let myArray = []
    for(let i = 0; i<5;i++) {
        myArray.push(<MyComponent/>)
    }
    return myArray
}

//... in JSX

<tbody>
    {myExample()}
</tbody>


问:
Specifying Maven's local repository location as a CLI parameter
Is it possible to set the location of the local Maven repository as argument on the Maven command line?

The thing is that I don't use the default one in ~/.m2/repository. However I checked out some project that is being built with its own settings with -s settings.xml. That settings.xml doesn't specify my local repository, so Maven uses uses ~/.m2/repository again... I would like to use a non-default local repository location without having to add a <localRepository> element in the project's settings.xml

I've tried

-DlocalRepository="..."

$mvn invoker:run -s settings.xml clean install -DskipTests -DlocalRepositoryPath=

-Dsettings.localRepository

but none of these options works.

So I think I have to decide whether I will be modifying a third party settings.xml or move my local repo to ~

答:
For git:

```<code>alias mvn='mvn "-Dmaven.repo.local=$(git rev-parse --show-toplevel)/.m2/repository"'
</code>```

This uses a separate maven repository in each git repository

Body:
For git:

alias mvn='mvn "-Dmaven.repo.local=$(git rev-parse --show-toplevel)/.m2/repository"'

This uses a separate maven repository in each git repository


问:
Save/Pass/GET event after page reload
I try to open a cordova-app with custom-url-scheme.

When i use it after triggering an event i works fine like this:

```<code><input id="myInput" onkeydown="checkKey(event);"/>

function checkKey(event) {
    if (event.which == 13 || event.keyCode == 13) {
        window.open('blablabla'); // call the App
    }
};
</code>```

Unfortunately in my case by pressing the Enter-key, the value has to be checked by a backend system, wich then reloads the page.

So i tried this:

```<code>document.addEventListener('DOMContentLoaded', function() {
   window.open('blablabla'); // call the App
}, false);
</code>```

The problem here is that have no active event, so chrome makes a navigation.block an the App cannot be opened.

Is there a way not to lose the event by reloading the page?

答:
Instead of DOMContentLoaded event you could just use ondeviceready event. In that, on initial page's (index page) onDeviceReady() you can do your validations and call the first page of the app after that.

We do this generally for login pages before directing users to main page of the app. For example -

```<code>document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    //get the value
    //check event through backend system
     window.open('blablabla');  //call the App's first page
}
</code>```

Quoting from [deviceready][1] Documentation -

The deviceready event behaves somewhat differently from others. Any event handler registered after the deviceready event fires has its callback function called immediately.

Title: Save/Pass/GET event after page reload

Body:
I try to open a cordova-app with custom-url-scheme.

When i use it after triggering an event i works fine like this:

<input id="myInput" onkeydown="checkKey(event);"/>

function checkKey(event) {
    if (event.which == 13 || event.keyCode == 13) {
        window.open('blablabla'); // call the App
    }
};

Unfortunately in my case by pressing the Enter-key, the value has to be checked by a backend system, wich then reloads the page.

So i tried this:

document.addEventListener('DOMContentLoaded', function() {
   window.open('blablabla'); // call the App
}, false);

The problem here is that have no active event, so chrome makes a navigation.block an the App cannot be opened.

Is there a way not to lose the event by reloading the page?

Body:
Instead of DOMContentLoaded event you could just use ondeviceready event. In that, on initial page's (index page) onDeviceReady() you can do your validations and call the first page of the app after that.

We do this generally for login pages before directing users to main page of the app. For example -

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    //get the value
    //check event through backend system
     window.open('blablabla');  //call the App's first page
}

Quoting from [deviceready][1] Documentation -

The deviceready event behaves somewhat differently from others. Any event handler registered after the deviceready event fires has its callback function called immediately.


问:
How to present frequencies and cumulative frequencies side by side (dodge position) in barchart with ggplot
I am trying to present frequencies and cumulative frequencies side by side in a bar chart in ggplot but what I end up is overlapping bars.

For a reproducible example:

```<code>data(mtcars)
setDT(mtcars)

data <- mtcars[, .(Total = .N), by = carb][order(carb)][, .(carb, freq = Total/sum(Total))][
  , .(carb, freq, cumfreq = cumsum(freq))]

ggplot(data, aes(x = carb)) +
  geom_bar(fill = "red", alpha = 0.5, stat = "identity" , aes(y = freq), position = position_dodge()) +
  geom_bar(fill = "blue", alpha = 0.5, stat = "identity" , aes(y = cumfreq), position = position_dodge())
</code>```

Your advice will be appreciated.

答: That's a good question! It's common to just add layers when it comes to different geometry types, but I've always had to regroup/reshape the data to plot grouped/dodged bars. Nonetheless, I believe you can get what you want (no data wrangling) using plotly: https://plot.ly/~luana.marinho/114#plot. Not the most sophisticated solution, agreed, but it's fast and you can snoop into the R code there.</p>

Body:
I am trying to present frequencies and cumulative frequencies side by side in a bar chart in ggplot but what I end up is overlapping bars.

For a reproducible example:

data(mtcars)
setDT(mtcars)

data <- mtcars[, .(Total = .N), by = carb][order(carb)][, .(carb, freq = Total/sum(Total))][
  , .(carb, freq, cumfreq = cumsum(freq))]

ggplot(data, aes(x = carb)) +
  geom_bar(fill = "red", alpha = 0.5, stat = "identity" , aes(y = freq), position = position_dodge()) +
  geom_bar(fill = "blue", alpha = 0.5, stat = "identity" , aes(y = cumfreq), position = position_dodge())

Your advice will be appreciated.


问:
How to remove all characters after a certain character in bash for a whole file
I've found a couple of questions like this, but they don't talk about using a whole file.

I've got a file of packages from my old OS, but I factory reset it and am hoping to make sure that all of these packages are installed.

See the file here

However I don't need all of the extra information after the /, I only want the names of the packages, so that I can sudo apt installcat packages.formatted`.

How can I remove this using a tool such as grep.

Example

```<code>nautilus/oldstable,now 3.14.1-2 armhf [installed]
minecraft-pi/stable,now 0.1.1-4 armhf [installed]
</code>```

becomes

```<code>nautilus
minecraft-pi
</code>```

NOTE: If you can find a better way for me to install all of these packages, you can answer with that as well,  but that is not the main point of this question

答:
You can use awk for that (or cut). Essentially delimiting the file using that character and returning only the first field:

```<code>awk -F"/" '{print $1}' yourfile > outputfile
</code>```

This can be piped instead, too:

```<code>awk -F"/" '{print $1}' packages.txt | sudo apt install
</code>```

Assuming apt can read from stdin like that.

Body:
I've found a couple of questions like this, but they don't talk about using a whole file.

I've got a file of packages from my old OS, but I factory reset it and am hoping to make sure that all of these packages are installed.

See the file here

However I don't need all of the extra information after the /, I only want the names of the packages, so that I can sudo apt installcat packages.formatted`.

How can I remove this using a tool such as grep.

Example

nautilus/oldstable,now 3.14.1-2 armhf [installed]
minecraft-pi/stable,now 0.1.1-4 armhf [installed]

becomes

nautilus
minecraft-pi

NOTE: If you can find a better way for me to install all of these packages, you can answer with that as well,  but that is not the main point of this question

Body:
You can use awk for that (or cut). Essentially delimiting the file using that character and returning only the first field:

awk -F"/" '{print $1}' yourfile > outputfile

This can be piped instead, too:

awk -F"/" '{print $1}' packages.txt | sudo apt install

Assuming apt can read from stdin like that.


问:
How does laravel model relationships work in core?
Consider this example

```<code>class SomeClass extends Model{
    public function user(){
        return $this->belongsTo('App\User');
    }
}
$instance = SomeClass::findOrFail(1);
$user = $instance->user;
</code>```

how do laravel know(i mean in core) that $instance->user (without brackets) return related model?

答:
Basically, whenever you try to access a property from a model, the __get magic method is invoked and it's something like the following:

public function __get($key)
{
    return $this->getAttribute($key);
}
```

<p>As you can see that, the <code>__get</code> magic method calls another user defined method (<code>getAttribute</code>) which is something like the following:</p>

<pre class="lang-php prettyprint-override"><code>public function getAttribute($key)
{
    if (! $key) {
        return;
    }

    // If the attribute exists in the attribute array or has a "get" mutator we will
    // get the attribute's value. Otherwise, we will proceed as if the developers
    // are asking for a relationship's value. This covers both types of values.
    if (array_key_exists($key, $this->attributes) ||
        $this->hasGetMutator($key)) {
        return $this->getAttributeValue($key);
    }

    // Here we will determine if the model base class itself contains this given key
    // since we do not want to treat any of those methods are relationships since
    // they are all intended as helper methods and none of these are relations.
    if (method_exists(self::class, $key)) {
        return;
    }

    return $this->getRelationValue($key);
}
</code>```

In this case (for relation), the last line return $this->getRelationValue($key); is responsible for retrieving a relationship. Keep reading the source code, track each function calls and you'll get the idea. Start from Illuminate\Database\Eloquent\Model.php::__get method. Btw, this code is taken from latest version of Laravel but ultimately the process is same.

Short summary: Laravel at first checks if the property/$kay being accessed is a property of a model or if it's an accessor method defined in the model itself then it simply returns that property otherwise it keeps further checking and if it founds a method defined in the model using that name (property/$kay) then it simply returns the relationship.

Body:
Consider this example

class SomeClass extends Model{
    public function user(){
        return $this->belongsTo('App\User');
    }
}
$instance = SomeClass::findOrFail(1);
$user = $instance->user;

how do laravel know(i mean in core) that $instance->user (without brackets) return related model?

Body:
Basically, whenever you try to access a property from a model, the __get magic method is invoked and it's something like the following:

public function __get($key)
{
    return $this->getAttribute($key);
}

As you can see that, the __get magic method calls another user defined method (getAttribute) which is something like the following:

public function getAttribute($key)
{
    if (! $key) {
        return;
    }

    // If the attribute exists in the attribute array or has a "get" mutator we will
    // get the attribute's value. Otherwise, we will proceed as if the developers
    // are asking for a relationship's value. This covers both types of values.
    if (array_key_exists($key, $this->attributes) ||
        $this->hasGetMutator($key)) {
        return $this->getAttributeValue($key);
    }

    // Here we will determine if the model base class itself contains this given key
    // since we do not want to treat any of those methods are relationships since
    // they are all intended as helper methods and none of these are relations.
    if (method_exists(self::class, $key)) {
        return;
    }

    return $this->getRelationValue($key);
}

In this case (for relation), the last line return $this->getRelationValue($key); is responsible for retrieving a relationship. Keep reading the source code, track each function calls and you'll get the idea. Start from Illuminate\Database\Eloquent\Model.php::__get method. Btw, this code is taken from latest version of Laravel but ultimately the process is same.

Short summary: Laravel at first checks if the property/$kay being accessed is a property of a model or if it's an accessor method defined in the model itself then it simply returns that property otherwise it keeps further checking and if it founds a method defined in the model using that name (property/$kay) then it simply returns the relationship.


问:
JS Sorting array of objects by a variable property
I'm trying to sort an array of objects, but the property I'm sorting it by is not known beforehand.  It's stored as a variable.

```<code>var items = [
    {foo: "4", bar: "5"},
    {foo: "7", bar: "1"},
    {foo: "5", bar: "9"},
];

var whatToSort = "";
if (Math.random() > .5) {
    whatToSort = "foo"
} else {
    whatToSort = "bar"
};

items.sort(function(a, b){
    return b.whatToSort - a.whatToSort;
};
</code>```

This works if my sort() function returns b.bar - a.bar but not if the variable whatToSort is used.  Is there a way to do this?

答:
You need to use the square bracket notation:

```<code>return b[whatToSort] - a[whatToSort];
</code>```

Otherwise, the JS engine thinks you are comparing properties that are literally named "whatToSort". This is one of the most common hangups people have when learning JavaScript. When you need to access a property of an object, but you are not sure what that property will be until runtime, you need to use the square bracket notation.

```<code>var myObject = {
  foo: 1,
  bar: 2
};
var myKey = 'foo';

myObject.foo;      // 1
myObject.bar;      // 2
myObject.myKey;    // undefined
myObject['foo'];   // 1
myObject['bar'];   // 2
myObject['myKey']; // undefined
myObject[myKey];   // 1
</code>```

Body:
I'm trying to sort an array of objects, but the property I'm sorting it by is not known beforehand.  It's stored as a variable.

var items = [
    {foo: "4", bar: "5"},
    {foo: "7", bar: "1"},
    {foo: "5", bar: "9"},
];

var whatToSort = "";
if (Math.random() > .5) {
    whatToSort = "foo"
} else {
    whatToSort = "bar"
};

items.sort(function(a, b){
    return b.whatToSort - a.whatToSort;
};

This works if my sort() function returns b.bar - a.bar but not if the variable whatToSort is used.  Is there a way to do this?

Body:
You need to use the square bracket notation:

return b[whatToSort] - a[whatToSort];

Otherwise, the JS engine thinks you are comparing properties that are literally named "whatToSort". This is one of the most common hangups people have when learning JavaScript. When you need to access a property of an object, but you are not sure what that property will be until runtime, you need to use the square bracket notation.

var myObject = {
  foo: 1,
  bar: 2
};
var myKey = 'foo';

myObject.foo;      // 1
myObject.bar;      // 2
myObject.myKey;    // undefined
myObject['foo'];   // 1
myObject['bar'];   // 2
myObject['myKey']; // undefined
myObject[myKey];   // 1


问:
Use asterisk as client to act as a soft phone
I have an account with vonage and I am able to make phone calls from my computer entering the following information into my soft phone (zoiper):

When entering that information (domain,usrename and password) into my soft phone settings I am able to make phone calls and also receive. At this point everything works great

Now my question is how can I make outbound calls from asterisk using that same information that I got from vonage? I would like my soft phone to connect to asterisk, then asterisk making the outbound call.

This is what I have tried:

This is how my sip.conf looks like:

```<code>[general]
   tcpenable=yes
   etc.....

 [SoftPhone1]
   secret=MySecretPassword
   context=MainContext
   type=friend
   disallow=all
   transport=udp,tcp
   etc...

 [vonage-test]
   type=peer
   host=sip-55623.accounts.vocalocity.com
   secret=*********
   username=VH283034
   disallow=all
   allow=ulaw
   transport=udp,tcp
   dtmfmode=auto
   insecure=invite
</code>```

and on my extensions.conf

```<code>[general]
  static=yes
  etc...

[MainContext] ; this is the context where SoftPhone1 is registered
  exten => 100,1,NoOp(Testing to see if we can make outbound call) ; just write to the console
  same => n,Dial(SIP/3051234567@vonage-test) ; make phone call to 3051234567
  same => n,Hangup()

  etc...
</code>```

when I dial extension 100 the call never goes to phone number 3051234567. Why?

答:
1) In EVERY section you should put ONE transport

2) you should correctly setup headers, like fromuser etc. For more info ask vonage

3) you should do registration,see register =>  tag.

Body:
I have an account with vonage and I am able to make phone calls from my computer entering the following information into my soft phone (zoiper):

When entering that information (domain,usrename and password) into my soft phone settings I am able to make phone calls and also receive. At this point everything works great

Now my question is how can I make outbound calls from asterisk using that same information that I got from vonage? I would like my soft phone to connect to asterisk, then asterisk making the outbound call.

This is what I have tried:

This is how my sip.conf looks like:

[general]
   tcpenable=yes
   etc.....

 [SoftPhone1]
   secret=MySecretPassword
   context=MainContext
   type=friend
   disallow=all
   transport=udp,tcp
   etc...

 [vonage-test]
   type=peer
   host=sip-55623.accounts.vocalocity.com
   secret=*********
   username=VH283034
   disallow=all
   allow=ulaw
   transport=udp,tcp
   dtmfmode=auto
   insecure=invite

and on my extensions.conf

[general]
  static=yes
  etc...

[MainContext] ; this is the context where SoftPhone1 is registered
  exten => 100,1,NoOp(Testing to see if we can make outbound call) ; just write to the console
  same => n,Dial(SIP/3051234567@vonage-test) ; make phone call to 3051234567
  same => n,Hangup()

  etc...

when I dial extension 100 the call never goes to phone number 3051234567. Why?


问:
r identify two populations in scatterplot
I am comparing two rasters with a simple scatter plot of cell-by-cell plot, and find that I have two seemingly different populations:

Now I am trying to extract the locations of each of these populations (by isolating the row IDs, e.g.) so I can see where they fall in the rasters and maybe understand why I get this behavior.    Here is a reproducible example:

X <- seq(1,1000,1)

Z <- runif(1000, 1, 2)

A = c(1.2 * X * Z + 100)

B = c(0.6 * X * Z )

df = data.frame(X = c(X,X), Y = c(A,B))

plot(df$X,df$Y)

Also, my original data has some 1,000,000 rows, so the solution needs to support a large data frame as well.
Any ideas on how I can isolate each of these groups?

Thanks

答:
You data has a linear separating line.  You can find it with:

```<code>plot(df$X,df$Y)
Pts = locator(2)
</code>```

You will want to click on one point between the two groups down by the origin and another on the far right (between the groups).  With your data I got

```<code>Pts
$x
[1]   0.8066296 994.9723687
$y
[1]   48.56932 1255.32870

## Slope
(Pts$y[2] - Pts$y[1]) / (Pts$x[2] - Pts$x[1])
[1] 1.213841

## Draw the line to confirm
abline(48,1.2, col="red")

## use the line to distinguish the groups
Group = rep(1, nrow(df))
Group[df$X*1.2 + 48 < df$Y] = 2
plot(df, pch=20, col=Group)
</code>```

Body:
You data has a linear separating line.  You can find it with:

plot(df$X,df$Y)
Pts = locator(2)

You will want to click on one point between the two groups down by the origin and another on the far right (between the groups).  With your data I got

Pts
$x
[1]   0.8066296 994.9723687
$y
[1]   48.56932 1255.32870

## Slope
(Pts$y[2] - Pts$y[1]) / (Pts$x[2] - Pts$x[1])
[1] 1.213841

## Draw the line to confirm
abline(48,1.2, col="red")

## use the line to distinguish the groups
Group = rep(1, nrow(df))
Group[df$X*1.2 + 48 < df$Y] = 2
plot(df, pch=20, col=Group)


问:
Make a loop inside NodeJS Web server?
I'm doing a big project in NodeJS using Express and I wonder if I can make an infinite loop inside the server application. I think this cannot be accomplished in other languages such as Java (because it would stall the application) but I'm not sure about the JS behavior in this case.

The server application has to do two main tasks. The first one is to handle the web page (it has to listen for requests and stuff like that). The second one would be looping through a cluster  of arduinos via wifi in order to get some values. These values would be sent to the web page using socket.io.

So, the question is: is it possible for the server to do two tasks at the same time? I imagine the requests sent from the web page to the server as events that would stop the loop iteration, and once they are answered the loop continues.

Sorry for my bad english. Thanks in advance!

答:
You could set up your server to handle the webpage, and use a cronjob to trigger a function which queries the arduinos.

There are npm packages that enable you to define cronjobs in your javascript code. One example of these is cron

Title: Make a loop inside NodeJS Web server?


问:
Error 405 & 401 open weather map API Angularjs
trying to call data through openweathermap api
if I call it through 'GET'method.there is

405 (Method Not Allowed)

```<code>var req = {
    method: 'GET',
    url: 'http://api.openweathermap.org/data/2.5/forecast/daily?APPID=' + ApiKey + '&q=London,us',
    headers: {
        'x-api-key': ApiKey
    }
}

$http(req)
    .then(function (data) {
        console.log(data);
    }, function (err) {
        console.log(err);
    });
</code>```

答:
Use the params property to encode the search parameters:

```<code>var req = {
    method: 'GET',
    //url: 'http://api.openweathermap.org/data/2.5/forecast/daily?APPID=' + ApiKey + '&q=London,us',
    url: 'http://api.openweathermap.org/data/2.5/forecast/daily',
    params: { appid: ApiKey, q: 'London,us' }
}
</code>```

The problem is likely that the &q=London,us is illegal. The comma character needs to be percent-encoded to q=London%2Cus. Use the params property to properly encode the parameters.

Update

I tested it with my APPID (which I am not going to publish) and it worked.

Here is my DEMO on PLNKR with the APPID removed.

Body:
trying to call data through openweathermap api
if I call it through 'GET'method.there is

405 (Method Not Allowed)

var req = {
    method: 'GET',
    url: 'http://api.openweathermap.org/data/2.5/forecast/daily?APPID=' + ApiKey + '&q=London,us',
    headers: {
        'x-api-key': ApiKey
    }
}

$http(req)
    .then(function (data) {
        console.log(data);
    }, function (err) {
        console.log(err);
    });

Body:
Use the params property to encode the search parameters:

var req = {
    method: 'GET',
    //url: 'http://api.openweathermap.org/data/2.5/forecast/daily?APPID=' + ApiKey + '&q=London,us',
    url: 'http://api.openweathermap.org/data/2.5/forecast/daily',
    params: { appid: ApiKey, q: 'London,us' }
}

The problem is likely that the &q=London,us is illegal. The comma character needs to be percent-encoded to q=London%2Cus. Use the params property to properly encode the parameters.

Update

I tested it with my APPID (which I am not going to publish) and it worked.

Here is my DEMO on PLNKR with the APPID removed.


问:
SVG: append shapes along curved path
I'm currently in a situation in which I need to append text to follow a curved path in SVG.  Our goal is to allow users to dynamically enter text that will be displayed along a curved path.  Normally I would use the textPath method but the hang-up is that-- for the text to render as our designer has specified-- we need to convert the text to paths (probably using something like Opentype).  I wasn't hopeful that appending shapes to the textPath would work (it didn't) but I'm not sure where to go from here to achieve the same end.

```<code><svg viewBox="0 0 1000 300"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink">

<defs>
 <path id="MyPath"
  d="M 100 200
  C 200 100 300   0 400 100
  C 500 200 600 300 700 200
  C 800 100 900 100 900 100" />
</defs>

<use xlink:href="#MyPath" fill="none" stroke="red"  />

<text font-family="Verdana" font-size="42.5">
 <textPath xlink:href="#MyPath">
  <rect class="sq-1" height="50" width="50" x="0" y="0"/>
  <rect class="sq-2" height="50" width="50" x="100" y="0"/>
  <rect class="sq-3" height="50" width="50" x="200" y="0"/>
 </textPath>
</text>

<rect x="1" y="1" width="998" height="298" fill="none" stroke="black" stroke-width="2" />
</svg>
</code>```

Here is a fiddle for the above example.

答:
There is no way to do this in the browser - at least not built in anyway.  As I see it, your options are:

hope that there is a Javascript library out there that can convert a <textPath> to a <path>.  I'm not aware of any. JS doesn't have access to the font geometry or metrics. The library would have to parse fonts itself.

find or write a Javascript library out there that can distribute <path> elements along a <path>

Have a post-processing script on the server that runs the SVG through Inkscape, Illustrator etc to do the convert-to-path step.

Title: SVG: append shapes along curved path

Body:
I'm currently in a situation in which I need to append text to follow a curved path in SVG.  Our goal is to allow users to dynamically enter text that will be displayed along a curved path.  Normally I would use the textPath method but the hang-up is that-- for the text to render as our designer has specified-- we need to convert the text to paths (probably using something like Opentype).  I wasn't hopeful that appending shapes to the textPath would work (it didn't) but I'm not sure where to go from here to achieve the same end.

<svg viewBox="0 0 1000 300"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink">

<defs>
 <path id="MyPath"
  d="M 100 200
  C 200 100 300   0 400 100
  C 500 200 600 300 700 200
  C 800 100 900 100 900 100" />
</defs>

<use xlink:href="#MyPath" fill="none" stroke="red"  />

<text font-family="Verdana" font-size="42.5">
 <textPath xlink:href="#MyPath">
  <rect class="sq-1" height="50" width="50" x="0" y="0"/>
  <rect class="sq-2" height="50" width="50" x="100" y="0"/>
  <rect class="sq-3" height="50" width="50" x="200" y="0"/>
 </textPath>
</text>

<rect x="1" y="1" width="998" height="298" fill="none" stroke="black" stroke-width="2" />
</svg>

Here is a fiddle for the above example.