问:
Vue component $(...).owlCarousel is not a function
I have the next issue.

I'm using Laravel 5.4 with vue components. I want to use owl carousel 2 in my app.

I have the next code in a script tag and it works:

```<code>$(".owl-1").owlCarousel({items: 1, singleItem:true, loop: true});

$(".owl-2").owlCarousel({items: 1, singleItem:true, loop: true,mouseDrag: false, touchDrag: false, pullDrag: false, freeDrag: false});

$(".owl-1").on('change.owl.carousel', function(event) {
 if (event.namespace && event.property.name === 'position') {
 var target = event.relatedTarget.relative(event.property.value, true);
     $(".owl-2").owlCarousel('to', target, 300, true);
 }
});
</code>```

When I load the page when it is my owl html structure works very well, but when I try to use owl carousel inside my vue component it show me the next error.

```<code>$(...).owlCarousel is not a function.
</code>```

I have the next code on the bottom of my html

```<code><script src="/assets/js/owl.carousel.min.js"></script>
<script src="/assets/js/main.js"></script>
</code>```

I'm don't know if I need to intall it with npm, I was looking in npm and I didn't find it then I add the css and js files in my assets files.

Any ideas?
Thanks in advance.

答:
I solved this in the next way:

I checked the link who aks gave me, thanks for that.

I declared in my watch poperty the name of my v-model that in my case was houses, and in my created method I call the values from an api and in my watch detects the change and then I initialized the owl carousel with window. before the jquery selector.

Also I add the import of owl.carousel

```<code>import 'owl.carousel'

export default {

data(){
 return {
     houses: []
   }
 },
created(){

  //Call api
  this.houses = response.data.houses;
},
watch: {

        /*
            Carousel Structure
         */
        houses() {

            let owl  = window.$(".owl-1");
            let owl2 = window.$(".owl-2");

            owl.owlCarousel({items: 1, singleItem:true, loop: true});;

            owl2.owlCarousel({items: 1, singleItem:true, loop: true,mouseDrag: false, touchDrag: false, pullDrag: false, freeDrag: false});
        }
    }
  }
</code>```

I hope helps to someone else.

Body:
I have the next issue.

I'm using Laravel 5.4 with vue components. I want to use owl carousel 2 in my app.

I have the next code in a script tag and it works:

$(".owl-1").owlCarousel({items: 1, singleItem:true, loop: true});

$(".owl-2").owlCarousel({items: 1, singleItem:true, loop: true,mouseDrag: false, touchDrag: false, pullDrag: false, freeDrag: false});

$(".owl-1").on('change.owl.carousel', function(event) {
 if (event.namespace && event.property.name === 'position') {
 var target = event.relatedTarget.relative(event.property.value, true);
     $(".owl-2").owlCarousel('to', target, 300, true);
 }
});

When I load the page when it is my owl html structure works very well, but when I try to use owl carousel inside my vue component it show me the next error.

$(...).owlCarousel is not a function.

I have the next code on the bottom of my html

I'm don't know if I need to intall it with npm, I was looking in npm and I didn't find it then I add the css and js files in my assets files.

Any ideas?
Thanks in advance.

Body:
I solved this in the next way:

I checked the link who aks gave me, thanks for that.

I declared in my watch poperty the name of my v-model that in my case was houses, and in my created method I call the values from an api and in my watch detects the change and then I initialized the owl carousel with window. before the jquery selector.

Also I add the import of owl.carousel

import 'owl.carousel'

export default {

data(){
 return {
     houses: []
   }
 },
created(){

  //Call api
  this.houses = response.data.houses;
},
watch: {

        /*
            Carousel Structure
         */
        houses() {

            let owl  = window.$(".owl-1");
            let owl2 = window.$(".owl-2");

            owl.owlCarousel({items: 1, singleItem:true, loop: true});;

            owl2.owlCarousel({items: 1, singleItem:true, loop: true,mouseDrag: false, touchDrag: false, pullDrag: false, freeDrag: false});
        }
    }
  }

I hope helps to someone else.


来源: stackexchange

问:
how to print current user's ip address in php 7.1.1
I am trying to get current users ip address using {$_SERVER['REMOTE_ADDR']} or {getenv('REMOTE_ADDR')}, in both of the cases i am getting ::1 .
I am using php 7.1.1, can any one help how i can get current ip address of current user.</p>

答:
If your using your local server it will always be ::1 or the local ip address.

```<code>$_SERVER['REMOTE_ADDR']
</code>```

will return the ip when its on a server outside of your localnetwork.

ContentLicense: CC BY-SA 3.0

Body:
If your using your local server it will always be ::1 or the local ip address.

$_SERVER['REMOTE_ADDR']

will return the ip when its on a server outside of your localnetwork.


问:
is there a way lazy load a component in angular 2 dart?
I have a component that uses another component with a ngIf statement. I would like to only load the second component once the ngIf evaluates to true.

EDIT: found an article that can almost do what I need:
https://medium.com/@matanlurey/lazy-loading-with-angular-dart-14f58004f988. However, after the library loaded, it takes the whole view of the component. In my case, I need to insert it into a specific place in the html of the parent component.

Something like:

```<code>import '../other/edit_component.dart' deferred as otherEdit;

@Component(
    selector: 'edit-component',
    template: '<other-component *ngIf="canOther"></other-component>
    <button type="button" (click)="go()"></button>',
    directives: const [
      otherEdit.OtherComponent
    ]
)
class EditComponent {
  @Input()
  bool canOther = false;

  go() {
    otherEdit.loadLibrary();
    canOther = true;
  }
}
</code>```

答: I do not think you can do it directly. What you can do instead is using DynamicComponent from Angular2_components and pass the type after lazily loading it.</p>

Body:
I have a component that uses another component with a ngIf statement. I would like to only load the second component once the ngIf evaluates to true.

EDIT: found an article that can almost do what I need:
https://medium.com/@matanlurey/lazy-loading-with-angular-dart-14f58004f988. However, after the library loaded, it takes the whole view of the component. In my case, I need to insert it into a specific place in the html of the parent component.

Something like:

import '../other/edit_component.dart' deferred as otherEdit;

@Component(
    selector: 'edit-component',
    template: '<other-component *ngIf="canOther"></other-component>
    <button type="button" (click)="go()"></button>',
    directives: const [
      otherEdit.OtherComponent
    ]
)
class EditComponent {
  @Input()
  bool canOther = false;

  go() {
    otherEdit.loadLibrary();
    canOther = true;
  }
}


问:
Is it possible to force a reload of a thread_local variable after migration across kernel threads?
I am implementing user threading on top of kernel and threads and observed that, when a user thread migrates between kernel threads, thread_local variables are read from the previous kernel location even when the variables are also tagged as volatile.

Since the compiler merely sees a user-level swapcontext as a function call, the example below demonstrates the problem with a simple function call.

```<code>#include <stdio.h>

struct Foo {
    int x;
    int y;
};

__thread Foo* volatile foo;

void bar() {
    asm("nop");
}
void f() {
    foo->x = 5;
    bar();
    asm volatile("":::"memory");
    // We desire a second computation of the address of foo here as an offset
    // from the FS register.
    foo->y = 7;
}

int main(){
    foo = new Foo;
    f();
    delete foo;
}
</code>```

Next we run the following commands to compile and disassemble. Note that the -fPIC flag seems necessary to reproduce this problem, and is also required for my use case because I am building a library. Assume the code above is in a file called TL.cc

```<code>g++ -std=c++11 -O3  -fPIC  -Wall -g TL.cc   -o TL
objdump -d TL
</code>```

Here is the assembly dump for the function f().

```<code>  400760:       53                      push   %rbx
  # Notice this computation happens only once.
  400761:       64 48 8b 04 25 00 00    mov    %fs:0x0,%rax
  400768:       00 00
  40076a:       48 8d 80 f8 ff ff ff    lea    -0x8(%rax),%rax
  400771:       48 89 c3                mov    %rax,%rbx
  400774:       48 8b 00                mov    (%rax),%rax
  400777:       c7 00 05 00 00 00       movl   $0x5,(%rax)
  40077d:       e8 ce ff ff ff          callq  400750 <_Z3barv>
  # Observe that the value of rbx came from before the function call,
  # so if the function bar() actually returned on a different kernel
  # thread, we would be referencing the original kernel thread's
  # version of foo, instead of the new kernel thread's version.
  400782:       48 8b 03                mov    (%rbx),%rax
  400785:       c7 40 04 07 00 00 00    movl   $0x7,0x4(%rax)
  40078c:       5b                      pop    %rbx
  40078d:       c3                      retq
  40078e:       66 90                   xchg   %ax,%ax
</code>```

We observe the register rax is being reloaded from memory, but that the memory location was determined before the call to bar().

Is there a way to force a reload of the address of the variable as an offset from the current value of the fs register?

I am fine with using gcc-specific hacks if those exist.

Here is the output g++ --version

```<code>g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

答:
I wrote the following hack which forces a reload of the TLS in all the cases that I tested, but would appreciate feedback on all the ways it may be broken.

```<code>#define SafeTLS(TypeName, name) \
struct name##_SafeClass { \
    name##_SafeClass& \
    __attribute__ ((noinline)) \
    operator=(const TypeName& other) { \
        asm (""); \
        name = const_cast<TypeName&>(other); \
        return *this; \
    } \
    TypeName& \
    __attribute__ ((noinline)) \
    operator->() { \
       asm (""); \
        return get(); \
    } \
    operator TypeName() { return get(); } \
    TypeName& \
    __attribute__ ((noinline)) \
    get() { \
        asm (""); \
        return name; \
    } \
   \
    TypeName* \
    operator&() { \
        asm (""); \
        return &name; \
    } \
} name##_Safe
</code>```

Here is a more sophisticated test case that uses this.

```<code>#include <stdio.h>
#include "TLS.h"

struct Foo {
    int x;
    int y;
};

__thread Foo* volatile foo;
__thread int bar;

SafeTLS(Foo* volatile, foo);
SafeTLS(int, bar);

void f2() {
    asm("nop");
}
void f() {
    foo_Safe->x = 5;
    f2();
    asm volatile("":::"memory");
    // We desire a second computation of the address of foo here as an offset
    // from the FS register.
    (*foo_Safe).y = 7;
    bar = 7;
    printf("%d\n", bar);
    printf("%d %d\n", foo->x, foo->y);

    bar = 8;
    printf("%d\n", bar_Safe.get());
}

int main(){
    foo = new Foo;
    f();
    delete foo;
}
</code>```

Body:
I am implementing user threading on top of kernel and threads and observed that, when a user thread migrates between kernel threads, thread_local variables are read from the previous kernel location even when the variables are also tagged as volatile.

Since the compiler merely sees a user-level swapcontext as a function call, the example below demonstrates the problem with a simple function call.

#include <stdio.h>

struct Foo {
    int x;
    int y;
};

__thread Foo* volatile foo;

void bar() {
    asm("nop");
}
void f() {
    foo->x = 5;
    bar();
    asm volatile("":::"memory");
    // We desire a second computation of the address of foo here as an offset
    // from the FS register.
    foo->y = 7;
}

int main(){
    foo = new Foo;
    f();
    delete foo;
}

Next we run the following commands to compile and disassemble. Note that the -fPIC flag seems necessary to reproduce this problem, and is also required for my use case because I am building a library. Assume the code above is in a file called TL.cc

g++ -std=c++11 -O3  -fPIC  -Wall -g TL.cc   -o TL
objdump -d TL

Here is the assembly dump for the function f().

  400760:       53                      push   %rbx
  # Notice this computation happens only once.
  400761:       64 48 8b 04 25 00 00    mov    %fs:0x0,%rax
  400768:       00 00
  40076a:       48 8d 80 f8 ff ff ff    lea    -0x8(%rax),%rax
  400771:       48 89 c3                mov    %rax,%rbx
  400774:       48 8b 00                mov    (%rax),%rax
  400777:       c7 00 05 00 00 00       movl   $0x5,(%rax)
  40077d:       e8 ce ff ff ff          callq  400750 <_Z3barv>
  # Observe that the value of rbx came from before the function call,
  # so if the function bar() actually returned on a different kernel
  # thread, we would be referencing the original kernel thread's
  # version of foo, instead of the new kernel thread's version.
  400782:       48 8b 03                mov    (%rbx),%rax
  400785:       c7 40 04 07 00 00 00    movl   $0x7,0x4(%rax)
  40078c:       5b                      pop    %rbx
  40078d:       c3                      retq
  40078e:       66 90                   xchg   %ax,%ax

We observe the register rax is being reloaded from memory, but that the memory location was determined before the call to bar().

Is there a way to force a reload of the address of the variable as an offset from the current value of the fs register?

I am fine with using gcc-specific hacks if those exist.

Here is the output g++ --version

g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Body:
I wrote the following hack which forces a reload of the TLS in all the cases that I tested, but would appreciate feedback on all the ways it may be broken.

#define SafeTLS(TypeName, name) \
struct name##_SafeClass { \
    name##_SafeClass& \
    __attribute__ ((noinline)) \
    operator=(const TypeName& other) { \
        asm (""); \
        name = const_cast<TypeName&>(other); \
        return *this; \
    } \
    TypeName& \
    __attribute__ ((noinline)) \
    operator->() { \
       asm (""); \
        return get(); \
    } \
    operator TypeName() { return get(); } \
    TypeName& \
    __attribute__ ((noinline)) \
    get() { \
        asm (""); \
        return name; \
    } \
   \
    TypeName* \
    operator&() { \
        asm (""); \
        return &name; \
    } \
} name##_Safe

Here is a more sophisticated test case that uses this.

#include <stdio.h>
#include "TLS.h"

struct Foo {
    int x;
    int y;
};

__thread Foo* volatile foo;
__thread int bar;

SafeTLS(Foo* volatile, foo);
SafeTLS(int, bar);

void f2() {
    asm("nop");
}
void f() {
    foo_Safe->x = 5;
    f2();
    asm volatile("":::"memory");
    // We desire a second computation of the address of foo here as an offset
    // from the FS register.
    (*foo_Safe).y = 7;
    bar = 7;
    printf("%d\n", bar);
    printf("%d %d\n", foo->x, foo->y);

    bar = 8;
    printf("%d\n", bar_Safe.get());
}

int main(){
    foo = new Foo;
    f();
    delete foo;
}


问:
com.ibm.msg.client.jms.DetailedJMSException: JMSWMQ0018: Failed to connect to queue manager 'xxx' with connection mode 'yyy' and host name 'zzz'
JMS app requires seven parameters to make successful SSL connection with MQ series given here,
https://github.com/ibm-messaging/mq-tls-ssl-wizard/blob/master/com.ibm.mq.ssl-wizard/src/tlswizard/samples/SSLSampleJMS.java

I am trying to interpret these parameters,

Conname- the connection name of the server queue manager in the same format as the CONNAME parameter on the MQSC DEFINE CHANNEL command, but without the port specified.

I guess this is host name

Port - the connection port of the server queue manager.

This is port number

SvrconnChannelName - the name of the server connection channel on the server queue manager with which the sample program will try to connect.

QMgrName - the name of the server queue manager.

SSLCiph - the SSL CipherSpec.

I am using SSL_RSA_WITH_AES_256_CBC_SHA.

SSLKeyr - the name of a single store, which is both the keystore and truststore.

I generated myjksfile.jks using mycertfile.cert using mypassword with below command and provided path of this file in program as "C:\Users\abc\myjksfile.jks",

keytool -import -trustcacerts -keystore myjksfile.jks -storepass changeit -noprompt -alias ibmWebSphereMQUTQX -file C:\mqlib\mycertfile.cert

SSLKeyrPassword - the SSL key repository password
the password which I used to generate myjksfile.jks file

Running above program with these seven parameters results this exception,

```<code>com.ibm.msg.client.jms.DetailedJMSException: JMSWMQ0018: Failed to connect to
queue manager 'XXXX' with connection mode 'Client' and host name
'xxxx.yyyyyy.com(XXXXX)'.Check the queue manager is started and if running in
client mode, check there is a listener running. Please see the linked
exception for more information. at
com.ibm.msg.client.wmq.common.internal.Reason.reasonToException
(Reason.java:580) at
com.ibm.msg.client.wmq.common.internal.Reason.createException
(Reason.java:216) at com.ibm.msg.client.wmq.internal.WMQConnection.<init>
(WMQConnection.java:431) at
com.ibm.msg.client.wmq.factories.WMQConnectionFactory.
createV7ProviderConnection(WMQConnectionFactory.java:6789) at
com.ibm.msg.client.wmq.factories.WMQConnectionFactory.
createProviderConnection(WMQConnectionFactory.java:6157)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl.
createConnection(JmsConnectionFactoryImpl.java:285)
at com.ibm.mq.jms.MQConnectionFactory.createCommonConnection
(MQConnectionFactory.java:6126) at
com.ibm.mq.jms.MQQueueConnectionFactory.createQueueConnection
(MQQueueConnectionFactory.java:115) at
SSLSampleJMS.runSample(SSLSampleJMS.java:176)
at SSLSampleJMS.main(SSLSampleJMS.java:135)
Caused by: com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with
compcode '2' ('MQCC_FAILED') reason '2393' ('MQRC_SSL_INITIALIZATION_ERROR').
at com.ibm.msg.client.wmq.common.internal.Reason.createException
(Reason.java:204)... 8 more
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2393;AMQ9204: Connection to
host 'xxxx.yyyyyy.com(XXXXX)' rejected.
[1=com.ibm.mq.jmqi.JmqiException[CC=2;RC=2393;AMQ9771: SSL handshake failed.
[1=java.lang.IllegalArgumentException[Cannot support
SSL_RSA_WITH_AES_256_CBC_SHA with currently installed
providers],3=xxxx.yyyyyy.com/XX.XXX.XXX.XXX:XXXXX (xxxx.yyyyyy.com),4=SSLSocket.createSocket,5=default]],3=xxxx.yyyyyy.com(XXXXX),5=RemoteTCPConnection.makeSocketSecure]
at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:2098)
at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1347)
at com.ibm.msg.client.wmq.internal.WMQConnection.<init>(WMQConnection.java:350)
... 7 more
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2393;AMQ9771: SSL handshake
failed. [1=java.lang.IllegalArgumentException[Cannot support
SSL_RSA_WITH_AES_256_CBC_SHA with currently installed
providers],3=xxxx.yyyyyy.com/XX.XXX.XXX.XXX:XXXXX
(xxxx.yyyyyy.com),4=SSLSocket.createSocket,5=default]
at com.ibm.mq.jmqi.remote.impl.RemoteTCPConnection.makeSocketSecure
(RemoteTCPConnection.java:2001) at com.ibm.mq.jmqi.remote.impl.
RemoteTCPConnection.connnectUsingLocalAddress(RemoteTCPConnection.java:855)
at com.ibm.mq.jmqi.remote.impl.RemoteTCPConnection.protocolConnect
(RemoteTCPConnection.java:1262) at
com.ibm.mq.jmqi.remote.impl.RemoteConnection.connect
(RemoteConnection.java:714) at
com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.
getSessionFromNewConnection(RemoteConnectionSpecification.java:356)
at com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.
getSession(RemoteConnectionSpecification.java:265)
at com.ibm.mq.jmqi.remote.impl.RemoteConnectionPool.
getSession(RemoteConnectionPool.java:144)
at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1709)
... 9 more
Caused by: java.lang.IllegalArgumentException: Cannot support
SSL_RSA_WITH_AES_256_CBC_SHA with currently installed providers
at com.ibm.jsse2.o.<init>(o.java:29)
at com.ibm.jsse2.as.setEnabledCipherSuites(as.java:5)
at com.ibm.mq.jmqi.remote.impl.RemoteTCPConnection.makeSocketSecure
(RemoteTCPConnection.java:1994)
... 16 more
Process finished with exit code 0
</code>```

答:
Above exception was cause of using wrong cipher suite on JMS clint side. I was using SSL_RSA_WITH_AES_256_CBC_SHA cipher suite on client side and was getting "java.lang.IllegalArgumentException[Cannot support
SSL_RSA_WITH_AES_256_CBC_SHA with currently installed<br>
providers." Using correct cipher suite (TLS_RSA_WITH_AES_256_CBC_SHA) at JMS client side made handshake successful between JMS client and MQ series.
Ref: http://www-01.ibm.com/support/docview.wss?uid=swg1IV66840 </p>

Body:
JMS app requires seven parameters to make successful SSL connection with MQ series given here,
https://github.com/ibm-messaging/mq-tls-ssl-wizard/blob/master/com.ibm.mq.ssl-wizard/src/tlswizard/samples/SSLSampleJMS.java

I am trying to interpret these parameters,

Conname- the connection name of the server queue manager in the same format as the CONNAME parameter on the MQSC DEFINE CHANNEL command, but without the port specified.

I guess this is host name

Port - the connection port of the server queue manager.

This is port number

SvrconnChannelName - the name of the server connection channel on the server queue manager with which the sample program will try to connect.

QMgrName - the name of the server queue manager.

SSLCiph - the SSL CipherSpec.

I am using SSL_RSA_WITH_AES_256_CBC_SHA.

SSLKeyr - the name of a single store, which is both the keystore and truststore.

I generated myjksfile.jks using mycertfile.cert using mypassword with below command and provided path of this file in program as "C:\Users\abc\myjksfile.jks",

keytool -import -trustcacerts -keystore myjksfile.jks -storepass changeit -noprompt -alias ibmWebSphereMQUTQX -file C:\mqlib\mycertfile.cert

SSLKeyrPassword - the SSL key repository password
the password which I used to generate myjksfile.jks file

Running above program with these seven parameters results this exception,

com.ibm.msg.client.jms.DetailedJMSException: JMSWMQ0018: Failed to connect to
queue manager 'XXXX' with connection mode 'Client' and host name
'xxxx.yyyyyy.com(XXXXX)'.Check the queue manager is started and if running in
client mode, check there is a listener running. Please see the linked
exception for more information. at
com.ibm.msg.client.wmq.common.internal.Reason.reasonToException
(Reason.java:580) at
com.ibm.msg.client.wmq.common.internal.Reason.createException
(Reason.java:216) at com.ibm.msg.client.wmq.internal.WMQConnection.<init>
(WMQConnection.java:431) at
com.ibm.msg.client.wmq.factories.WMQConnectionFactory.
createV7ProviderConnection(WMQConnectionFactory.java:6789) at
com.ibm.msg.client.wmq.factories.WMQConnectionFactory.
createProviderConnection(WMQConnectionFactory.java:6157)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl.
createConnection(JmsConnectionFactoryImpl.java:285)
at com.ibm.mq.jms.MQConnectionFactory.createCommonConnection
(MQConnectionFactory.java:6126) at
com.ibm.mq.jms.MQQueueConnectionFactory.createQueueConnection
(MQQueueConnectionFactory.java:115) at
SSLSampleJMS.runSample(SSLSampleJMS.java:176)
at SSLSampleJMS.main(SSLSampleJMS.java:135)
Caused by: com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with
compcode '2' ('MQCC_FAILED') reason '2393' ('MQRC_SSL_INITIALIZATION_ERROR').
at com.ibm.msg.client.wmq.common.internal.Reason.createException
(Reason.java:204)... 8 more
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2393;AMQ9204: Connection to
host 'xxxx.yyyyyy.com(XXXXX)' rejected.
[1=com.ibm.mq.jmqi.JmqiException[CC=2;RC=2393;AMQ9771: SSL handshake failed.
[1=java.lang.IllegalArgumentException[Cannot support
SSL_RSA_WITH_AES_256_CBC_SHA with currently installed
providers],3=xxxx.yyyyyy.com/XX.XXX.XXX.XXX:XXXXX (xxxx.yyyyyy.com),4=SSLSocket.createSocket,5=default]],3=xxxx.yyyyyy.com(XXXXX),5=RemoteTCPConnection.makeSocketSecure]
at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:2098)
at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1347)
at com.ibm.msg.client.wmq.internal.WMQConnection.<init>(WMQConnection.java:350)
... 7 more
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2393;AMQ9771: SSL handshake
failed. [1=java.lang.IllegalArgumentException[Cannot support
SSL_RSA_WITH_AES_256_CBC_SHA with currently installed
providers],3=xxxx.yyyyyy.com/XX.XXX.XXX.XXX:XXXXX
(xxxx.yyyyyy.com),4=SSLSocket.createSocket,5=default]
at com.ibm.mq.jmqi.remote.impl.RemoteTCPConnection.makeSocketSecure
(RemoteTCPConnection.java:2001) at com.ibm.mq.jmqi.remote.impl.
RemoteTCPConnection.connnectUsingLocalAddress(RemoteTCPConnection.java:855)
at com.ibm.mq.jmqi.remote.impl.RemoteTCPConnection.protocolConnect
(RemoteTCPConnection.java:1262) at
com.ibm.mq.jmqi.remote.impl.RemoteConnection.connect
(RemoteConnection.java:714) at
com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.
getSessionFromNewConnection(RemoteConnectionSpecification.java:356)
at com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.
getSession(RemoteConnectionSpecification.java:265)
at com.ibm.mq.jmqi.remote.impl.RemoteConnectionPool.
getSession(RemoteConnectionPool.java:144)
at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1709)
... 9 more
Caused by: java.lang.IllegalArgumentException: Cannot support
SSL_RSA_WITH_AES_256_CBC_SHA with currently installed providers
at com.ibm.jsse2.o.<init>(o.java:29)
at com.ibm.jsse2.as.setEnabledCipherSuites(as.java:5)
at com.ibm.mq.jmqi.remote.impl.RemoteTCPConnection.makeSocketSecure
(RemoteTCPConnection.java:1994)
... 16 more
Process finished with exit code 0

Body:
Above exception was cause of using wrong cipher suite on JMS clint side. I was using SSL_RSA_WITH_AES_256_CBC_SHA cipher suite on client side and was getting "java.lang.IllegalArgumentException[Cannot support
SSL_RSA_WITH_AES_256_CBC_SHA with currently installed

providers." Using correct cipher suite (TLS_RSA_WITH_AES_256_CBC_SHA) at JMS client side made handshake successful between JMS client and MQ series.
Ref: http://www-01.ibm.com/support/docview.wss?uid=swg1IV66840


问:
C# serialize private class member
```<code>class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

Simple question yet it seems like a big mess when trying to answer it.

Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?

How do I serialize private class members?

Edit #1:

Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.

Anyway, here are more facts:

 1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.

 2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.

 3.I was hoping that there's a certain attribute like:

```<code>class Person
{
    public string m_name;
    [SerializeThat(ElementName="Age")]
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

OR (continue of fact #3) an attribute that goes on the class which would look like:

```<code>[Serializable(DoPrivate = true, DoProtected = true)]
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

Now, what can I do to achieve it?

答: Going on the assumption of a typo, I'd like to redirect you to this SO article where the solution is to use a DataContractSerializer instead.

ContentLicense: CC BY-SA 2.5

Title: C# serialize private class member

Body:
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Simple question yet it seems like a big mess when trying to answer it.

Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?

How do I serialize private class members?

Edit #1:

Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.

Anyway, here are more facts:

 1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.

 2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.

 3.I was hoping that there's a certain attribute like:

class Person
{
    public string m_name;
    [SerializeThat(ElementName="Age")]
    private int m_age; // << how do I serialize the darn little rat?
}

OR (continue of fact #3) an attribute that goes on the class which would look like:

[Serializable(DoPrivate = true, DoProtected = true)]
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Now, what can I do to achieve it?


问:
AS3: How to access children of children of children?
Is there a better (quicker, shorter or neater) way to access a child sprite (object) 3 layers or more deep? If the children have all been given names and you know the names. Is there a better way to do it than the code I made below?

var mySprite:DisplayObjectContainer = layerASprite.getChildByName("layerA") as DisplayObjectContainer;

mySprite = mySprite.getChildByName("layerB") as DisplayObjectContainer;

mySprite.getChildByName("layerC").y = 200;

答:
If they are unique you can create a "global" registry in a form of static class variables/methods:

```<code>package
{
    public class Registry
    {
        static private var hash:Object = new Object;

        static public function register(name:String, target:DisplayObject):void
        {
            hash[name] = target;
        }

        static public function access(name:String):DisplayObject
        {
            return hash[name];
        }
    }
}
</code>```

Usage:

```<code>// Any MovieClip, frame 1 or class constructor.
import Registry;

Registry.register("deepChild", this);

// From any other place.
import Registry;

Registry.access("deepChild").y = 200;
</code>```

Alternately you can use a method that digs children of children by a single string argument:

```<code>function offSpring(path:String):DisplayObject
{
    var aSplit:Array = path.split(".");
    var result:DisplayObject = this;

    while (aSplit.length)
    {
        var aParent:DisplayObjectContainer = result as DisplayObjectContainer;

        if (!aParent) return null;

        result = aParent.getChildByName(aSplit.shift());
    }

    return result;
}
</code>```

Usage:

```<code>offSpring("layerA.layerB.layerC").y = 200;
</code>```

Body:
If they are unique you can create a "global" registry in a form of static class variables/methods:

package
{
    public class Registry
    {
        static private var hash:Object = new Object;

        static public function register(name:String, target:DisplayObject):void
        {
            hash[name] = target;
        }

        static public function access(name:String):DisplayObject
        {
            return hash[name];
        }
    }
}

Usage:

// Any MovieClip, frame 1 or class constructor.
import Registry;

Registry.register("deepChild", this);

// From any other place.
import Registry;

Registry.access("deepChild").y = 200;

Alternately you can use a method that digs children of children by a single string argument:

function offSpring(path:String):DisplayObject
{
    var aSplit:Array = path.split(".");
    var result:DisplayObject = this;

    while (aSplit.length)
    {
        var aParent:DisplayObjectContainer = result as DisplayObjectContainer;

        if (!aParent) return null;

        result = aParent.getChildByName(aSplit.shift());
    }

    return result;
}

Usage:

offSpring("layerA.layerB.layerC").y = 200;


问:
How do I get rid of the sidebar and toolbar when embedding a pdf in an html file?
Trying to embed a pdf on my website like so:

```<code><iframe src="filename.pdf" type='application/pdf' frameborder="0"></iframe>
</code>```

The website is a rails site, and currently I'm only running it on a local server.

The problem is that the pdfs render with a toolbar on top and a sidebar with my adobe creative cloud account information, as seen in the picture below (the actual content of the pdf displays in the white box under the toolbar and to the left of the sidebar)

How can I get the pdf to render alone, without the menu and sidebar?

答:
If you allow the browser to choose how the PDF gets rendered, you're never going to be able to create a consistent experience for your users unless you are in a controlled desktop environment.

If you are looking for a consistent experience, use pdf.js to render the PDF in the browser.

If you are in a controlled environment and all of your users have a browser/viewer combination that will let the browser show PDF using the Adobe Reader plugin (as your screen shot shows) then you can use the "open parameters" at the end of the URL to control what gets shown. See the documentation at the link below.

http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf

That said, don't count on that solution to work for very long. Most modern browsers are not allowing the viewer plugins to function anymore and the rest are moving in that direction.

Body:
Trying to embed a pdf on my website like so:

The website is a rails site, and currently I'm only running it on a local server.

The problem is that the pdfs render with a toolbar on top and a sidebar with my adobe creative cloud account information, as seen in the picture below (the actual content of the pdf displays in the white box under the toolbar and to the left of the sidebar)

How can I get the pdf to render alone, without the menu and sidebar?


问:
Twilio Nodejs - How to place call to twilio and gather entered digits to call another person
I'm trying to figure out how to create calls from my Twilio number after I've dialed into it and entered a number. After reading the docs I see that this is done with the gather feature, which can then be redirected to another Twiml document to handle the response. However, I can't quite get it to work. I'm extremely confused on how to execute Twiml correctly and how to access the request parameters in another Twiml doc. I've also looked into Twimlets but I wasn't able to construct what I needed there correctly either.

I've gone back and tried to just make a simple voice message play when only my number calls. If it's not me calling then it needs to be redirected to a Twiml url which will try to connect to my phone. If that fails it will prompt the caller to leave a message.

```<code>//Handle incoming call requests
app.post('/call', function(req, res)  {
  var twiml = new twilio.TwimlResponse();
  res.type('text/xml');

  if ( req.body.From === "+1555555555") {
    twiml.say('Hello', {voice: alice});
    res.send(twiml.toString());
  } else {
    // Do something here.
  }
});
</code>```

I've found the correct solution for my problem. I wasn't initiating the twilio.TwimlResponse() correctly.

答: In order to solve this issue, I needed to use == instead of === so that my  req.body.from value wouldn't get coerced.

Body:
I'm trying to figure out how to create calls from my Twilio number after I've dialed into it and entered a number. After reading the docs I see that this is done with the gather feature, which can then be redirected to another Twiml document to handle the response. However, I can't quite get it to work. I'm extremely confused on how to execute Twiml correctly and how to access the request parameters in another Twiml doc. I've also looked into Twimlets but I wasn't able to construct what I needed there correctly either.

I've gone back and tried to just make a simple voice message play when only my number calls. If it's not me calling then it needs to be redirected to a Twiml url which will try to connect to my phone. If that fails it will prompt the caller to leave a message.

//Handle incoming call requests
app.post('/call', function(req, res)  {
  var twiml = new twilio.TwimlResponse();
  res.type('text/xml');

  if ( req.body.From === "+1555555555") {
    twiml.say('Hello', {voice: alice});
    res.send(twiml.toString());
  } else {
    // Do something here.
  }
});

I've found the correct solution for my problem. I wasn't initiating the twilio.TwimlResponse() correctly.


问:
How to extract a string from a cell from right to left using a specific character that occurs more than once?
Normally I would just use the RIGHT function in excel to split it by finding a specific character such as / and outputting the string that I want.

However, I am finding trouble extracting THISSTRING.txt from d/aaa/THISSTRING.txt. With only one instance of / I would just use a function such as =RIGHT(B17,LEN(B17) - FIND("/",B17))

答:
Objective: To return the rightmost sub-string from a target string after the last occurrence of a character which appears several times within the target string.

This formula:

```<code>=TRIM(RIGHT(SUBSTITUTE(A1,"/",REPT(" ",99)),99))
</code>```

Provides the correct result under the following conditions:

The sub-string to retrieve does not have more than 99 characters.

The sub-string to retrieve does not contain more than one space character together.

Example: To retrieve a sub-string which is 123 characters long and contains the following characters 1  ABC  XXX   123  XYZ.

Point 1 is easily solved by working with the length of the string instead of a fixed number:

```<code>=TRIM(RIGHT(SUBSTITUTE(A1,"/",REPT(" ",LEN(A1))), LEN(A1)))
</code>```

However point 2 can't be overcome with the referred formula.

Proposed solution: The following formula returns the correct result regardless of the conditions mentioned above:

```<code>=RIGHT(A1, LEN(A1) - FIND( CHAR(12),
SUBSTITUTE(A1, "/", CHAR(12), LEN(A1) - LEN( SUBSTITUTE(A1, "/", "" )))))
</code>```

Note: I used non-printable character 12 which is very unlikely to be found in excel, change as required.

Body:
Objective: To return the rightmost sub-string from a target string after the last occurrence of a character which appears several times within the target string.

This formula:

=TRIM(RIGHT(SUBSTITUTE(A1,"/",REPT(" ",99)),99))

Provides the correct result under the following conditions:

The sub-string to retrieve does not have more than 99 characters.

The sub-string to retrieve does not contain more than one space character together.

Example: To retrieve a sub-string which is 123 characters long and contains the following characters 1  ABC  XXX   123  XYZ.

Point 1 is easily solved by working with the length of the string instead of a fixed number:

=TRIM(RIGHT(SUBSTITUTE(A1,"/",REPT(" ",LEN(A1))), LEN(A1)))

However point 2 can't be overcome with the referred formula.

Proposed solution: The following formula returns the correct result regardless of the conditions mentioned above:

=RIGHT(A1, LEN(A1) - FIND( CHAR(12),
SUBSTITUTE(A1, "/", CHAR(12), LEN(A1) - LEN( SUBSTITUTE(A1, "/", "" )))))

Note: I used non-printable character 12 which is very unlikely to be found in excel, change as required.


问:
JSON Syntax: Transmitting an array
A valid JSON Syntax is something of the kind:

```<code>{
  "username": "admin",
  "password": "123"
}
</code>```

But what if I want to transmit an array of 'users' (given the example), instead of a single 'user' ?

Is the code below Valid JSON, according to the specifications?

```<code>[{
  "username": "admin",
  "password": "123"
}, {
  "username": "bbvb",
  "password": "sdfsdf"
}, {
  "username": "asd",
  "password": "222"
}]
</code>```

And if not, what is the best way to transmit an array of values across with JSON? (And with 'best way', I mean syntactically)

答: The not-very-well-known page json.org has a diagram that shows the syntax. It’s extremely simple to understand, IMHO.</p>

OwnerDisplayName: Dreas Grech

Title: JSON Syntax: Transmitting an array

Body:
A valid JSON Syntax is something of the kind:

{
  "username": "admin",
  "password": "123"
}

But what if I want to transmit an array of 'users' (given the example), instead of a single 'user' ?

Is the code below Valid JSON, according to the specifications?

[{
  "username": "admin",
  "password": "123"
}, {
  "username": "bbvb",
  "password": "sdfsdf"
}, {
  "username": "asd",
  "password": "222"
}]

And if not, what is the best way to transmit an array of values across with JSON? (And with 'best way', I mean syntactically)

OwnerDisplayName: Bombe


问:
To OpenID or not to OpenID? Is it worth it?
Does OpenID improve the user experience?

Edit

Not to detract from the other comments, but I got one really good reply below that outlined 3 advantages of OpenID in a rational bottom line kind of way. I've also heard some whisperings in other comments that you can get access to some details on the user through OpenID (name? email? what?) and that using that it might even be able to simplify the registration process by not needing to gather as much information.

Things that definitely need to be gathered in a checkout process:

Full name

Email

(I'm pretty sure I'll have to ask for these myself)

Billing address

Shipping address

Credit card info

There may be a few other things that are interesting from a marketing point of view, but I wouldn't ask the user to manually enter anything not absolutely required during the checkout process. So what's possible in this regard?

/Edit

(You may have noticed stackoverflow uses OpenID)

It seems to me it is easier and faster for the user to simply enter a username and password in a signup form they have to go through anyway. I mean you don't avoid entering a username and password either with OpenID. But you avoid the confusion of choosing a OpenID provider, and the trip out to and back from and external site.

With Microsoft making Live ID an OpenID provider (More Info), bringing on several hundred million additional accounts to those provided by Google, Yahoo, and others, this question is more important than ever.

I have to require new customers to sign up during the checkout process, and it is absolutely critical that the experience be as easy and smooth as possible, every little bit harder it becomes translates into lost sales. No geek factor outweighs cold hard cash at the end of the day :)

OpenID seems like a nice idea, but the implementation is of questionable value. What are the advantages of OpenID and is it really worth it in my scenario described above?

答: I ran across this discussion about what's wrong with OpenID and thought it helpful and relevant: http://www.quora.com/What-s-wrong-with-OpenID</p>


问:
multiple definition in header file
Given this code sample:

complex.h :

```<code>#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>

class Complex
{
public:
   Complex(float Real, float Imaginary);

   float real() const { return m_Real; };

private:
   friend std::ostream& operator<<(std::ostream& o, const Complex& Cplx);

   float m_Real;
   float m_Imaginary;
};

std::ostream& operator<<(std::ostream& o, const Complex& Cplx) {
   return o << Cplx.m_Real << " i" << Cplx.m_Imaginary;
}
#endif // COMPLEX_H
</code>```

complex.cpp :

```<code>#include "complex.h"

Complex::Complex(float Real, float Imaginary) {
   m_Real = Real;
   m_Imaginary = Imaginary;
}
</code>```

main.cpp :

```<code>#include "complex.h"
#include <iostream>

int main()
{
   Complex Foo(3.4, 4.5);
   std::cout << Foo << "\n";
   return 0;
}
</code>```

When compiling this code, I get the following error:

```<code>multiple definition of operator<<(std::ostream&, Complex const&)
</code>```

I've found that making this function inline solves the problem, but I don't understand why. Why does the compiler complain about multiple definition? My header file is guarded (with #define COMPLEX_H).

And, if complaining about the operator<< function, why not complain about the public real() function, which is defined in the header as well?

And is there another solution besides using the inline keyword?

答:
I was having this problem, even after my source and header file were correct.

It turned out Eclipse was using stale artifacts from a previous (failed) build.

To fix, use Project > Clean then rebuild.

Title: multiple definition in header file

Body:
Given this code sample:

complex.h :

#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>

class Complex
{
public:
   Complex(float Real, float Imaginary);

   float real() const { return m_Real; };

private:
   friend std::ostream& operator<<(std::ostream& o, const Complex& Cplx);

   float m_Real;
   float m_Imaginary;
};

std::ostream& operator<<(std::ostream& o, const Complex& Cplx) {
   return o << Cplx.m_Real << " i" << Cplx.m_Imaginary;
}
#endif // COMPLEX_H

complex.cpp :

#include "complex.h"

Complex::Complex(float Real, float Imaginary) {
   m_Real = Real;
   m_Imaginary = Imaginary;
}

main.cpp :

#include "complex.h"
#include <iostream>

int main()
{
   Complex Foo(3.4, 4.5);
   std::cout << Foo << "\n";
   return 0;
}

When compiling this code, I get the following error:

multiple definition of operator<<(std::ostream&, Complex const&)

I've found that making this function inline solves the problem, but I don't understand why. Why does the compiler complain about multiple definition? My header file is guarded (with #define COMPLEX_H).

And, if complaining about the operator<< function, why not complain about the public real() function, which is defined in the header as well?

And is there another solution besides using the inline keyword?


问:
using beginBackgroundTaskWithExpirationHandler for upload
From the doc it looks like uploading a file is a good use case for using beginBackgroundTaskWithExpirationHandler. I've found that using

```<code>let uploadTask = session.uploadTask(with: request as URLRequest, fromFile: file)
uploadTask.resume()
</code>```

will already run while the app is backgrounded (I'm getting upload progress pings for a while). Additionally I can set the URLSession to be backgrounded:

```<code>let config = URLSessionConfiguration.background(withIdentifier: "uploads")
session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
</code>```

So what is the advantage of using beginBackgroundTaskWithExpirationHandler ? Will it extend the time I've to finish my upload? If so can I know by how much (didn't see anything about this in the doc)? Or is it just that I'll get pinged before the app stops? Should I use it in combination with a background URLSession?

Additionally the docs says that the handler will be called shortly before the app’s remaining background time reaches 0 Does it mean that the app will be terminated after that? ie can I assume that the next call will be application:didFinishLaunchingWithOptions or can it be applicationDidBecomeActive ?

答:
This background task will let your app continue to run in background after the user leaves your app for an extra 3 minutes or so (check backgroundTimeRemaining for actual value) to let your request finish. And, yes, near the end of that 3 minutes, the timeout handler will be called if you haven't yet ended the background task.

So, if you end the background task during the normal flow of your app, this timeout closure won't need to be called. This closure is solely for any quick, last minute cleanup, that you might need to do before your app stops running in the background because it timed out before you had a chance to indicate that the background task ended. It's not for starting anything new, but just any last second clean-up. And make sure to end the background task in this timeout handler ... if you don't end the background task, the OS will summarily kill your app rather than just suspending it. Often, the only thing you need to do in this timeout closure is end the background task, but if you need to do any other cleanup, this is where you can do it.

Needless to say, you must end your background task (either when the network request finishes, or in the timeout handler if your app didn't yet get a chance to end the background task in its normal flow). If you don't, your app won't just be suspended, but rather it will be killed.

Regarding making assumptions about what happens when your app is restarted by the user later, you can't make any assumes about which app delegate method will be called. Even if you gracefully ended the background task, you have no assurances that it won't get jettisoned for other reasons (e.g. memory pressure). So don't assume anything.

Body:
From the doc it looks like uploading a file is a good use case for using beginBackgroundTaskWithExpirationHandler. I've found that using

let uploadTask = session.uploadTask(with: request as URLRequest, fromFile: file)
uploadTask.resume()

will already run while the app is backgrounded (I'm getting upload progress pings for a while). Additionally I can set the URLSession to be backgrounded:

let config = URLSessionConfiguration.background(withIdentifier: "uploads")
session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

So what is the advantage of using beginBackgroundTaskWithExpirationHandler ? Will it extend the time I've to finish my upload? If so can I know by how much (didn't see anything about this in the doc)? Or is it just that I'll get pinged before the app stops? Should I use it in combination with a background URLSession?

Additionally the docs says that the handler will be called shortly before the app’s remaining background time reaches 0 Does it mean that the app will be terminated after that? ie can I assume that the next call will be application:didFinishLaunchingWithOptions or can it be applicationDidBecomeActive ?


问:
How do I get out of ESC mode in zsh?
When using zsh, I sometimes accidentally press Escape out of habit, expecting it to clear the entire line as it does in Windows.  Instead, it goes into a mode that I'm not sure how to get out of.  The cursor goes back one character, and some keys perform some special commands, but all I really want to do is get out of this mode and be able to press Ctrl+U to clear the line.

Searching around has been tough - I get results for escaping characters.

答:
Short answer: press a.

Medium answer: press a, then enter bindkey -e.

Long answer: Like a lot of UNIX shells, zsh has an emacs-like mode and a vi-like mode. You're in vi-like mode, and ESC takes you out of the vi-like insert mode. a puts you back into insert mode, with the cursor after the current character. (Sorry for the two different uses of "mode," but it is the accepted terminology in both cases.)

bindkey -e overrides the settings from the rc files and puts zsh into emacs mode, which only has one mode (i.e., no "ESC mode"), so this won't bother you any more. Unfortunately, it won't carry over to your next shell invocation. bindkey -v would switch from emacs mode back to vi mode.

In the absence of any other configuration, zsh defaults to emacs mode, so unless there's something in one of the rc files, the likely culprit is that the EDITOR variable is some form of vi, which causes zsh to default to vi mode. If you don't like vi mode, then you should probably hunt down what part of the system-wide or user-specific configuration is causing zsh to default to vi mode and turn it off by removing it or overriding it in one of those rc files.

Title: How do I get out of ESC mode in zsh?


问:
Faster way to build text file in python
I have two 3d numpy arrays, call them a and b, 512x512x512. I need to write them to a text file:

```<code>a1 b1
a2 b2
a3 b3
...
</code>```

This can be accomplished with a triple loop:

```<code>lines = []
for x in range(nx):
    for y in range(ny):
        for z in range(nz):
            lines.append('{} {}'.format(a[x][y][z], b[x][y][z])
print('\n'.join(lines))
</code>```

But this is brutally slow (10 minutes when I'd prefer a few seconds on a mac pro).

I am using python 3.6, latest numpy, and am happy to use other libraries, build extensions, whatever is necessary. What is the best way to get this faster?

答:
It's a bit difficult to understand your problem without knowing what kind of data you have in those three arrays, but it looks like numpy.savetxt could be useful for you.

Here's how it works:

```<code>import numpy as np
a = np.array(range(10))
np.savetxt("myfile.txt", a)
</code>```

And here's the documentation:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

Title: Faster way to build text file in python

Body:
I have two 3d numpy arrays, call them a and b, 512x512x512. I need to write them to a text file:

a1 b1
a2 b2
a3 b3
...

This can be accomplished with a triple loop:

lines = []
for x in range(nx):
    for y in range(ny):
        for z in range(nz):
            lines.append('{} {}'.format(a[x][y][z], b[x][y][z])
print('\n'.join(lines))

But this is brutally slow (10 minutes when I'd prefer a few seconds on a mac pro).

I am using python 3.6, latest numpy, and am happy to use other libraries, build extensions, whatever is necessary. What is the best way to get this faster?

Body:
It's a bit difficult to understand your problem without knowing what kind of data you have in those three arrays, but it looks like numpy.savetxt could be useful for you.

Here's how it works:

import numpy as np
a = np.array(range(10))
np.savetxt("myfile.txt", a)

And here's the documentation:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html


问:
What does these variable names stand for?
I am using a function which have some variables that I don't know what they stand for.

The variables are:

```<code>a   //From var a = Math ...
</code>```

and

```<code>The d in dLat
</code>```

Here is the code:

```<code>function checkDistance(lat1,lon1,lat2,lon2) {
      var R = 6371; // Radius of the earth in km
      var dLat = deg2rad(lat2-lat1);  // deg2rad below
      var dLon = deg2rad(lon2-lon1);
      var a =
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
        Math.sin(dLon/2) * Math.sin(dLon/2)
        ;
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      var d = R * c; // Distance in km
      return d;
    }
</code>```

What do you think they stand for?

答:
This is a function which uses the haversine formula to calculate the Earth surface distance between two points (using the points' latitude and longitude values).

```<code> a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
 c = 2 ⋅ atan2( √a, √(1−a) )
 d = R ⋅ c
</code>```

The "d" in dLat stands for the delta Δ (aka the difference between the two latitudes). This is just what the variable was called in this function. The dLat is equivalent to Δφ, while dLon is equivalent to Δλ.

The a variable is equivalent to the first line of the formula.

I hope this answers your question.

You can find more info here: http://www.movable-type.co.uk/scripts/latlong.html

Body:
I am using a function which have some variables that I don't know what they stand for.

The variables are:

a   //From var a = Math ...

and

The d in dLat

Here is the code:

function checkDistance(lat1,lon1,lat2,lon2) {
      var R = 6371; // Radius of the earth in km
      var dLat = deg2rad(lat2-lat1);  // deg2rad below
      var dLon = deg2rad(lon2-lon1);
      var a =
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
        Math.sin(dLon/2) * Math.sin(dLon/2)
        ;
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      var d = R * c; // Distance in km
      return d;
    }

What do you think they stand for?

Body:
This is a function which uses the haversine formula to calculate the Earth surface distance between two points (using the points' latitude and longitude values).

 a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
 c = 2 ⋅ atan2( √a, √(1−a) )
 d = R ⋅ c

The "d" in dLat stands for the delta Δ (aka the difference between the two latitudes). This is just what the variable was called in this function. The dLat is equivalent to Δφ, while dLon is equivalent to Δλ.

The a variable is equivalent to the first line of the formula.

I hope this answers your question.

You can find more info here: http://www.movable-type.co.uk/scripts/latlong.html


问:
AngularDart - Manipulate DOM from Component
so I am using the standard template from AngularDart that comes from stagehand web-angular-simple.
Now, if I have something hardcoded in index.html and try to manipulate it from main.dart using querySelector, everything works fine.

But how can I use querySelector to manipulate the AppComponent that was loaded into the index.html file in the template?

So basically my question is: how to manipulate dynamically loaded elements in dart.
(p.s. I just started out in AngularDart...)

thanks in advance

答:
You can inject ElementRef and through it access nativeElement - this will be the DOM node of you component.

The question is why do you need? Almost always there is a way to do what you need through interacting with angular templates.


Title: C# serialize private class member

Body: ISerializable? http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx


答:
You could use np.stack and reshape the array to (-1, 2) (two columns) array, then use np.savetxt:

```<code>a = np.arange(8).reshape(2,2,2)
b = np.arange(8, 16).reshape(2,2,2)

np.stack([a, b], axis=-1).reshape(-1, 2)

#array([[ 0,  8],
#       [ 1,  9],
#       [ 2, 10],
#       [ 3, 11],
#       [ 4, 12],
#       [ 5, 13],
#       [ 6, 14],
#       [ 7, 15]])
</code>```

Then you can save the file as:

```<code>np.savetxt("*.txt", np.stack([a, b], axis=-1).reshape(-1, 2), fmt="%d")
</code>```

Title: Faster way to build text file in python

Body:
You could use np.stack and reshape the array to (-1, 2) (two columns) array, then use np.savetxt:

a = np.arange(8).reshape(2,2,2)
b = np.arange(8, 16).reshape(2,2,2)

np.stack([a, b], axis=-1).reshape(-1, 2)

#array([[ 0,  8],
#       [ 1,  9],
#       [ 2, 10],
#       [ 3, 11],
#       [ 4, 12],
#       [ 5, 13],
#       [ 6, 14],
#       [ 7, 15]])

Then you can save the file as:

np.savetxt("*.txt", np.stack([a, b], axis=-1).reshape(-1, 2), fmt="%d")


问:
Removing Tab Indicator from ViewPager
I have a ViewPager that contains multiple tabs. There is a tab indicator at the top of the screen (the black strip in the following picture). How do I disable the tab indicator?

Here's the code if needed:

```<code>    // ViewPager
ViewPager pager;
TeamTabAdapter tabAdapter;

REvent event;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.Backup);
    setContentView(R.layout.activity_team_viewer);

    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getApplicationContext(), R.color.actionbar)));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    event = (REvent) getIntent().getSerializableExtra("event");
    RTeam team = (RTeam) getIntent().getSerializableExtra("team");
    RForm form = new Loader(getApplicationContext()).loadForm(event.getID());

    tabAdapter = new TeamTabAdapter(getSupportFragmentManager(), event, team, form);
    pager = (ViewPager) findViewById(R.id.pager);

    pager.addOnPageChangeListener(this);

    pager.setAdapter(tabAdapter);
    pager.setCurrentItem(1);
}
</code>```

答:
Removing Tab Indicator from ViewPager

Remove the PagerTabStrip from the layout. It will be a child of the ViewPager.

How do I disable the tab indicator?

You can try calling setEnabled(false) on the PagerTabStrip, though I do not know if this works.

Title: Removing Tab Indicator from ViewPager

Body:
I have a ViewPager that contains multiple tabs. There is a tab indicator at the top of the screen (the black strip in the following picture). How do I disable the tab indicator?

Here's the code if needed:

    // ViewPager
ViewPager pager;
TeamTabAdapter tabAdapter;

REvent event;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.Backup);
    setContentView(R.layout.activity_team_viewer);

    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getApplicationContext(), R.color.actionbar)));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    event = (REvent) getIntent().getSerializableExtra("event");
    RTeam team = (RTeam) getIntent().getSerializableExtra("team");
    RForm form = new Loader(getApplicationContext()).loadForm(event.getID());

    tabAdapter = new TeamTabAdapter(getSupportFragmentManager(), event, team, form);
    pager = (ViewPager) findViewById(R.id.pager);

    pager.addOnPageChangeListener(this);

    pager.setAdapter(tabAdapter);
    pager.setCurrentItem(1);
}


问:
Microsoft SSRS 2016 Lookup (on dynamic dataset) and return multiple (n) columns
I have a unique Microsoft  SSRS (2016) situation:

I have this table below:

Table A (3 columns; key column:  OrderID) the main table, main dataset - fixed dataset:

```<code>OrderID Region  Store
124     FL      ORL-23
125     CA      SFO-21
126     TX      DAL-19
</code>```

I have another table, Table B (4 columns; key column:  OrderID) in another dataset (say Lookup dataset):

```<code>OrderID Gratuity    DeliveryFee Surcharge
124     $2.50       $3.00       $0.75
125     $3.50       $5.50       $0.67
126     $4.75       $3.75       $0.45
</code>```

Table B (Lookup dataset) is actually a dynamic table; it can have 3 columns (as shown above)  apart from OrderID, the base column; in some other cases (via parameters), it can have 4 columns (apart from OrderID), and so on - - say, n columns apart from OrderID, where n depends on a parameter value I choose.

I need to get the following result set (Table C with 6 columns (in this particular case, when Table B has 3 dynamic columns)), lookedup on OrderID column):

```<code>OrderID Region  Store   Gratuity    DeliveryFee Surcharge
124     FL      ORL-23  $2.50       $3.00       $0.75
125     CA      SFO-21  $3.50       $5.50       $0.67
126     TX      DAL-19  $4.75       $3.75       $0.45
</code>```

Table A:         fixed 3 columns;
Table B:         n varying columns

I need to get table C in SSRS 2016; I have options such as Lookup, LookupSet, MultiLookup, etc.

Remember that Table C must have 3 (or n, where n is the number of columns in the dynamic dataset Table B) new columns (Gratuity, DeliveryFee, Surcharge), not 1 column concatenated in this way:

```<code>Fields!Gratuity.Value & ", " & Fields!DeliveryFee.Value & ", " &  Fields!Surcharge.Value
</code>```

Hence Table C can have 6 columns, 7 columns, ...i.e. (3+n) columns, since Table B has a varying number of columns, depending on a parameter chosen.

How can I achieve this? Or should I try some options such as SubReport, or something?

Due to some business logic, I cannot use JOIN; table A- here I have simplified (actually Table A has many more columns with a lot of calculations such as SUM, DISTINCT COUNT, etc).  It has some aggregated calculations.

答:
This can be done in your query so it is one dataset in SSRS.</p>

```<code>SELECT
    a.OrderID
    ,a.Region
    ,a.Store
    ,b.Gratuity
    ,b.DeliveryFee
    ,b.Surcharge
FROM TableA A
JOIN TableB B ON
    a.OrderID = b.OrderID
</code>```

Body:
I have a unique Microsoft  SSRS (2016) situation:

I have this table below:

Table A (3 columns; key column:  OrderID) the main table, main dataset - fixed dataset:

OrderID Region  Store
124     FL      ORL-23
125     CA      SFO-21
126     TX      DAL-19

I have another table, Table B (4 columns; key column:  OrderID) in another dataset (say Lookup dataset):

OrderID Gratuity    DeliveryFee Surcharge
124     $2.50       $3.00       $0.75
125     $3.50       $5.50       $0.67
126     $4.75       $3.75       $0.45

Table B (Lookup dataset) is actually a dynamic table; it can have 3 columns (as shown above)  apart from OrderID, the base column; in some other cases (via parameters), it can have 4 columns (apart from OrderID), and so on - - say, n columns apart from OrderID, where n depends on a parameter value I choose.

I need to get the following result set (Table C with 6 columns (in this particular case, when Table B has 3 dynamic columns)), lookedup on OrderID column):

OrderID Region  Store   Gratuity    DeliveryFee Surcharge
124     FL      ORL-23  $2.50       $3.00       $0.75
125     CA      SFO-21  $3.50       $5.50       $0.67
126     TX      DAL-19  $4.75       $3.75       $0.45

Table A:         fixed 3 columns;
Table B:         n varying columns

I need to get table C in SSRS 2016; I have options such as Lookup, LookupSet, MultiLookup, etc.

Remember that Table C must have 3 (or n, where n is the number of columns in the dynamic dataset Table B) new columns (Gratuity, DeliveryFee, Surcharge), not 1 column concatenated in this way:

Fields!Gratuity.Value & ", " & Fields!DeliveryFee.Value & ", " &  Fields!Surcharge.Value

Hence Table C can have 6 columns, 7 columns, ...i.e. (3+n) columns, since Table B has a varying number of columns, depending on a parameter chosen.

How can I achieve this? Or should I try some options such as SubReport, or something?

Due to some business logic, I cannot use JOIN; table A- here I have simplified (actually Table A has many more columns with a lot of calculations such as SUM, DISTINCT COUNT, etc).  It has some aggregated calculations.

Body:
This can be done in your query so it is one dataset in SSRS.

SELECT
    a.OrderID
    ,a.Region
    ,a.Store
    ,b.Gratuity
    ,b.DeliveryFee
    ,b.Surcharge
FROM TableA A
JOIN TableB B ON
    a.OrderID = b.OrderID


问:
What environment variables can be used with a Docker image?
I'm just learning Docker. If I want to use a particular image from Docker Hub, such as mysql, how do I know what environment variables can be used with that Docker image? Any way to get a list of the available variables?</p>

答:
If you look at any Dockerfile, search for lines that begin with ENV:

```<code>cat Dockerfile | grep ENV
</code>```

If only an image is available, you can always do (--format=... is optional):

```<code>docker history --format="{{.CreatedBy}}" --no-trunc myimage  | grep ENV
</code>```

Body:
If you look at any Dockerfile, search for lines that begin with ENV:

cat Dockerfile | grep ENV

If only an image is available, you can always do (--format=... is optional):

docker history --format="{{.CreatedBy}}" --no-trunc myimage  | grep ENV

ContentLicense: CC BY-SA 4.0


问:
Delete query working in PgAdmin 3 but not working on Java JDBC
I am trying to delete a list of times saved in a database where the date (end_time - timestamp) is bigger that my reference day for a specific employee (employeeId - integer).
The query works perfectly on pgAdmin III. However I cannot make it work in JDBC.
It works, but it deletes everything from that particular employee and not just the dates I want. I looks like it ignores the date in the Where clause. Also, I do not get any exception.
The variable nextDayTimestamp comes out like: '2017-03-31 12:00:00.0'
Could anybody please help?

```<code> public void deleteBigListOfPeriodOfWorkFutureOnly(int employeeId, LocalDate referenceDate) {
        Connection myConn = null;
        PreparedStatement myStmt = null;

        try {

            myConn = dataSource.getConnection();

            LocalDate nextDay = referenceDate.plusDays(1);
            Timestamp nextDayTimestamp = Timestamp.valueOf(LocalDateTime.of(nextDay, LocalTime.NOON));
            String sql = "delete from working_time where working_time.end_time > ? and employee_id = ?";

            myStmt = myConn.prepareStatement(sql);

            myStmt.setTimestamp(1, nextDayTimestamp);
            myStmt.setInt(2, employeeId);

            myStmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            CloseConnection.close(myConn, myStmt, null);
        }

    }
}
</code>```

答: If the Connection coming out of that dataSource doesn't have AutoCommit turned on, your update will succeed, but the "transaction" never commits, so in the database won't reflect your changes.  Maybe put an explicit myConn.commit(); after that executeUpdate and see if your updates now show up in the database.

Body:
I am trying to delete a list of times saved in a database where the date (end_time - timestamp) is bigger that my reference day for a specific employee (employeeId - integer).
The query works perfectly on pgAdmin III. However I cannot make it work in JDBC.
It works, but it deletes everything from that particular employee and not just the dates I want. I looks like it ignores the date in the Where clause. Also, I do not get any exception.
The variable nextDayTimestamp comes out like: '2017-03-31 12:00:00.0'
Could anybody please help?

 public void deleteBigListOfPeriodOfWorkFutureOnly(int employeeId, LocalDate referenceDate) {
        Connection myConn = null;
        PreparedStatement myStmt = null;

        try {

            myConn = dataSource.getConnection();

            LocalDate nextDay = referenceDate.plusDays(1);
            Timestamp nextDayTimestamp = Timestamp.valueOf(LocalDateTime.of(nextDay, LocalTime.NOON));
            String sql = "delete from working_time where working_time.end_time > ? and employee_id = ?";

            myStmt = myConn.prepareStatement(sql);

            myStmt.setTimestamp(1, nextDayTimestamp);
            myStmt.setInt(2, employeeId);

            myStmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            CloseConnection.close(myConn, myStmt, null);
        }

    }
}


问:
Rails composer devise-rails will not let me complete a rails db:reset
I used the rails composer tool to create a rails devise composed project, which included rails confirmable.

It was all fine - and then I decided I wanted to perform a rails db:reset

I ran the command and this is the output:

```<code>Andys-MacBook-Pro:myproj andyarmstrong$ rails db:reset
Dropped database 'myproj_development'
Dropped database 'myproj_test'
Created database 'myproj_development'
Created database 'myproj_test'
-- enable_extension("plpgsql")
   -> 0.0419s
-- create_table("users", {:force=>:cascade})
   -> 0.0188s
-- enable_extension("plpgsql")
   -> 0.0305s
-- create_table("users", {:force=>:cascade})
   -> 0.0236s
rails aborted!
NoMethodError: undefined method `confirm!' for #<User:0x007fa47ac1c2a0>
Did you mean?  confirm
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activemodel-5.1.0.rc1/lib/active_model/attribute_methods.rb:432:in `method_missing'
/Users/andyarmstrong/Documents/Personal/myproj/app/services/create_admin_service.rb:6:in `block in call'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/core.rb:339:in `initialize'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/devise-4.2.1/lib/devise/models/confirmable.rb:65:in `initialize'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/inheritance.rb:66:in `new'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/inheritance.rb:66:in `new'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/persistence.rb:50:in `create!'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/relation.rb:156:in `block in create!'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/relation.rb:337:in `scoping'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/relation.rb:156:in `create!'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/relation.rb:227:in `find_or_create_by!'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/querying.rb:6:in `find_or_create_by!'
/Users/andyarmstrong/Documents/Personal/myproj/app/services/create_admin_service.rb:3:in `call'
/Users/andyarmstrong/Documents/Personal/myproj/db/seeds.rb:8:in `<top (required)>'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:286:in `load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:286:in `block in load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:258:in `load_dependency'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:286:in `load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/engine.rb:549:in `load_seed'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/tasks/database_tasks.rb:268:in `load_seed'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/railties/databases.rake:181:in `block (2 levels) in <top (required)>'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/commands/rake/rake_command.rb:21:in `block in perform'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/commands/rake/rake_command.rb:18:in `perform'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/command.rb:46:in `invoke'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/commands.rb:16:in `<top (required)>'
/Users/andyarmstrong/Documents/Personal/myproj/bin/rails:9:in `require'
/Users/andyarmstrong/Documents/Personal/myproj/bin/rails:9:in `<top (required)>'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/client/rails.rb:28:in `load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/client/rails.rb:28:in `call'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/client/command.rb:7:in `call'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/client.rb:30:in `run'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/bin/spring:49:in `<top (required)>'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/binstub.rb:31:in `load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/binstub.rb:31:in `<top (required)>'
/Users/andyarmstrong/Documents/Personal/myproj/bin/spring:15:in `require'
/Users/andyarmstrong/Documents/Personal/myproj/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
</code>```

Following through the stack trace - I see it is failing in the db:seeds component, on this line : user = CreateAdminService.new.call. If i then go into app/services and open the create_admin_service.rb file we can finally see our problem line:

```<code>class CreateAdminService
  def call
    user = User.find_or_create_by!(email: Rails.application.secrets.admin_email) do |user|
        user.password = Rails.application.secrets.admin_password
        user.password_confirmation = Rails.application.secrets.admin_password
        user.confirm!
      end
  end
end
</code>```

Why is user.confirm! failing to be found? Is that not meant to be part of the base Devise package? For reference this is my user model:

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable,
    :recoverable, :rememberable, :trackable, :validatable
end
</code>```

答:
I decided to try changing the line:

```<code> user.confirm!
</code>```

in the create_admin_service to simply be :

```<code>user.confirm
</code>```

Because confirmable.rb of devise doesn't appear to have 'confirm!' as a method. This allowed the db:reset to succeed, so I can only assume this is a problem with devise-rails composer confirmable example! I have made an appropriate issue on their github.

Body:
I used the rails composer tool to create a rails devise composed project, which included rails confirmable.

It was all fine - and then I decided I wanted to perform a rails db:reset

I ran the command and this is the output:

Andys-MacBook-Pro:myproj andyarmstrong$ rails db:reset
Dropped database 'myproj_development'
Dropped database 'myproj_test'
Created database 'myproj_development'
Created database 'myproj_test'
-- enable_extension("plpgsql")
   -> 0.0419s
-- create_table("users", {:force=>:cascade})
   -> 0.0188s
-- enable_extension("plpgsql")
   -> 0.0305s
-- create_table("users", {:force=>:cascade})
   -> 0.0236s
rails aborted!
NoMethodError: undefined method `confirm!' for #<User:0x007fa47ac1c2a0>
Did you mean?  confirm
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activemodel-5.1.0.rc1/lib/active_model/attribute_methods.rb:432:in `method_missing'
/Users/andyarmstrong/Documents/Personal/myproj/app/services/create_admin_service.rb:6:in `block in call'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/core.rb:339:in `initialize'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/devise-4.2.1/lib/devise/models/confirmable.rb:65:in `initialize'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/inheritance.rb:66:in `new'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/inheritance.rb:66:in `new'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/persistence.rb:50:in `create!'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/relation.rb:156:in `block in create!'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/relation.rb:337:in `scoping'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/relation.rb:156:in `create!'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/relation.rb:227:in `find_or_create_by!'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/querying.rb:6:in `find_or_create_by!'
/Users/andyarmstrong/Documents/Personal/myproj/app/services/create_admin_service.rb:3:in `call'
/Users/andyarmstrong/Documents/Personal/myproj/db/seeds.rb:8:in `<top (required)>'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:286:in `load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:286:in `block in load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:258:in `load_dependency'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activesupport-5.1.0.rc1/lib/active_support/dependencies.rb:286:in `load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/engine.rb:549:in `load_seed'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/tasks/database_tasks.rb:268:in `load_seed'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/activerecord-5.1.0.rc1/lib/active_record/railties/databases.rake:181:in `block (2 levels) in <top (required)>'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/commands/rake/rake_command.rb:21:in `block in perform'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/commands/rake/rake_command.rb:18:in `perform'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/command.rb:46:in `invoke'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/railties-5.1.0.rc1/lib/rails/commands.rb:16:in `<top (required)>'
/Users/andyarmstrong/Documents/Personal/myproj/bin/rails:9:in `require'
/Users/andyarmstrong/Documents/Personal/myproj/bin/rails:9:in `<top (required)>'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/client/rails.rb:28:in `load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/client/rails.rb:28:in `call'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/client/command.rb:7:in `call'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/client.rb:30:in `run'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/bin/spring:49:in `<top (required)>'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/binstub.rb:31:in `load'
/Users/andyarmstrong/.rvm/gems/ruby-2.4.0@myproj/gems/spring-2.0.1/lib/spring/binstub.rb:31:in `<top (required)>'
/Users/andyarmstrong/Documents/Personal/myproj/bin/spring:15:in `require'
/Users/andyarmstrong/Documents/Personal/myproj/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `'

Following through the stack trace - I see it is failing in the db:seeds component, on this line : user = CreateAdminService.new.call. If i then go into app/services and open the create_admin_service.rb file we can finally see our problem line:

class CreateAdminService
  def call
    user = User.find_or_create_by!(email: Rails.application.secrets.admin_email) do |user|
        user.password = Rails.application.secrets.admin_password
        user.password_confirmation = Rails.application.secrets.admin_password
        user.confirm!
      end
  end
end

Why is user.confirm! failing to be found? Is that not meant to be part of the base Devise package? For reference this is my user model:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable,
    :recoverable, :rememberable, :trackable, :validatable
end

Body:
I decided to try changing the line:

 user.confirm!

in the create_admin_service to simply be :

user.confirm

Because confirmable.rb of devise doesn't appear to have 'confirm!' as a method. This allowed the db:reset to succeed, so I can only assume this is a problem with devise-rails composer confirmable example! I have made an appropriate issue on their github.


问:
jQuery Validation Highlighting One Label for Two Fields
I have a form validation script using the jQuery Validation plugin where for the phone area, there are 2 fields, area code and phone number. However, there is only one label for both fields that reads "Phone." Both fields are required in the validation.

So when there is an error in the phone field, the label gets highlighted and the error message is shown. If there is an error in the area code field, the error message is shown but the label doesn't get the error class so it doesn't get the highlight.

Can anyone think of a way to highlight the "Phone" label and display the correct message when the area code field does not validate? Thanks!

答:
You can write a custom rule for the phone field that checks the area code field as well. Like

jQuery.validator.addMethod('PHONE',function() {
        *check both inputs, return true if both correct*
})


问:
Unity 5 3d Shop menu with prefabs
Can someone tell me how to implement other player prefabs as a shop menu LIKE THIS.

答:
I'm going to assume that every pink rectangle is a prefab.

First, you need to understand the concept of prefabs.

Second, you need to know how to instantiate a prefab in run time.

Third, you need to acces the properties for your new fresh instantiate game object so you can change the information of that prefab if you want, maybe you want some values to be 200 instead of 100, idk.

Finally, ther's no "right way" to achieve this, but I recommend you to use Unity UI and scroll rect to achieve your goal.

If you have some time to experiment there will be a good idea to check out a pooling system so you doesn't need to use so much memory at instantiate and destroying objects at runtime, you just reuse them.

Hope it helps.

Title: Unity 5 3d Shop menu with prefabs


问:
How to store API data (array) into database with php
I am having error trying to store data into a database. I need help on how best to fix this my code, so that my array content can be stored in a my database. When I tried to echo the content, it worked not to store the data in my database is the problem.
Here is my code:

```<code>foreach ($data['players'] as $myp) {
//    echo $myp["name"]."<br>";
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

//insert into mysql table
mysql_select_db($db, $conn); //database and connection

$date = date('Y-m-d H:m:s'); //date stamp formatting
//sql query that insert the user info into the database
$sql =  "INSERT INTO staffdb ( Name, Position, Nationality, Market, Created)
        VALUES($name, $posi, $nation, $market, $date)";
echo $name . "<br>";
//if the connection is sucessful, display regards message
if (mysql_query($sql, $conn)) {
    echo "Thank you <br/>";
} else {   //if the connection is not established
    die('Error: ' . mysql_error());
}
</code>```

Here is the error I was getting:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Costa, Centre Forward, Spain, 45,000,000 €, 2017-03-31 23:03:04)' at line 2

In the error it printed the right value which i would like to be instead stored in the database.

Kindly correct my SQL part so that I can get my foreach data into my database.

Thanks alot!

答:
You need quotes around your values. In addition you should use PDO and bind those values.</p>

```<code>$sql =  "INSERT INTO staffdb ( Name, Position, Nationality, Market, Created)
        VALUES('$name', '$posi', '$nation', '$market', '$date')";
</code>```

Body:
I am having error trying to store data into a database. I need help on how best to fix this my code, so that my array content can be stored in a my database. When I tried to echo the content, it worked not to store the data in my database is the problem.
Here is my code:

foreach ($data['players'] as $myp) {
//    echo $myp["name"]."
";
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

//insert into mysql table
mysql_select_db($db, $conn); //database and connection

$date = date('Y-m-d H:m:s'); //date stamp formatting
//sql query that insert the user info into the database
$sql =  "INSERT INTO staffdb ( Name, Position, Nationality, Market, Created)
        VALUES($name, $posi, $nation, $market, $date)";
echo $name . "
";
//if the connection is sucessful, display regards message
if (mysql_query($sql, $conn)) {
    echo "Thank you
";
} else {   //if the connection is not established
    die('Error: ' . mysql_error());
}

Here is the error I was getting:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Costa, Centre Forward, Spain, 45,000,000 €, 2017-03-31 23:03:04)' at line 2

In the error it printed the right value which i would like to be instead stored in the database.

Kindly correct my SQL part so that I can get my foreach data into my database.

Thanks alot!

Body:
You need quotes around your values. In addition you should use PDO and bind those values.

$sql =  "INSERT INTO staffdb ( Name, Position, Nationality, Market, Created)
        VALUES('$name', '$posi', '$nation', '$market', '$date')";


问:
WPF Update binding properties of multiple items contained in a list at the same time
I'm binding a list of object to an ItemsControl which contain a TextBox control.

I want to be able to change the textbox background color based on the background color property of the bind object.

It works perfectly with the INotifyPropertyChanged interface but when I need to update let say 1000 objects it takes a huge amount of time I guess because it needs to update the controls one by one.

Does someone has a tip for me to lets say, update all my objects background color and than update the binding in one shot instead of object by object?

Thanks,

Mat

答:
I finally found why it was taking me so long to update my UI. Byt the way, What I'm trying to achieve is a kind of spreadsheet grid. My cell container was a border with the borders visible. I was updating the Border control Background color based on cell selection. Disabling the borders of the Border control resolved my issue right away. The UI update time went from 4-5 seconds to instantaneous.

Thank you guys for your answer, I will still try to implement your suggestion to improve even more my project.

Thanks

Mat


答:
You need single quotes around your field names:

```<code>$sql =  "INSERT INTO staffdb ( Name, Position, Nationality, Market, Created)
    VALUES('$name', '$posi', '$nation', '$market', '$date')";
</code>```

You should read up on SQL injection as your code is very vulnerable.

Also, you should move the closing } tag from your foreach loop so it comes at the end of your code. That way each item in your array will be added to your database.

Title: How to store API data (array) into database with php

Body:
You need single quotes around your field names:

$sql =  "INSERT INTO staffdb ( Name, Position, Nationality, Market, Created)
    VALUES('$name', '$posi', '$nation', '$market', '$date')";

You should read up on SQL injection as your code is very vulnerable.

Also, you should move the closing } tag from your foreach loop so it comes at the end of your code. That way each item in your array will be added to your database.


问:
Changing XLSX form control location with Apache POI
I've some number of xlsm files containing form controls. I'd like to programmatically move a particular button down a few rows on each sheet. My first hope was to do something like this:

```<code>FileInputStream inputStream = new FileInputStream(new File("t.xlsm"));
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet xs = (XSSFSheet)wb.getSheetAt(1);
RelationPart rp = xs.getRelationParts().get(0);
XSSFDrawing drawing = (XSSFDrawing)rp.getDocumentPart();

for(XSSFShape sh : drawing.getShapes()){
    XSSFClientAnchor a = (XSSFClientAnchor)sh.getAnchor();
    if (sh.getShapeName().equals("Button 2")) {
        a.setRow1(a.getRow1()+10);
        a.setRow2(a.getRow2()+10);
    }
}
</code>```

However, the shape objects given by XSSFDrawing.getShapes() are copies and any changes to them are not reflected in the document after a wb.write().

I tried a couple other approaches, such as getting the CTShape and parsing the XML within but things quickly got hairy.

Is there a recommended way to manage form controls like this via POI?

答:
I ended up fiddling directly with the XML:

```<code>wb = new XSSFWorkbook(new File(xlsmFile));
XSSFSheet s = wb.getSheet("TWO");
XmlObject[] subobj = s.getCTWorksheet().selectPath(declares+
            " .//mc:AlternateContent/mc:Choice/main:controls/mc:AlternateContent/mc:Choice/main:control");

String targetButton = "Button 2";
int rowsDown = 10;

for (XmlObject obj : subobj) {
    XmlCursor cursor = obj.newCursor();
    cursor.push();
    String attrName = cursor.getAttributeText(new QName("name"));
    if (attrName.equals(targetButton)) {
        cursor.selectPath(declares+" .//main:from/xdr:row");
        if (!cursor.toNextSelection()) {
            throw new Exception();
        }
        int newRow = Integer.parseInt(cursor.getTextValue()) + rowsDown;
        cursor.setTextValue(Integer.toString(newRow));

        cursor.pop();
        cursor.selectPath(declares+" .//main:to/xdr:row");
        if (!cursor.toNextSelection()) {
            throw new Exception();
        }
        newRow = Integer.parseInt(cursor.getTextValue()) + rowsDown;
        cursor.setTextValue(Integer.toString(newRow));
    }
    cursor.dispose();
}
</code>```

This moves the named button down 10 rows. I had to discover the button name (which may not be easy to do via Excel, I inspected the file directly). I'm guessing this is going to be very sensitive to the version of Excel in use.

Body:
I've some number of xlsm files containing form controls. I'd like to programmatically move a particular button down a few rows on each sheet. My first hope was to do something like this:

FileInputStream inputStream = new FileInputStream(new File("t.xlsm"));
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet xs = (XSSFSheet)wb.getSheetAt(1);
RelationPart rp = xs.getRelationParts().get(0);
XSSFDrawing drawing = (XSSFDrawing)rp.getDocumentPart();

for(XSSFShape sh : drawing.getShapes()){
    XSSFClientAnchor a = (XSSFClientAnchor)sh.getAnchor();
    if (sh.getShapeName().equals("Button 2")) {
        a.setRow1(a.getRow1()+10);
        a.setRow2(a.getRow2()+10);
    }
}

However, the shape objects given by XSSFDrawing.getShapes() are copies and any changes to them are not reflected in the document after a wb.write().

I tried a couple other approaches, such as getting the CTShape and parsing the XML within but things quickly got hairy.

Is there a recommended way to manage form controls like this via POI?

Body:
I ended up fiddling directly with the XML:

wb = new XSSFWorkbook(new File(xlsmFile));
XSSFSheet s = wb.getSheet("TWO");
XmlObject[] subobj = s.getCTWorksheet().selectPath(declares+
            " .//mc:AlternateContent/mc:Choice/main:controls/mc:AlternateContent/mc:Choice/main:control");

String targetButton = "Button 2";
int rowsDown = 10;

for (XmlObject obj : subobj) {
    XmlCursor cursor = obj.newCursor();
    cursor.push();
    String attrName = cursor.getAttributeText(new QName("name"));
    if (attrName.equals(targetButton)) {
        cursor.selectPath(declares+" .//main:from/xdr:row");
        if (!cursor.toNextSelection()) {
            throw new Exception();
        }
        int newRow = Integer.parseInt(cursor.getTextValue()) + rowsDown;
        cursor.setTextValue(Integer.toString(newRow));

        cursor.pop();
        cursor.selectPath(declares+" .//main:to/xdr:row");
        if (!cursor.toNextSelection()) {
            throw new Exception();
        }
        newRow = Integer.parseInt(cursor.getTextValue()) + rowsDown;
        cursor.setTextValue(Integer.toString(newRow));
    }
    cursor.dispose();
}

This moves the named button down 10 rows. I had to discover the button name (which may not be easy to do via Excel, I inspected the file directly). I'm guessing this is going to be very sensitive to the version of Excel in use.