问:
mongodb BSON Object error
I am using

```<code>GroupBy groupBy = GroupBy.key("Dimension","frequency")
            .initialDocument("{ value: 0 }")
            .reduceFunction("function(obj, result) { " +
                            "  result.Dimension = obj.Dimension; " +
                            "  result.frequency = obj.frequency; " +
                            "  result.value += obj.value; " +
                            "}");
</code>```

with dependencies

```<code>    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.0.4.RELEASE</version>
    </dependency>

<dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>2.9.1</version>
    </dependency>
</code>```

It is working fine with mongodb version 3.0.3

But is throwing error when I am using mongodb version 3.2.0

Here is the exception

```<code>HTTP Status 500 - org.apache.cxf.interceptor.Fault: Command execution failed: Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) { result.Dimension = obj.Dimension; result.frequency = obj.frequency; result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}

type Exception report

message org.apache.cxf.interceptor.Fault: Command execution failed: Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) { result.Dimension = obj.Dimension; result.frequency = obj.frequency; result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.RuntimeException: org.apache.cxf.interceptor.Fault: Command execution failed:  Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) {   result.Dimension = obj.Dimension;   result.frequency = obj.frequency;   result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}
    org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:116)
    org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:322)
    org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122)
    org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)
    org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)
    org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:129)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:115)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

org.apache.cxf.interceptor.Fault: Command execution failed:  Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) {   result.Dimension = obj.Dimension;   result.frequency = obj.frequency;   result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}
    org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:162)
    org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:128)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:167)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:94)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)
    java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    java.util.concurrent.FutureTask.run(FutureTask.java:266)
    org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:106)
    org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
    org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122)
    org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)
    org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)
    org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:129)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:115)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

org.springframework.dao.InvalidDataAccessApiUsageException: Command execution failed:  Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) {   result.Dimension = obj.Dimension;   result.frequency = obj.frequency;   result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}
    org.springframework.data.mongodb.core.MongoTemplate.handleCommandError(MongoTemplate.java:1566)
    org.springframework.data.mongodb.core.MongoTemplate.group(MongoTemplate.java:1068)
    com.org.project.repo.repositories.repository.getMetadataDetails(repository.java:253)
    com.org.project.repo.business.repoDataBoEntity.getMetadataDetails(repoDataBoEntity.java:580)
    com.org.project.endpoints.PublicData.getMetadataDetails(PublicData.java:304)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:180)
    org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:167)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:94)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)
    java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    java.util.concurrent.FutureTask.run(FutureTask.java:266)
    org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:106)
    org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
    org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122)
    org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)
    org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)
    org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:129)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:115)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}
    com.mongodb.CommandResult.getException(CommandResult.java:88)
    com.mongodb.CommandResult.throwOnError(CommandResult.java:134)
    org.springframework.data.mongodb.core.MongoTemplate.handleCommandError(MongoTemplate.java:1560)
    org.springframework.data.mongodb.core.MongoTemplate.group(MongoTemplate.java:1068)
    com.org.project.repo.repositories.repository.getMetadataDetails(repository.java:253)
    com.org.project.repo.business.repoDataBoEntity.getMetadataDetails(repoDataBoEntity.java:580)
    com.org.project.endpoints.PublicData.getMetadataDetails(PublicData.java:304)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:180)
    org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:167)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:94)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)
    java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    java.util.concurrent.FutureTask.run(FutureTask.java:266)
    org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:106)
    org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
    org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122)
    org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)
    org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)
    org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:129)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:115)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

note The full stack trace of the root cause is available in the Apache Tomcat/8.0.9 logs.
Apache Tomcat/8.0.9
</code>```

Please help me. What am I doing wrong?

Thanks in advance.

答:
not anything you did, this was a bug introduced in 3.2, fixed in 3.4.
It bit us too while upgrading from 2.6 -> 3.0 -> 3.2 -> 3.4</p>

Title: mongodb BSON Object error

Body:
I am using

GroupBy groupBy = GroupBy.key("Dimension","frequency")
            .initialDocument("{ value: 0 }")
            .reduceFunction("function(obj, result) { " +
                            "  result.Dimension = obj.Dimension; " +
                            "  result.frequency = obj.frequency; " +
                            "  result.value += obj.value; " +
                            "}");

with dependencies

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.0.4.RELEASE</version>
    </dependency>

<dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>2.9.1</version>
    </dependency>

It is working fine with mongodb version 3.0.3

But is throwing error when I am using mongodb version 3.2.0

Here is the exception

HTTP Status 500 - org.apache.cxf.interceptor.Fault: Command execution failed: Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) { result.Dimension = obj.Dimension; result.frequency = obj.frequency; result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}

type Exception report

message org.apache.cxf.interceptor.Fault: Command execution failed: Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) { result.Dimension = obj.Dimension; result.frequency = obj.frequency; result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.RuntimeException: org.apache.cxf.interceptor.Fault: Command execution failed:  Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) {   result.Dimension = obj.Dimension;   result.frequency = obj.frequency;   result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}
    org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:116)
    org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:322)
    org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122)
    org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)
    org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)
    org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:129)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:115)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

org.apache.cxf.interceptor.Fault: Command execution failed:  Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) {   result.Dimension = obj.Dimension;   result.frequency = obj.frequency;   result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}
    org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:162)
    org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:128)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:167)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:94)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)
    java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    java.util.concurrent.FutureTask.run(FutureTask.java:266)
    org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:106)
    org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
    org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122)
    org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)
    org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)
    org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:129)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:115)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

org.springframework.dao.InvalidDataAccessApiUsageException: Command execution failed:  Error [Failure to enumerate object], Command = { "group" : { "key" : { "Dimension" : 1 , "frequency" : 1} , "$reduce" : "function(obj, result) {   result.Dimension = obj.Dimension;   result.frequency = obj.frequency;   result.value += obj.value; }" , "initial" : { "value" : 0} , "ns" : "projectentity" , "cond" : { "api_source_name" : { "$in" : [ "Score1"]} , "category" : { "$in" : [ "Score1"]} , "dataset" : { "$in" : [ "Score"]} , "active_flag" : { "$in" : [ "y"]}}}}; nested exception is com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}
    org.springframework.data.mongodb.core.MongoTemplate.handleCommandError(MongoTemplate.java:1566)
    org.springframework.data.mongodb.core.MongoTemplate.group(MongoTemplate.java:1068)
    com.org.project.repo.repositories.repository.getMetadataDetails(repository.java:253)
    com.org.project.repo.business.repoDataBoEntity.getMetadataDetails(repoDataBoEntity.java:580)
    com.org.project.endpoints.PublicData.getMetadataDetails(PublicData.java:304)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:180)
    org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:167)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:94)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)
    java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    java.util.concurrent.FutureTask.run(FutureTask.java:266)
    org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:106)
    org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
    org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122)
    org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)
    org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)
    org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:129)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:115)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

com.mongodb.CommandResult$CommandFailure: command failed [group]: { "serverUsed" : "/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "Failure to enumerate object" , "code" : 139}
    com.mongodb.CommandResult.getException(CommandResult.java:88)
    com.mongodb.CommandResult.throwOnError(CommandResult.java:134)
    org.springframework.data.mongodb.core.MongoTemplate.handleCommandError(MongoTemplate.java:1560)
    org.springframework.data.mongodb.core.MongoTemplate.group(MongoTemplate.java:1068)
    com.org.project.repo.repositories.repository.getMetadataDetails(repository.java:253)
    com.org.project.repo.business.repoDataBoEntity.getMetadataDetails(repoDataBoEntity.java:580)
    com.org.project.endpoints.PublicData.getMetadataDetails(PublicData.java:304)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:180)
    org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:167)
    org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:94)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)
    java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    java.util.concurrent.FutureTask.run(FutureTask.java:266)
    org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
    org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:106)
    org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
    org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122)
    org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)
    org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)
    org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:129)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:115)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

note The full stack trace of the root cause is available in the Apache Tomcat/8.0.9 logs.
Apache Tomcat/8.0.9

Please help me. What am I doing wrong?

Thanks in advance.


来源: stackexchange

问:
Associative array: how to get the key of the current element which is an array
I have an array

```<code>Array (
      [0] => Array ( [2006] => Array ( [0] => 12 ) )
      [1] => Array ( [2004] => Array ( [0] => 12 [1] => 6 ) )
)
</code>```

How do I get the year so I can generate the folllowing using unordered list

```<code>2006
    December
2004
    December
    June
</code>```

答:
You can try:</p>

```<code>$arr = Array(
  0 => Array(
    2006 => Array(
      0 => 12
    )
  ),
  1 => Array(
    2004 => Array(
      0 => 12,
      1 => 6
    )
  )
) ;

echo "<ul>\n";
foreach ($arr as $elem) {
  foreach ($elem as $year => $months) {
    echo "<li>$year\n<ul>\n";
    foreach ($months as $num => $month) {
        echo strftime("<li>%B</li>\n", mktime(0, 0, 0, $month));
    }
    echo "</ul>\n</li>\n";
  }
}
echo "</ul>\n";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array

Array (
      [0] => Array ( [2006] => Array ( [0] => 12 ) )
      [1] => Array ( [2004] => Array ( [0] => 12 [1] => 6 ) )
)

How do I get the year so I can generate the folllowing using unordered list

2006
    December
2004
    December
    June

Body:
You can try:

$arr = Array(
  0 => Array(
    2006 => Array(
      0 => 12
    )
  ),
  1 => Array(
    2004 => Array(
      0 => 12,
      1 => 6
    )
  )
) ;

echo "<ul>\n";
foreach ($arr as $elem) {
  foreach ($elem as $year => $months) {
    echo "<li>$year\n<ul>\n";
    foreach ($months as $num => $month) {
        echo strftime("<li>%B</li>\n", mktime(0, 0, 0, $month));
    }
    echo "</ul>\n</li>\n";
  }
}
echo "</ul>\n";

ContentLicense: CC BY-SA 2.5


问:
PHP- Unable to Access Data from DB in dropdown menu
I am trying to create a drop down menu that will display Project Names off all Projects present in  the table Project in the database Testing... The drop down is created but it is not accessing the database and retrieving the required data...
The code is as follows:

```<code><html>
<head>
<title>Dynamic Drop Down List</title>
</head>

    <form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
        Project List :
        <select Project Name='NEW'>
        <option value="">--- Select ---</option>
        <?
            $serverName = "Swagatha-PC";
            $connectionInfo = array( "Database"=>"Testing");
            $conn = sqlsrv_connect( $serverName, $connectionInfo);

            if( $conn )
            {
            echo "Connection established.<br />";
            }
            else
            {
            echo "Connection could not be established.<br />";
            die( print_r( sqlsrv_errors(), true));
            }
            if (isset ($select)&&$select!="")
            {
            $select=$_POST ['NEW'];
        }
        ?>
        <?
            $query=mysql_query("select ProjectName from dbo.Project");
            $menu=" ";
            while($row = sqlsrv_fetch_array($query))
            {
               $menu ="<option>" . $row["ProjectName"] . "</option>";
            }

            ?>
        </select>
        <input type="submit" name="Next" value="Select" />
    </form>
</body>
</html>
</code>```

Dropdown Error

What Do i do to fix this??

答:
The solution is

```<code>while($row = sqlsrv_fetch_array($query))
{
   echo "<option>" . $row["ProjectName"] . "</option>";
}
</code>```

See? You output data with echo instead assinging data to variable.

And as @FirstOne noticed using mysql_query with sqlsrv_connect is an error too. I hope it's just your typo:

```<code>$query=sqlsrv_query($conn, "select ProjectName from dbo.Project");
</code>```

As another sidenote

```<code>if (isset ($select)&&$select!="")
{
    $select=$_POST ['NEW'];
}
</code>```

this if will always be false, because you first check $select and then define it. It definitely should be:

```<code>if (isset($_POST['NEW']) && $_POST['NEW'] != "")
{
    $select = $_POST['NEW'];
}
</code>```

Body:
I am trying to create a drop down menu that will display Project Names off all Projects present in  the table Project in the database Testing... The drop down is created but it is not accessing the database and retrieving the required data...
The code is as follows:

<title>Dynamic Drop Down List</title>

    <form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
        Project List :
        <select Project Name='NEW'>
        <option value="">--- Select ---</option>
        <?
            $serverName = "Swagatha-PC";
            $connectionInfo = array( "Database"=>"Testing");
            $conn = sqlsrv_connect( $serverName, $connectionInfo);

            if( $conn )
            {
            echo "Connection established.
";
            }
            else
            {
            echo "Connection could not be established.
";
            die( print_r( sqlsrv_errors(), true));
            }
            if (isset ($select)&&$select!="")
            {
            $select=$_POST ['NEW'];
        }
        ?>
        <?
            $query=mysql_query("select ProjectName from dbo.Project");
            $menu=" ";
            while($row = sqlsrv_fetch_array($query))
            {
               $menu ="<option>" . $row["ProjectName"] . "</option>";
            }

            ?>
        </select>
        <input type="submit" name="Next" value="Select" />
    </form>

Dropdown Error

What Do i do to fix this??

Body:
The solution is

while($row = sqlsrv_fetch_array($query))
{
   echo "<option>" . $row["ProjectName"] . "</option>";
}

See? You output data with echo instead assinging data to variable.

And as @FirstOne noticed using mysql_query with sqlsrv_connect is an error too. I hope it's just your typo:

$query=sqlsrv_query($conn, "select ProjectName from dbo.Project");

As another sidenote

if (isset ($select)&&$select!="")
{
    $select=$_POST ['NEW'];
}

this if will always be false, because you first check $select and then define it. It definitely should be:

if (isset($_POST['NEW']) && $_POST['NEW'] != "")
{
    $select = $_POST['NEW'];
}


问:
Microsoft Cognitive Bing Search API (v5) returning incorrect results
I would like to take a beer and search on Bing to return a result from http://ratebeer.com. The results I've gotten are mostly good but some results are (what I think) wrong.

One of the beers I've encountered problems with is named "Kolk Maak Amber Ale".

Using R and the httr package, my code is:

```<code>url <- https://api.cognitive.microsoft.com/bing/v5.0/search?q=Kolk+Maak+Amber+Ale+site:http://ratebeer.com/beer&mkt=en-us
res <- GET(url,
          add_headers("Ocp-Apim-Subscription-Key"=APIkey))
</code>```

where "APIkey" is my personal key from Microsoft-Cognitive-Services.
The results are:

```<code>> content(res)
$`_type`
[1] "SearchResponse"

$webPages
$webPages$webSearchUrl
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=28PvtjGreQkOBLSaPy_GCtmkd-G642-BVoJp814ve_8&v=1&r=https%3a%2f%2fwww.bing.com%2fsearch%3fq%3dKolk%2bMaak%2bAmber%2bAle%2bsite%253ahttp%253a%252f%252fratebeer.com%252fbeer&p=DevEx,5148.1"

$webPages$totalEstimatedMatches
[1] 3

$webPages$value
$webPages$value[[1]]
$webPages$value[[1]]$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.0"

$webPages$value[[1]]$name
[1] "North River Grisette du Noorden - ratebeer.com"

$webPages$value[[1]]$url
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=71h-PtMgTQkVXsH3vxpLLwGtkRp4nyYvBbVMTwc47XM&v=1&r=https%3a%2f%2fwww.ratebeer.com%2fbeer%2fnorth-river-grisette-du-noorden%2f492033%2f&p=DevEx,5056.1"

$webPages$value[[1]]$displayUrl
[1] "https://www.ratebeer.com/beer/north-river-grisette-du-noorden/492033"

$webPages$value[[1]]$snippet
[1] "North River Grisette du Noorden a Traditional Ale beer by North ... Pours a hazed amber with a medium ... Jopen Stripbier 2016: Tania (Hanco Kolk) 82 Jopen Koyt 94"

$webPages$value[[1]]$dateLastCrawled
[1] "2017-04-13T12:56:00"

$webPages$value[[2]]
$webPages$value[[2]]$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.1"

$webPages$value[[2]]$name
[1] "Frankenheim Alt - ratebeer.com"

$webPages$value[[2]]$url
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=-1irhi3khCoAu383TebZwPJdZMjMAL9L5KH6Nfs668U&v=1&r=https%3a%2f%2fwww.ratebeer.com%2fbeer%2ffrankenheim-alt%2f11335%2f&p=DevEx,5068.1"

$webPages$value[[2]]$displayUrl
[1] "https://www.ratebeer.com/beer/frankenheim-alt/11335"

$webPages$value[[2]]$snippet
[1] "... donkere mouten, aangebrande caramel, metalig bitter, aards, noten, nee hier maak je ... Bottle 3 cl. Pours a hazy amber with a ... Element Interval Ale ..."

$webPages$value[[2]]$dateLastCrawled
[1] "2017-04-11T15:13:00"

$webPages$value[[3]]
$webPages$value[[3]]$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.2"

$webPages$value[[3]]$name
[1] "Cervoise Lancelot - ratebeer.com"

$webPages$value[[3]]$url
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=Fsu_98e2uQEcyl7FovpvzwTjtwLnOJvGezmVQvKAbPY&v=1&r=https%3a%2f%2fwww.ratebeer.com%2fbeer%2fcervoise-lancelot%2f9828%2f&p=DevEx,5080.1"

$webPages$value[[3]]$displayUrl
[1] "https://www.ratebeer.com/beer/cervoise-lancelot/9828"

$webPages$value[[3]]$snippet
[1] "Cervoise Lancelot a Traditional Ale beer by Lancelot, ... Slightly hazy amber with quick diminishing head. Sweet malts, ... (Hanco Kolk) 82"

$webPages$value[[3]]$dateLastCrawled
[1] "2017-04-13T18:28:00"

$rankingResponse
$rankingResponse$mainline
$rankingResponse$mainline$items
$rankingResponse$mainline$items[[1]]
$rankingResponse$mainline$items[[1]]$answerType
[1] "WebPages"

$rankingResponse$mainline$items[[1]]$resultIndex
[1] 0

$rankingResponse$mainline$items[[1]]$value
$rankingResponse$mainline$items[[1]]$value$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.0"

$rankingResponse$mainline$items[[2]]
$rankingResponse$mainline$items[[2]]$answerType
[1] "WebPages"

$rankingResponse$mainline$items[[2]]$resultIndex
[1] 1

$rankingResponse$mainline$items[[2]]$value
$rankingResponse$mainline$items[[2]]$value$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.1"

$rankingResponse$mainline$items[[3]]
$rankingResponse$mainline$items[[3]]$answerType
[1] "WebPages"

$rankingResponse$mainline$items[[3]]$resultIndex
[1] 2

$rankingResponse$mainline$items[[3]]$value
$rankingResponse$mainline$items[[3]]$value$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.2"
</code>```

As you can see here, none of the three beers listed show the correct beer which is searched for (Kolk Maak Amber Ale). However, if I follow the search response link from

```<code>content(res)$webPages$webSearchUrl
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=28PvtjGreQkOBLSaPy_GCtmkd-G642-BVoJp814ve_8&v=1&r=https%3a%2f%2fwww.bing.com%2fsearch%3fq%3dKolk%2bMaak%2bAmber%2bAle%2bsite%253ahttp%253a%252f%252fratebeer.com%252fbeer&p=DevEx,5148.1"
</code>```

using a browser(Chrome/Firefox/IE) I get the correct beer as a first result.

Why is this happening? Why do all search values return the wrong url, but using a physical browser for it returns the right url? Other beers that I have tested this on return the right url.

答:
This is very interesting.  If you type this into the search box, with pluses, you get the right results from Bing.  Without them, you don't get the right page:

Kolk+Maak+Amber+Ale+site:ratebeer.com

Also, this version provides the right result:
site:ratebeer.com Kolk Maak ale amber

But this version doesn't work:
site:ratebeer.com Kolk Maak amber ale

Body:
I would like to take a beer and search on Bing to return a result from http://ratebeer.com. The results I've gotten are mostly good but some results are (what I think) wrong.

One of the beers I've encountered problems with is named "Kolk Maak Amber Ale".

Using R and the httr package, my code is:

url <- https://api.cognitive.microsoft.com/bing/v5.0/search?q=Kolk+Maak+Amber+Ale+site:http://ratebeer.com/beer&mkt=en-us
res <- GET(url,
          add_headers("Ocp-Apim-Subscription-Key"=APIkey))

where "APIkey" is my personal key from Microsoft-Cognitive-Services.
The results are:

> content(res)
$`_type`
[1] "SearchResponse"

$webPages
$webPages$webSearchUrl
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=28PvtjGreQkOBLSaPy_GCtmkd-G642-BVoJp814ve_8&v=1&r=https%3a%2f%2fwww.bing.com%2fsearch%3fq%3dKolk%2bMaak%2bAmber%2bAle%2bsite%253ahttp%253a%252f%252fratebeer.com%252fbeer&p=DevEx,5148.1"

$webPages$totalEstimatedMatches
[1] 3

$webPages$value
$webPages$value[[1]]
$webPages$value[[1]]$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.0"

$webPages$value[[1]]$name
[1] "North River Grisette du Noorden - ratebeer.com"

$webPages$value[[1]]$url
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=71h-PtMgTQkVXsH3vxpLLwGtkRp4nyYvBbVMTwc47XM&v=1&r=https%3a%2f%2fwww.ratebeer.com%2fbeer%2fnorth-river-grisette-du-noorden%2f492033%2f&p=DevEx,5056.1"

$webPages$value[[1]]$displayUrl
[1] "https://www.ratebeer.com/beer/north-river-grisette-du-noorden/492033"

$webPages$value[[1]]$snippet
[1] "North River Grisette du Noorden a Traditional Ale beer by North ... Pours a hazed amber with a medium ... Jopen Stripbier 2016: Tania (Hanco Kolk) 82 Jopen Koyt 94"

$webPages$value[[1]]$dateLastCrawled
[1] "2017-04-13T12:56:00"

$webPages$value[[2]]
$webPages$value[[2]]$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.1"

$webPages$value[[2]]$name
[1] "Frankenheim Alt - ratebeer.com"

$webPages$value[[2]]$url
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=-1irhi3khCoAu383TebZwPJdZMjMAL9L5KH6Nfs668U&v=1&r=https%3a%2f%2fwww.ratebeer.com%2fbeer%2ffrankenheim-alt%2f11335%2f&p=DevEx,5068.1"

$webPages$value[[2]]$displayUrl
[1] "https://www.ratebeer.com/beer/frankenheim-alt/11335"

$webPages$value[[2]]$snippet
[1] "... donkere mouten, aangebrande caramel, metalig bitter, aards, noten, nee hier maak je ... Bottle 3 cl. Pours a hazy amber with a ... Element Interval Ale ..."

$webPages$value[[2]]$dateLastCrawled
[1] "2017-04-11T15:13:00"

$webPages$value[[3]]
$webPages$value[[3]]$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.2"

$webPages$value[[3]]$name
[1] "Cervoise Lancelot - ratebeer.com"

$webPages$value[[3]]$url
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=Fsu_98e2uQEcyl7FovpvzwTjtwLnOJvGezmVQvKAbPY&v=1&r=https%3a%2f%2fwww.ratebeer.com%2fbeer%2fcervoise-lancelot%2f9828%2f&p=DevEx,5080.1"

$webPages$value[[3]]$displayUrl
[1] "https://www.ratebeer.com/beer/cervoise-lancelot/9828"

$webPages$value[[3]]$snippet
[1] "Cervoise Lancelot a Traditional Ale beer by Lancelot, ... Slightly hazy amber with quick diminishing head. Sweet malts, ... (Hanco Kolk) 82"

$webPages$value[[3]]$dateLastCrawled
[1] "2017-04-13T18:28:00"

$rankingResponse
$rankingResponse$mainline
$rankingResponse$mainline$items
$rankingResponse$mainline$items[[1]]
$rankingResponse$mainline$items[[1]]$answerType
[1] "WebPages"

$rankingResponse$mainline$items[[1]]$resultIndex
[1] 0

$rankingResponse$mainline$items[[1]]$value
$rankingResponse$mainline$items[[1]]$value$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.0"

$rankingResponse$mainline$items[[2]]
$rankingResponse$mainline$items[[2]]$answerType
[1] "WebPages"

$rankingResponse$mainline$items[[2]]$resultIndex
[1] 1

$rankingResponse$mainline$items[[2]]$value
$rankingResponse$mainline$items[[2]]$value$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.1"

$rankingResponse$mainline$items[[3]]
$rankingResponse$mainline$items[[3]]$answerType
[1] "WebPages"

$rankingResponse$mainline$items[[3]]$resultIndex
[1] 2

$rankingResponse$mainline$items[[3]]$value
$rankingResponse$mainline$items[[3]]$value$id
[1] "https://api.cognitive.microsoft.com/api/v5/#WebPages.2"

As you can see here, none of the three beers listed show the correct beer which is searched for (Kolk Maak Amber Ale). However, if I follow the search response link from

content(res)$webPages$webSearchUrl
[1] "https://www.bing.com/cr?IG=8E30DC638C5B48E592061644988A6924&CID=08A1C0B86E4C6A7527FCCADF6FAB6BD5&rd=1&h=28PvtjGreQkOBLSaPy_GCtmkd-G642-BVoJp814ve_8&v=1&r=https%3a%2f%2fwww.bing.com%2fsearch%3fq%3dKolk%2bMaak%2bAmber%2bAle%2bsite%253ahttp%253a%252f%252fratebeer.com%252fbeer&p=DevEx,5148.1"

using a browser(Chrome/Firefox/IE) I get the correct beer as a first result.

Why is this happening? Why do all search values return the wrong url, but using a physical browser for it returns the right url? Other beers that I have tested this on return the right url.


问:
Schedule daily a task in meteor
I am using percolate:synced-cron in my meteor app. I am following the tutorial here http://richsilv.github.io/meteor/scheduling-events-in-the-future-with-meteor/

I am confused in part of

```<code>function scheduleMail(details) {

    if (details.date < new Date()) {
        sendMail(details);
    } else {
        var thisId = FutureTasks.insert(details);
        addTask(thisId, details);
    }
    return true;

}
</code>```

and in

```<code>FutureTasks.find().forEach(function(mail) {
    if (mail.date < new Date()) {
        sendMail(mail)
    } else {
        addTask(mail._id, mail);
    }
});
</code>```

Anyone can explain more about these two part of codes?
Also how can I make the task run every day at midnight?

答:
The first part send the mail if it's supposed to be send immediately else execute addTask function which create a cron to be executed at a specific date. When the cron is executed the mail is sent and the task and cron then deleted.

the second part is launched at startup to send mail that where not sent when the server is down following the same process

It is my personal opinion that this is rather ineffective since a cron is created then deleted which is not reusable.

If you want to run a cron every day at midnight here how it works:

```<code>SyncedCron.add({
    name: "NAME",
    schedule: function(parser) {
        return parser.cron("0 0 * * *");
    },
    job: function() {
        //execute your task
    }
});
</code>```

Title: Schedule daily a task in meteor

Body:
I am using percolate:synced-cron in my meteor app. I am following the tutorial here http://richsilv.github.io/meteor/scheduling-events-in-the-future-with-meteor/

I am confused in part of

function scheduleMail(details) {

    if (details.date < new Date()) {
        sendMail(details);
    } else {
        var thisId = FutureTasks.insert(details);
        addTask(thisId, details);
    }
    return true;

}

and in

FutureTasks.find().forEach(function(mail) {
    if (mail.date < new Date()) {
        sendMail(mail)
    } else {
        addTask(mail._id, mail);
    }
});

Anyone can explain more about these two part of codes?
Also how can I make the task run every day at midnight?

Body:
The first part send the mail if it's supposed to be send immediately else execute addTask function which create a cron to be executed at a specific date. When the cron is executed the mail is sent and the task and cron then deleted.

the second part is launched at startup to send mail that where not sent when the server is down following the same process

It is my personal opinion that this is rather ineffective since a cron is created then deleted which is not reusable.

If you want to run a cron every day at midnight here how it works:

SyncedCron.add({
    name: "NAME",
    schedule: function(parser) {
        return parser.cron("0 0 * * *");
    },
    job: function() {
        //execute your task
    }
});


问:
Getting the binary value of a character string in Powershell
```<code>$getInput = Read-Host "ASCII or Binary? `n"
$getInput = $getInput.toLower()

if($getInput -eq "ascii"){

    ""

    #Write-Host "Type In Your ASCII" -backgroundcolor "black"
    $getAscii = Read-Host "Type In Your ASCII`n"
    ""
    ""
    $readAscii = @($getAscii)
    [byte[]]$outBytes = $readAscii

}
elseif($getInput -eq "binary"){

}
else{
    Write-Host "Wrong Input... [ASCII] or [BINARY]" -backgroundcolor "red" -foregroundcolor "white"
}
</code>```

I want to be able to get a users paragraph or whatever string they put in and convert it to binary. The [conver]::toString($getAscii,2) only works for integers.

答:
```<code>'hello world' -split '' | % {
    if ($_ -ne '') {
        #[int][char]$_
        [System.Convert]::ToString(([int][char]$_),2)
    }
}
</code>```

Use the split operator to split the string by each character

Send that down the pipeline to a foreach-object loop

The split operation ends up including the space character in the string
so the conditional makes sure we don't act upon it--we filter it out.

The commented line was for testing purposes.  Each character has a
TYPE of [string] and we need it as a [char] so we explicitly cast it
as such and the PowerShell engine dynamically switches it for us (as
long as it can).  In the same line, we explicitly cast the [char] to
an [int] to get the ASCII->decimal representation.  This test was just to
ensure I was getting the right output and I left it commented in
case the OP wanted to see it.

Finally, we use the ToString() method of the System.Convert class which accepts a "base"
parameter to define that we want a base2 (binary) representation of
the integer supplied in position 1, casted as TYPE [string].

Body:
$getInput = Read-Host "ASCII or Binary? `n"
$getInput = $getInput.toLower()

if($getInput -eq "ascii"){

    ""

    #Write-Host "Type In Your ASCII" -backgroundcolor "black"
    $getAscii = Read-Host "Type In Your ASCII`n"
    ""
    ""
    $readAscii = @($getAscii)
    [byte[]]$outBytes = $readAscii

}
elseif($getInput -eq "binary"){

}
else{
    Write-Host "Wrong Input... [ASCII] or [BINARY]" -backgroundcolor "red" -foregroundcolor "white"
}

I want to be able to get a users paragraph or whatever string they put in and convert it to binary. The [conver]::toString($getAscii,2) only works for integers.

Body:
'hello world' -split '' | % {
    if ($_ -ne '') {
        #[int][char]$_
        [System.Convert]::ToString(([int][char]$_),2)
    }
}

Use the split operator to split the string by each character

Send that down the pipeline to a foreach-object loop

The split operation ends up including the space character in the string
so the conditional makes sure we don't act upon it--we filter it out.

The commented line was for testing purposes.  Each character has a
TYPE of [string] and we need it as a [char] so we explicitly cast it
as such and the PowerShell engine dynamically switches it for us (as
long as it can).  In the same line, we explicitly cast the [char] to
an [int] to get the ASCII->decimal representation.  This test was just to
ensure I was getting the right output and I left it commented in
case the OP wanted to see it.

Finally, we use the ToString() method of the System.Convert class which accepts a "base"
parameter to define that we want a base2 (binary) representation of
the integer supplied in position 1, casted as TYPE [string].


问:
Python: condensing arbitrarily large dataframe query
I am using a pandas dataframe, and am iterating over all possible combinations of values in several columns.  I do this using itertools.combinations and pandas.Series.unique():

```<code>query_fields = ['direction','subj_id','speed']
query_items = [df_reps[k].unique() for k in query_fields]

for a in itertools.product(*query_items):
    df = df_reps[(df_reps['subj_id']==a[0]) & (df_reps['direction']==a[1]) & (df_reps['speed']==a[2])]
    #Do something with df
</code>```

I'm wondering if there is a more pythonic way of condensing my dataframe query.  If I had more possibly query fields then this approach would become increasingly unusable.  One possible method is to iterate over all the fields and apply each query individually (like a funnel) - could this be done with list comprehension, something like:

```<code>df = df_reps[(df_reps[qf]==a[i]) for qf,i in enumerate(query_fields)] #Doesn't work
</code>```

Does this functionality already exist in pandas?

EDIT

Input: A DataFrame and a list containing headers.

Output: A loop or similiar, selecting each unique combination of values in the columns specified by the header list.

答:
The problem of "iterating over all possible combinations of values in several columns" can be easily solved using pandas groupby.
Essentially you create groups based on the values of all the columns and then you retrieve the part of the data where each sequence occurs. No loops involved, it is a one-liner.

```<code>import pandas as pd
import numpy as np
import itertools

df = pd.DataFrame(np.random.randint(1,4, (100, 5)),
                  columns = ['direction','subj_id','speed','other1', 'other2'])

fields = ['direction','subj_id','speed']

grouped_by_values = df.groupby(fields)
queries_results = {key: group for key, group in grouped_by_values }
</code>```

Here is an example of the results:

```<code>for key, group in queries_results.iteritems():
#for key, group in grouped_by_values:  #Equivalent, probably better

    print key, group

(1, 1, 1)     direction  subj_id  speed  other1  other2
3           1        1      1       3       3
37          1        1      1       2       3
48          1        1      1       2       1
52          1        1      1       1       3
81          1        1      1       1       1
97          1        1      1       1       1
(1, 1, 2)     direction  subj_id  speed  other1  other2
25          1        1      2       2       3
62          1        1      2       3       1
</code>```

If instead you want to know how to "condense dataframe queries", here is an approach: generate a list of boolean masks (one for each condition) and then generating the intersection using reduce.

Here is an example:

```<code>import pandas as pd
import numpy as np

# Reproducible Example
df = pd.DataFrame(np.random.randint(1,4, (100, 3)), columns = ['A', 'B', 'C'])
query_fields = ['A','B','C']
query_items = [1,2,3]

# Individual masks
ind_masks = [df[key].eq(val) for key, val in zip(query_fields, query_items)]
# Combined Query
mask = reduce(lambda x, y: x & y, ind_masks)

query_result = df[mask]
</code>```

Body:
I am using a pandas dataframe, and am iterating over all possible combinations of values in several columns.  I do this using itertools.combinations and pandas.Series.unique():

query_fields = ['direction','subj_id','speed']
query_items = [df_reps[k].unique() for k in query_fields]

for a in itertools.product(*query_items):
    df = df_reps[(df_reps['subj_id']==a[0]) & (df_reps['direction']==a[1]) & (df_reps['speed']==a[2])]
    #Do something with df

I'm wondering if there is a more pythonic way of condensing my dataframe query.  If I had more possibly query fields then this approach would become increasingly unusable.  One possible method is to iterate over all the fields and apply each query individually (like a funnel) - could this be done with list comprehension, something like:

df = df_reps[(df_reps[qf]==a[i]) for qf,i in enumerate(query_fields)] #Doesn't work

Does this functionality already exist in pandas?

EDIT

Input: A DataFrame and a list containing headers.

Output: A loop or similiar, selecting each unique combination of values in the columns specified by the header list.

Body:
The problem of "iterating over all possible combinations of values in several columns" can be easily solved using pandas groupby.
Essentially you create groups based on the values of all the columns and then you retrieve the part of the data where each sequence occurs. No loops involved, it is a one-liner.

import pandas as pd
import numpy as np
import itertools

df = pd.DataFrame(np.random.randint(1,4, (100, 5)),
                  columns = ['direction','subj_id','speed','other1', 'other2'])

fields = ['direction','subj_id','speed']

grouped_by_values = df.groupby(fields)
queries_results = {key: group for key, group in grouped_by_values }

Here is an example of the results:

for key, group in queries_results.iteritems():
#for key, group in grouped_by_values:  #Equivalent, probably better

    print key, group

(1, 1, 1)     direction  subj_id  speed  other1  other2
3           1        1      1       3       3
37          1        1      1       2       3
48          1        1      1       2       1
52          1        1      1       1       3
81          1        1      1       1       1
97          1        1      1       1       1
(1, 1, 2)     direction  subj_id  speed  other1  other2
25          1        1      2       2       3
62          1        1      2       3       1

If instead you want to know how to "condense dataframe queries", here is an approach: generate a list of boolean masks (one for each condition) and then generating the intersection using reduce.

Here is an example:

import pandas as pd
import numpy as np

# Reproducible Example
df = pd.DataFrame(np.random.randint(1,4, (100, 3)), columns = ['A', 'B', 'C'])
query_fields = ['A','B','C']
query_items = [1,2,3]

# Individual masks
ind_masks = [df[key].eq(val) for key, val in zip(query_fields, query_items)]
# Combined Query
mask = reduce(lambda x, y: x & y, ind_masks)

query_result = df[mask]


问:
Why are my Keen IO counts off by one day?
Using the daily interval on Keen IO, my counts are off by one day as compared to what I see if I just look at the counts for a single day. Why are they different? I'm running this query in the Keen IO Explorer.

For example my query is

```<code>count 'subscriptions'
timeframe 'last_7_days'
interval 'daily'
</code>```

The line chart shows a count of 87 for 06/06/2017.

Then I run this count for a single day:

```<code>count 'subscriptions'
timeframe start '2017-06-06T:00:00.000Z'
timeframe end '2017-06-07T00:00:00.000Z'
</code>```

An the count shows the value for 06/05/2017.
Why are they different?

答:
This is related to the browser's timeframe/timezone presentation of the data. Change the timezone parameter of the query to match the timezone of your browser and you should see that the date labels on your line chart behave like you would expect.

The line chart uses the browser's timezone to decide how to delineate the days and draw the chart, whereas the single count simply displays the result back from the API. That's how it can appear that you're getting "different results" for the same day.

Troubleshooting tip for the future: you can inspect the raw JSON of the query result to see what is coming back from the API.

Here's what the query result looks like for a count with a 7 day interval. You can see the exact datetime and timezone used in the query.

{
  "result": [
    {
      "value": 70,
      "timeframe": {
        "start": "2017-05-31T07:00:00.000Z",
        "end": "2017-06-01T07:00:00.000Z"
      }
    },
    {
      "value": 106,
      "timeframe": {
        "start": "2017-06-01T07:00:00.000Z",
        "end": "2017-06-02T07:00:00.000Z"
      }
    },
    {
      "value": 141,
      "timeframe": {
        "start": "2017-06-02T07:00:00.000Z",
        "end": "2017-06-03T07:00:00.000Z"
      }
    },
    {
      "value": 63,
      "timeframe": {
        "start": "2017-06-03T07:00:00.000Z",
        "end": "2017-06-04T07:00:00.000Z"
      }
    },
    {
      "value": 55,
      "timeframe": {
        "start": "2017-06-04T07:00:00.000Z",
        "end": "2017-06-05T07:00:00.000Z"
      }
    },
    {
      "value": 64,
      "timeframe": {
        "start": "2017-06-05T07:00:00.000Z",
        "end": "2017-06-06T07:00:00.000Z"
      }
    },
    {
      "value": 50,
      "timeframe": {
        "start": "2017-06-06T07:00:00.000Z",
        "end": "2017-06-07T07:00:00.000Z"
      }
    }
  ]
}```
</div>
</div>
</p>

<p>You can also use the "Embed" button in the explorer to see the exact code used in compiling your query.</p>

<p>e.g. </p>

```  var query = new Keen.Query("count", {
    event_collection: "create_organization",
    interval: "daily",
    timeframe: "this_7_days",
    timezone: "US/Pacific"
  });
```

Body:
Using the daily interval on Keen IO, my counts are off by one day as compared to what I see if I just look at the counts for a single day. Why are they different? I'm running this query in the Keen IO Explorer.

For example my query is

count 'subscriptions'
timeframe 'last_7_days'
interval 'daily'

The line chart shows a count of 87 for 06/06/2017.

Then I run this count for a single day:

count 'subscriptions'
timeframe start '2017-06-06T:00:00.000Z'
timeframe end '2017-06-07T00:00:00.000Z'

An the count shows the value for 06/05/2017.
Why are they different?

Body:
This is related to the browser's timeframe/timezone presentation of the data. Change the timezone parameter of the query to match the timezone of your browser and you should see that the date labels on your line chart behave like you would expect.

The line chart uses the browser's timezone to decide how to delineate the days and draw the chart, whereas the single count simply displays the result back from the API. That's how it can appear that you're getting "different results" for the same day.

Troubleshooting tip for the future: you can inspect the raw JSON of the query result to see what is coming back from the API.

Here's what the query result looks like for a count with a 7 day interval. You can see the exact datetime and timezone used in the query.

{
  "result": [
    {
      "value": 70,
      "timeframe": {
        "start": "2017-05-31T07:00:00.000Z",
        "end": "2017-06-01T07:00:00.000Z"
      }
    },
    {
      "value": 106,
      "timeframe": {
        "start": "2017-06-01T07:00:00.000Z",
        "end": "2017-06-02T07:00:00.000Z"
      }
    },
    {
      "value": 141,
      "timeframe": {
        "start": "2017-06-02T07:00:00.000Z",
        "end": "2017-06-03T07:00:00.000Z"
      }
    },
    {
      "value": 63,
      "timeframe": {
        "start": "2017-06-03T07:00:00.000Z",
        "end": "2017-06-04T07:00:00.000Z"
      }
    },
    {
      "value": 55,
      "timeframe": {
        "start": "2017-06-04T07:00:00.000Z",
        "end": "2017-06-05T07:00:00.000Z"
      }
    },
    {
      "value": 64,
      "timeframe": {
        "start": "2017-06-05T07:00:00.000Z",
        "end": "2017-06-06T07:00:00.000Z"
      }
    },
    {
      "value": 50,
      "timeframe": {
        "start": "2017-06-06T07:00:00.000Z",
        "end": "2017-06-07T07:00:00.000Z"
      }
    }
  ]
}

You can also use the "Embed" button in the explorer to see the exact code used in compiling your query.

e.g.

  var query = new Keen.Query("count", {
    event_collection: "create_organization",
    interval: "daily",
    timeframe: "this_7_days",
    timezone: "US/Pacific"
  });


问:
How do I communicate from a slot child definition to the containing component in vue 2.x?
I am writing a simple tooltip component. The contents of the tooltip are defined with a vue slot. I want the contents of the slot to be able to signal a close of the tooltip, the same way the tooltip can close itself from its own template.

Here's example code:

Vue.component('vtip', {
  created: function() {
    this.$on('closeDialog', function(a,b,c) {
      console.log('[closeDialog in vtip]', a,b,c,this);
      this.closeDialog(); // idfk
    });
  },
  props: ['button_text'],
  template: '#vtip_template',
  methods: {
    closeDialog: function(event) {
      var $dialog = $(this.$refs.dialog);
      $dialog.fadeToggle('fast');
    },
    toggleDialog: function(event) {
      var $button = $(this.$refs.button);
      var $dialog = $(this.$refs.dialog);

      var button_left = $button.position().left;
      var button_top = $button.position().top;

      var extras = 2;
      var arrow_size = 10;
      var new_pos = {left:button_left+'px',top:button_top+$button.height()+arrow_size+extras+'px'};

      $dialog.css(new_pos);
      $dialog.fadeToggle('fast');
    },
  }
});

var v_app;
$(document).ready(function () {
  v_app = new Vue({
    el: '#v_app',
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background:#eee;
  padding:1em;
  font-family:Verdana;
  font-size:11pt;
}

.dialog {
  background:#222;
  color:#eee;
  border:2px solid white;
  display:none;

  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  border-radius:4px;

  position:absolute;
}

.dialog .item-body .item-body {
  padding:1em 1em;
}

.dialog .item-body {
  min-width:10em;
  padding:0.5em 1em;
}</code>```

    1. Click Hey.

    2. How do I make the "Yes!" button close the component like the "x" link does?

    <vtip button_text="hey">

        Are you sure?
        <button>Yes!</button>
    </vtip>

```

答:
You could add a ref attribute to the vtip component tag, and then reference the component's closeDialog method via the $refs object:

```<code><vtip button_text="hey" ref="tip">
    Are you sure?
    <button @click="$refs.tip.closeDialog()">Yes!</button>
</vtip>
</code>```

Vue.component('vtip', {
  created: function() {
    this.$on('closeDialog', function(a,b,c) {
      console.log('[closeDialog in vtip]', a,b,c,this);
      this.closeDialog(); // idfk
    });
  },
  props: ['button_text'],
  template: '#vtip_template',
  methods: {
    closeDialog: function(event) {
      var $dialog = $(this.$refs.dialog);
      $dialog.fadeToggle('fast');
    },
    toggleDialog: function(event) {
      var $button = $(this.$refs.button);
      var $dialog = $(this.$refs.dialog);

      var button_left = $button.position().left;
      var button_top = $button.position().top;

      var extras = 2;
      var arrow_size = 10;
      var new_pos = {left:button_left+'px',top:button_top+$button.height()+arrow_size+extras+'px'};

      $dialog.css(new_pos);
      $dialog.fadeToggle('fast');
    },
  }
});

var v_app;
$(document).ready(function () {
  v_app = new Vue({
    el: '#v_app',
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background:#eee;
  padding:1em;
  font-family:Verdana;
  font-size:11pt;
}

.dialog {
  background:#222;
  color:#eee;
  border:2px solid white;
  display:none;

  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  border-radius:4px;

  position:absolute;
}

.dialog .item-body .item-body {
  padding:1em 1em;
}

.dialog .item-body {
  min-width:10em;
  padding:0.5em 1em;
}</code>```

    1. Click Hey.

    2. How do I make the "Yes!" button close the component like the "x" link does?

    <vtip button_text="hey" ref="tip">

        Are you sure?
        <button @click="$refs.tip.closeDialog()">Yes!</button>
    </vtip>

```
</div>
</div>
</p>
<hr />
<p>Alternatively, you could also use a scoped slot, passing the <code>closeDialog</code> method as a click handler property in the <code>props</code>.</p>
<p>In the slot definition, bind a <code>clickHandler</code> property:</p>
```<slot :clickHandler="closeDialog">...</slot>
```
<p>Then, in your parent component, you can access the <code>clickHandler</code> via the scoped <code>props</code> like so:</p>
```<vtip button_text="hey">
  <template scope="props">
    Are you sure?
    <button @click="props.clickHandler">Yes!</button>
  </template>
</vtip>
```
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.component('vtip', {
  created: function() {
    this.$on('closeDialog', function(a,b,c) {
      console.log('[closeDialog in vtip]', a,b,c,this);
      this.closeDialog(); // idfk
    });
  },
  props: ['button_text'],
  template: '#vtip_template',
  methods: {
    closeDialog: function(event) {
      var $dialog = $(this.$refs.dialog);
      $dialog.fadeToggle('fast');
    },
    toggleDialog: function(event) {
      var $button = $(this.$refs.button);
      var $dialog = $(this.$refs.dialog);

      var button_left = $button.position().left;
      var button_top = $button.position().top;

      var extras = 2;
      var arrow_size = 10;
      var new_pos = {left:button_left+'px',top:button_top+$button.height()+arrow_size+extras+'px'};

      $dialog.css(new_pos);
      $dialog.fadeToggle('fast');
    },
  }
});

var v_app;
$(document).ready(function () {
  v_app = new Vue({
    el: '#v_app',
  });
});</code>```

body {
  background:#eee;
  padding:1em;
  font-family:Verdana;
  font-size:11pt;
}

.dialog {
  background:#222;
  color:#eee;
  border:2px solid white;
  display:none;

  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  border-radius:4px;

  position:absolute;
}

.dialog .item-body .item-body {
  padding:1em 1em;
}

.dialog .item-body {
  min-width:10em;
  padding:0.5em 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script id="vtip_template" type="x-template">
    <span style="position:relative;">
        <button @click="toggleDialog" v-text="button_text" ref="button"></button>
        <div ref="dialog" class="dialog">
            <div class='item-body'>
                x
                <!-- i hate slots -->
                <slot :clickHandler="closeDialog">...</slot>
            </div>
        </div>
    </span>
</script>

<DIV id="v_app">

    1. Click Hey.<br>
    2. How do I make the "Yes!" button close the component like the "x" link does?<br>

    <vtip button_text="hey">
      <template scope="props">
        Are you sure?
        <button @click="props.clickHandler">Yes!</button>
      </template>
    </vtip>

</DIV></code>```

Body:
I am writing a simple tooltip component. The contents of the tooltip are defined with a vue slot. I want the contents of the slot to be able to signal a close of the tooltip, the same way the tooltip can close itself from its own template.

Here's example code:

Vue.component('vtip', {
  created: function() {
    this.$on('closeDialog', function(a,b,c) {
      console.log('[closeDialog in vtip]', a,b,c,this);
      this.closeDialog(); // idfk
    });
  },
  props: ['button_text'],
  template: '#vtip_template',
  methods: {
    closeDialog: function(event) {
      var $dialog = $(this.$refs.dialog);
      $dialog.fadeToggle('fast');
    },
    toggleDialog: function(event) {
      var $button = $(this.$refs.button);
      var $dialog = $(this.$refs.dialog);

      var button_left = $button.position().left;
      var button_top = $button.position().top;

      var extras = 2;
      var arrow_size = 10;
      var new_pos = {left:button_left+'px',top:button_top+$button.height()+arrow_size+extras+'px'};

      $dialog.css(new_pos);
      $dialog.fadeToggle('fast');
    },
  }
});

var v_app;
$(document).ready(function () {
  v_app = new Vue({
    el: '#v_app',
  });
});

body {
  background:#eee;
  padding:1em;
  font-family:Verdana;
  font-size:11pt;
}

.dialog {
  background:#222;
  color:#eee;
  border:2px solid white;
  display:none;

  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  border-radius:4px;

  position:absolute;
}

.dialog .item-body .item-body {
  padding:1em 1em;
}

.dialog .item-body {
  min-width:10em;
  padding:0.5em 1em;
}

    1. Click Hey.

    2. How do I make the "Yes!" button close the component like the "x" link does?

    <vtip button_text="hey">

        Are you sure?
        <button>Yes!</button>
    </vtip>

Body:
You could add a ref attribute to the vtip component tag, and then reference the component's closeDialog method via the $refs object:

<vtip button_text="hey" ref="tip">
    Are you sure?
    <button @click="$refs.tip.closeDialog()">Yes!</button>
</vtip>

Vue.component('vtip', {
  created: function() {
    this.$on('closeDialog', function(a,b,c) {
      console.log('[closeDialog in vtip]', a,b,c,this);
      this.closeDialog(); // idfk
    });
  },
  props: ['button_text'],
  template: '#vtip_template',
  methods: {
    closeDialog: function(event) {
      var $dialog = $(this.$refs.dialog);
      $dialog.fadeToggle('fast');
    },
    toggleDialog: function(event) {
      var $button = $(this.$refs.button);
      var $dialog = $(this.$refs.dialog);

      var button_left = $button.position().left;
      var button_top = $button.position().top;

      var extras = 2;
      var arrow_size = 10;
      var new_pos = {left:button_left+'px',top:button_top+$button.height()+arrow_size+extras+'px'};

      $dialog.css(new_pos);
      $dialog.fadeToggle('fast');
    },
  }
});

var v_app;
$(document).ready(function () {
  v_app = new Vue({
    el: '#v_app',
  });
});

body {
  background:#eee;
  padding:1em;
  font-family:Verdana;
  font-size:11pt;
}

.dialog {
  background:#222;
  color:#eee;
  border:2px solid white;
  display:none;

  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  border-radius:4px;

  position:absolute;
}

.dialog .item-body .item-body {
  padding:1em 1em;
}

.dialog .item-body {
  min-width:10em;
  padding:0.5em 1em;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script id="vtip_template" type="x-template">
    <span style="position:relative;">
        <button @click="toggleDialog" v-text="button_text" ref="button"></button>
        <div ref="dialog" class="dialog">
            <div class='item-body'>
                <a @click="closeDialog" style="float:right;color:white;padding:1em;" href="#">x</a>
                <!-- i hate slots -->
                <slot>...</slot>
            </div>
        </div>
    </span>
</script>

<DIV id="v_app">

    1. Click Hey.<br>
    2. How do I make the "Yes!" button close the component like the "x" link does?<br>

    <vtip button_text="hey" ref="tip">
        <!-- how do i make it so this slot child can close the parent component -->
        Are you sure?
        <button @click="$refs.tip.closeDialog()">Yes!</button> <!-- @click="closeDialog" does not work (and should not) -->
    </vtip>

</DIV>

Alternatively, you could also use a scoped slot, passing the closeDialog method as a click handler property in the props.

In the slot definition, bind a clickHandler property:

<slot :clickHandler="closeDialog">...</slot>

Then, in your parent component, you can access the clickHandler via the scoped props like so:

<vtip button_text="hey">
  <template scope="props">
    Are you sure?
    <button @click="props.clickHandler">Yes!</button>
  </template>
</vtip>

Vue.component('vtip', {
  created: function() {
    this.$on('closeDialog', function(a,b,c) {
      console.log('[closeDialog in vtip]', a,b,c,this);
      this.closeDialog(); // idfk
    });
  },
  props: ['button_text'],
  template: '#vtip_template',
  methods: {
    closeDialog: function(event) {
      var $dialog = $(this.$refs.dialog);
      $dialog.fadeToggle('fast');
    },
    toggleDialog: function(event) {
      var $button = $(this.$refs.button);
      var $dialog = $(this.$refs.dialog);

      var button_left = $button.position().left;
      var button_top = $button.position().top;

      var extras = 2;
      var arrow_size = 10;
      var new_pos = {left:button_left+'px',top:button_top+$button.height()+arrow_size+extras+'px'};

      $dialog.css(new_pos);
      $dialog.fadeToggle('fast');
    },
  }
});

var v_app;
$(document).ready(function () {
  v_app = new Vue({
    el: '#v_app',
  });
});

body {
  background:#eee;
  padding:1em;
  font-family:Verdana;
  font-size:11pt;
}

.dialog {
  background:#222;
  color:#eee;
  border:2px solid white;
  display:none;

  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  border-radius:4px;

  position:absolute;
}

.dialog .item-body .item-body {
  padding:1em 1em;
}

.dialog .item-body {
  min-width:10em;
  padding:0.5em 1em;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script id="vtip_template" type="x-template">
    <span style="position:relative;">
        <button @click="toggleDialog" v-text="button_text" ref="button"></button>
        <div ref="dialog" class="dialog">
            <div class='item-body'>
                <a @click="closeDialog" style="float:right;color:white;padding:1em;" href="#">x</a>
                <!-- i hate slots -->
                <slot :clickHandler="closeDialog">...</slot>
            </div>
        </div>
    </span>
</script>

<DIV id="v_app">

    1. Click Hey.<br>
    2. How do I make the "Yes!" button close the component like the "x" link does?<br>

    <vtip button_text="hey">
      <template scope="props">
        Are you sure?
        <button @click="props.clickHandler">Yes!</button>
      </template>
    </vtip>

</DIV>

ContentLicense: CC BY-SA 4.0


问:
Removing specific item from localStorage
I'm adding some items to localStorage, using jQuery/JS, which is all fine but in trying to remove a specific item within the array (if it's the same item) is proving difficult.

In my console logs (for testing) it seems to clear the [Object] but it's not updating the key. Perhaps my hierarchy is wrong... any ideas?

```<code>//
function addToStorage(elem, name) {

    localData = localStorage.getItem(name + 'Storage');
    var typefaces;

    if (localData == 'null' || !localData) {
        typefaces = [];
    } else {
       typefaces = JSON.parse(localData);
    }

    typefaceID = elem.find('input').val();
    typefaceName = elem.find('input').attr('data-name');
    typefacePrice = elem.find('input').attr('data-price');
    typefaceQty = 1;

    $.each(typefaces, function(index, value) {
        if (value !== null) {
            if (value.id == typefaceID) {
                if (name == 'drf') {
                    //console.log(index);
                    //console.log(typefaces);
                    typefaces.splice(index, 1);
                    //console.log(typefaces);
                }
            }
        }
    });

    typefaces.push({
        'id': typefaceID,
        'name': typefaceName,
        'price': typefacePrice,
        'qty': typefaceQty
    });

    localStorage.setItem(name + 'Storage', JSON.stringify(typefaces));

}

//
$(document).on('click', 'summary.cart td.font', function(e) {
    e.preventDefault();
    addTo = $(this);
    addTo.each(function() {
        addToStorage(addTo, 'drf');
    });
});
</code>```

This is an example of the localData once it's been added to.

```<code>[
   {
      "id":"dr-raymond-desktop-40374",
      "name":"DR-Raymond",
      "format":"Desktop (OTF)",
      "price":"15.00",
      "qty":1
   },
   {
      "id":"dr-raymond-webfont-39949",
      "name":"DR-Raymond",
      "format":"Webfont (WOFF)",
      "price":"15.00",
      "qty":1
   }
]
</code>```

答:
You are mutating the array by splicing it. The only localstorage items that are being re written are the ones that are left in the array.

So delete the item from the storage when you splice an object from the array.

```<code>$.each(typefaces, function(index, value) {
        if (value !== null) {
            if (value.id == typefaceID) {
                if (name == 'drf') {
                    //console.log(index);
                    //console.log(typefaces);
                    var removedTypeFace = typefaces.splice(index, 1);
                    //console.log(typefaces);

                    if(removedTypeFace) {
                        localStorage.removeItem(removedTypeFace.name + 'Storage');
                    }
                }
            }
        }
    });
</code>```

Body:
I'm adding some items to localStorage, using jQuery/JS, which is all fine but in trying to remove a specific item within the array (if it's the same item) is proving difficult.

In my console logs (for testing) it seems to clear the [Object] but it's not updating the key. Perhaps my hierarchy is wrong... any ideas?

//
function addToStorage(elem, name) {

    localData = localStorage.getItem(name + 'Storage');
    var typefaces;

    if (localData == 'null' || !localData) {
        typefaces = [];
    } else {
       typefaces = JSON.parse(localData);
    }

    typefaceID = elem.find('input').val();
    typefaceName = elem.find('input').attr('data-name');
    typefacePrice = elem.find('input').attr('data-price');
    typefaceQty = 1;

    $.each(typefaces, function(index, value) {
        if (value !== null) {
            if (value.id == typefaceID) {
                if (name == 'drf') {
                    //console.log(index);
                    //console.log(typefaces);
                    typefaces.splice(index, 1);
                    //console.log(typefaces);
                }
            }
        }
    });

    typefaces.push({
        'id': typefaceID,
        'name': typefaceName,
        'price': typefacePrice,
        'qty': typefaceQty
    });

    localStorage.setItem(name + 'Storage', JSON.stringify(typefaces));

}

//
$(document).on('click', 'summary.cart td.font', function(e) {
    e.preventDefault();
    addTo = $(this);
    addTo.each(function() {
        addToStorage(addTo, 'drf');
    });
});

This is an example of the localData once it's been added to.

[
   {
      "id":"dr-raymond-desktop-40374",
      "name":"DR-Raymond",
      "format":"Desktop (OTF)",
      "price":"15.00",
      "qty":1
   },
   {
      "id":"dr-raymond-webfont-39949",
      "name":"DR-Raymond",
      "format":"Webfont (WOFF)",
      "price":"15.00",
      "qty":1
   }
]

Body:
You are mutating the array by splicing it. The only localstorage items that are being re written are the ones that are left in the array.

So delete the item from the storage when you splice an object from the array.

$.each(typefaces, function(index, value) {
        if (value !== null) {
            if (value.id == typefaceID) {
                if (name == 'drf') {
                    //console.log(index);
                    //console.log(typefaces);
                    var removedTypeFace = typefaces.splice(index, 1);
                    //console.log(typefaces);

                    if(removedTypeFace) {
                        localStorage.removeItem(removedTypeFace.name + 'Storage');
                    }
                }
            }
        }
    });


问:
How to convert lists of lines in strings to lists of lists, with each item in the lines stripped
I want to convert lists of lines in strings to lists of lists, with each item in the lines stripped.

The following works, but I suspect there is a sleeker way to do this.

```<code>def str_to_lst_of_lsts(s):
    lst = s.splitlines()[1:]
    lst2 = [i.split(';') for i in lst]
    lst3 = []
    for i in lst2:
        i2 = [j.strip() for j in i]
        lst3.append(i2)
    return lst3

s = '''
c; German for dog; Hund
c; capital of France; Paris
c; company; IBM
c; nation; Sweden
c; nickname for James; Jim
'''

print(str_to_lst_of_lsts(s))

# [['c', 'German for dog', 'Hund'], ['c', 'capital of France', 'Paris'], ['c', 'company', 'IBM'], ['c', 'nation', 'Sweden'], ['c', 'nickname for James', 'Jim']]
</code>```

答:
You can use a nested string comprehension</p>

```<code>def str_to_lst_of_lsts(s):
    return [
        [part.strip() for part in line.split(';')]
        for line in s.splitlines()[1:]
    ]
</code>```

Body:
I want to convert lists of lines in strings to lists of lists, with each item in the lines stripped.

The following works, but I suspect there is a sleeker way to do this.

def str_to_lst_of_lsts(s):
    lst = s.splitlines()[1:]
    lst2 = [i.split(';') for i in lst]
    lst3 = []
    for i in lst2:
        i2 = [j.strip() for j in i]
        lst3.append(i2)
    return lst3

s = '''
c; German for dog; Hund
c; capital of France; Paris
c; company; IBM
c; nation; Sweden
c; nickname for James; Jim
'''

print(str_to_lst_of_lsts(s))

# [['c', 'German for dog', 'Hund'], ['c', 'capital of France', 'Paris'], ['c', 'company', 'IBM'], ['c', 'nation', 'Sweden'], ['c', 'nickname for James', 'Jim']]

Body:
You can use a nested string comprehension

def str_to_lst_of_lsts(s):
    return [
        [part.strip() for part in line.split(';')]
        for line in s.splitlines()[1:]
    ]


问:
Where do I find amqp_userinfo of amqp_URI for connecting to RabbitMQ
So I'm trying connect to my local RabbitMQ server through a java application using the amqp_URI which is of the following format

```<code>amqp_URI       = "amqp://" amqp_authority [ "/" vhost ] [ "?" query ]
amqp_authority = [ amqp_userinfo "@" ] host [ ":" port ]
amqp_userinfo  = username [ ":" password ]
</code>```

the question is where do I find the amqp_userinfo in my server for the connection.
the user: guest and pwd: guest of the http://localhost:15672/ doesn't work. I have also tried creating a new user in http://localhost:15672/ and using it, it doesn't help.

Thanks in advance

答: Got it, apparently the password length was too short, was successful when I created longer password for the user</p>

Body:
So I'm trying connect to my local RabbitMQ server through a java application using the amqp_URI which is of the following format

amqp_URI       = "amqp://" amqp_authority [ "/" vhost ] [ "?" query ]
amqp_authority = [ amqp_userinfo "@" ] host [ ":" port ]
amqp_userinfo  = username [ ":" password ]

the question is where do I find the amqp_userinfo in my server for the connection.
the user: guest and pwd: guest of the http://localhost:15672/ doesn't work. I have also tried creating a new user in http://localhost:15672/ and using it, it doesn't help.

Thanks in advance


问:
Why is Django admin login giving me 403 CSRF error?
I am running Django 1.2.2 and I get the following error when I try to log in to the Django admin:

Forbidden (403) CSRF verification
  failed. Request aborted.

Reason given for failure:

No CSRF or session cookie.

** I have made NO customization to the barebones admin and when I inspect the source there is a CSRF token in the form in what I believe is the correct place.

When I look at the actual request that is being sent there is a csrf token being sent but Django still says CSRF verification failed.

Can anyone point me in the right direction? Why is this happening?

答:
I've had the same problem on Django 1.2.1 FINAL. Since I knew that Django on our production site would never be updated from 1.0 (for various reasons), I found a workaround which I implemented into my development version of settings.py, leaving the production settings.py untouched.

Create a middleware.py file in your application directory with the following code:

```<code>class disableCSRF:
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)
        return None
</code>```

Then in your development version of settings.py, insert this into MIDDLEWARE_CLASSES:

```<code>'your_app_name.middleware.disableCSRF',
</code>```

Perhaps not the safest solution, but our Django site is strictly internal, so there is a minimum risk for any type of malicious actions. This solution is simple and doesn't involve changes to templates/views, and it worked instantly (unlike other I've tried).

Hopefully someone in a similar situation to mine will find this useful.

Credit goes to John McCollum, on whose site I've found this.

Body:
I've had the same problem on Django 1.2.1 FINAL. Since I knew that Django on our production site would never be updated from 1.0 (for various reasons), I found a workaround which I implemented into my development version of settings.py, leaving the production settings.py untouched.

Create a middleware.py file in your application directory with the following code:

class disableCSRF:
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)
        return None

Then in your development version of settings.py, insert this into MIDDLEWARE_CLASSES:

'your_app_name.middleware.disableCSRF',

Perhaps not the safest solution, but our Django site is strictly internal, so there is a minimum risk for any type of malicious actions. This solution is simple and doesn't involve changes to templates/views, and it worked instantly (unlike other I've tried).

Hopefully someone in a similar situation to mine will find this useful.

Credit goes to John McCollum, on whose site I've found this.


问:
How do you search MS SQL database for a particular string?
The Situation

I come from PHP + MySQL background and I'm migrating an ASP website.

I've migrated them a few times before, but in this case I'm encountering a couple of issues that disorient me and are preventing me from importing a database.

The Obstacles

I downloaded, through Plesk (current version as of writing of this post), a backup of the MS SQL database. But upon opening it I find strings of numbers, not SQL. Thus I cannot do a find and replace of the website URL.

Ex.

5441 5045 0000 0300 8c00 0e01 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000

When I connect to MS SQL via myLittleAdmin and navigate to Tools > New Query and attempt to use a FIND or SEARCH command, as I would in MySQL, it simply doesn't work.

I search the MS SQL documention for similar commands but couldn't locate any. And all of the Questions here on Stack Overflow that come up related to my question have huge queries that have a lot of syntax / code that is irrelevant to the simplicity of my question.

The Question

Can someone help me understand what I'm missing here?

Ultimately I am just seeking the MS SQL code I write to search the entire database for an instance of a particular string of text.

答:
I hired someone to write the script for me.

Here is the find script (update line 2, "TEXT_TO_SEARCH"):

```<code>USE DATABASE_NAME
DECLARE @SearchStr nvarchar(100) = 'TEXT_TO_SEARCH'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL

BEGIN
    SET @ColumnName = ''
    SET @TableName =
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL

        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END
END

SELECT ColumnName, ColumnValue FROM @Results
</code>```

And here is the find and replace script (update line 13):

```<code>SET NOCOUNT ON

DECLARE @stringToFind VARCHAR(100)
DECLARE @stringToReplace VARCHAR(100)
DECLARE @schema sysname
DECLARE @table sysname
DECLARE @count INT
DECLARE @sqlCommand VARCHAR(8000)
DECLARE @where VARCHAR(8000)
DECLARE @columnName sysname
DECLARE @object_id INT

SET @stringToFind = 'TEXT_TO _FIND'
SET @stringToReplace = 'TEXT_TO_REPLACE'

DECLARE TAB_CURSOR CURSOR  FOR
SELECT   B.NAME      AS SCHEMANAME,
         A.NAME      AS TABLENAME,
         A.OBJECT_ID
FROM     sys.objects A
         INNER JOIN sys.schemas B
           ON A.SCHEMA_ID = B.SCHEMA_ID
WHERE    TYPE = 'U'
ORDER BY 1

OPEN TAB_CURSOR

FETCH NEXT FROM TAB_CURSOR
INTO @schema,
     @table,
     @object_id

WHILE @@FETCH_STATUS = 0
  BEGIN
    DECLARE COL_CURSOR CURSOR FOR
    SELECT A.NAME
    FROM   sys.columns A
           INNER JOIN sys.types B
             ON A.SYSTEM_TYPE_ID = B.SYSTEM_TYPE_ID
    WHERE  OBJECT_ID = @object_id
           AND IS_COMPUTED = 0
           AND B.NAME IN ('char','nchar','nvarchar','varchar','text','ntext')

    OPEN COL_CURSOR

    FETCH NEXT FROM COL_CURSOR
    INTO @columnName

    WHILE @@FETCH_STATUS = 0
      BEGIN
        SET @sqlCommand = 'UPDATE ' + @schema + '.' + @table + ' SET [' + @columnName
                           + '] = REPLACE(convert(nvarchar(max),[' + @columnName + ']),'''
                           + @stringToFind + ''',''' + @stringToReplace + ''')'

        SET @where = ' WHERE [' + @columnName + '] LIKE ''%' + @stringToFind + '%'''

        EXEC( @sqlCommand + @where)

        SET @count = @@ROWCOUNT

        IF @count > 0
          BEGIN
            PRINT @sqlCommand + @where
            PRINT 'Updated: ' + CONVERT(VARCHAR(10),@count)
            PRINT '----------------------------------------------------'
          END

        FETCH NEXT FROM COL_CURSOR
        INTO @columnName
      END

    CLOSE COL_CURSOR
    DEALLOCATE COL_CURSOR

    FETCH NEXT FROM TAB_CURSOR
    INTO @schema,
         @table,
         @object_id
  END

CLOSE TAB_CURSOR
DEALLOCATE TAB_CURSOR
</code>```

Body:
I hired someone to write the script for me.

Here is the find script (update line 2, "TEXT_TO_SEARCH"):

USE DATABASE_NAME
DECLARE @SearchStr nvarchar(100) = 'TEXT_TO_SEARCH'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL

BEGIN
    SET @ColumnName = ''
    SET @TableName =
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL

        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END
END

SELECT ColumnName, ColumnValue FROM @Results

And here is the find and replace script (update line 13):

SET NOCOUNT ON

DECLARE @stringToFind VARCHAR(100)
DECLARE @stringToReplace VARCHAR(100)
DECLARE @schema sysname
DECLARE @table sysname
DECLARE @count INT
DECLARE @sqlCommand VARCHAR(8000)
DECLARE @where VARCHAR(8000)
DECLARE @columnName sysname
DECLARE @object_id INT

SET @stringToFind = 'TEXT_TO _FIND'
SET @stringToReplace = 'TEXT_TO_REPLACE'

DECLARE TAB_CURSOR CURSOR  FOR
SELECT   B.NAME      AS SCHEMANAME,
         A.NAME      AS TABLENAME,
         A.OBJECT_ID
FROM     sys.objects A
         INNER JOIN sys.schemas B
           ON A.SCHEMA_ID = B.SCHEMA_ID
WHERE    TYPE = 'U'
ORDER BY 1

OPEN TAB_CURSOR

FETCH NEXT FROM TAB_CURSOR
INTO @schema,
     @table,
     @object_id

WHILE @@FETCH_STATUS = 0
  BEGIN
    DECLARE COL_CURSOR CURSOR FOR
    SELECT A.NAME
    FROM   sys.columns A
           INNER JOIN sys.types B
             ON A.SYSTEM_TYPE_ID = B.SYSTEM_TYPE_ID
    WHERE  OBJECT_ID = @object_id
           AND IS_COMPUTED = 0
           AND B.NAME IN ('char','nchar','nvarchar','varchar','text','ntext')

    OPEN COL_CURSOR

    FETCH NEXT FROM COL_CURSOR
    INTO @columnName

    WHILE @@FETCH_STATUS = 0
      BEGIN
        SET @sqlCommand = 'UPDATE ' + @schema + '.' + @table + ' SET [' + @columnName
                           + '] = REPLACE(convert(nvarchar(max),[' + @columnName + ']),'''
                           + @stringToFind + ''',''' + @stringToReplace + ''')'

        SET @where = ' WHERE [' + @columnName + '] LIKE ''%' + @stringToFind + '%'''

        EXEC( @sqlCommand + @where)

        SET @count = @@ROWCOUNT

        IF @count > 0
          BEGIN
            PRINT @sqlCommand + @where
            PRINT 'Updated: ' + CONVERT(VARCHAR(10),@count)
            PRINT '----------------------------------------------------'
          END

        FETCH NEXT FROM COL_CURSOR
        INTO @columnName
      END

    CLOSE COL_CURSOR
    DEALLOCATE COL_CURSOR

    FETCH NEXT FROM TAB_CURSOR
    INTO @schema,
         @table,
         @object_id
  END

CLOSE TAB_CURSOR
DEALLOCATE TAB_CURSOR


问:
Spark deduplication of RDD to get bigger RDD
I have a dataframe loaded from disk

```<code>df_ = sqlContext.read.json("/Users/spark_stats/test.json")
</code>```

It contains 500k rows.

my script works fine on this size, but I want to test it for example on 5M rows, is there a way to duplicate the df 9 times? (it does not matter for me to have duplicates in the df)

i already use union but it is really too slow (as I think it keeps reading from the disk everytime)

```<code>df = df_
for i in range(9):
    df = df.union(df_)
</code>```

Do you have an idea about a clean way to do that?

Thanks

答:
You can use explode.  It should only read from the raw disk once:</p>

```<code>from pyspark.sql.types import *
from pyspark.sql.functions import *

schema = StructType([StructField("f1", StringType()), StructField("f2", StringType())])

data = [("a", "b"), ("c", "d")]
rdd = sc.parallelize(data)
df = sqlContext.createDataFrame(rdd, schema)

# Create an array with as many values as times you want to duplicate the rows
dups_array = [lit(i) for i in xrange(9)]
duplicated = df.withColumn("duplicate", array(*dups_array)) \
               .withColumn("duplicate", explode("duplicate")) \
               .drop("duplicate")
</code>```

Body:
I have a dataframe loaded from disk

df_ = sqlContext.read.json("/Users/spark_stats/test.json")

It contains 500k rows.

my script works fine on this size, but I want to test it for example on 5M rows, is there a way to duplicate the df 9 times? (it does not matter for me to have duplicates in the df)

i already use union but it is really too slow (as I think it keeps reading from the disk everytime)

df = df_
for i in range(9):
    df = df.union(df_)

Do you have an idea about a clean way to do that?

Thanks

Body:
You can use explode.  It should only read from the raw disk once:

from pyspark.sql.types import *
from pyspark.sql.functions import *

schema = StructType([StructField("f1", StringType()), StructField("f2", StringType())])

data = [("a", "b"), ("c", "d")]
rdd = sc.parallelize(data)
df = sqlContext.createDataFrame(rdd, schema)

# Create an array with as many values as times you want to duplicate the rows
dups_array = [lit(i) for i in xrange(9)]
duplicated = df.withColumn("duplicate", array(*dups_array)) \
               .withColumn("duplicate", explode("duplicate")) \
               .drop("duplicate")