问:
Is WaitGroup in golang a step backward compare to other languages like Python?
I am very new to golang and I was trying out goroutine, while it's quite easy to run things concurrently, I am a bit surprised the way golang to "join the threads" using WaitGroup.

As far as I know, the goroutine needs to have reference to the WaitGroup object to call Done(), which means, I have to either make the goroutine to accept a WaitGroup object, or make WaitGroup object global to the goroutine.

But in other languages like Python, you call thread.join(), the "controlling" part sits outside of the thread code.

Like I said, I am very new to golang, I don't know why it was designed this way, could someone please shed some light on this aspect?

UPDATE:
I hope the argument is not based on 'Goroutine vs Thread', at the end of the day they both try to achieve (some kind of) 'concurrency', my question is more about controlling the program flow.

答:
As far as I know, the goroutine needs to have reference to the WaitGroup object to call Done(), which means, I have to either make the goroutine to accept a WaitGroup object, or make WaitGroup object global to the goroutine.

I disagree that WaitGroup is a step backward when compared to other languages. I really like its simplicity. However, I do agree that passing the WaitGroup object around would mean that the concurrency logic would be mixed with your business logic and I did not like that.

So I came up with this generic function to solve this problem for me:

```<code>// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

Here is an example:

```<code>func1 := func() {
        for char := 'a'; char < 'a' + 3; char++ {
            fmt.Printf("%c ", char)
        }
}

func2 := func() {
        for number := 1; number < 4; number++ {
            fmt.Printf("%d ", number)
        }
}

Parallelize(func1, func2)  // a 1 b 2 c 3
</code>```

If you would like to use it, you can find it here https://github.com/shomali11/util

Body:
As far as I know, the goroutine needs to have reference to the WaitGroup object to call Done(), which means, I have to either make the goroutine to accept a WaitGroup object, or make WaitGroup object global to the goroutine.

I disagree that WaitGroup is a step backward when compared to other languages. I really like its simplicity. However, I do agree that passing the WaitGroup object around would mean that the concurrency logic would be mixed with your business logic and I did not like that.

So I came up with this generic function to solve this problem for me:

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

Here is an example:

func1 := func() {
        for char := 'a'; char < 'a' + 3; char++ {
            fmt.Printf("%c ", char)
        }
}

func2 := func() {
        for number := 1; number < 4; number++ {
            fmt.Printf("%d ", number)
        }
}

Parallelize(func1, func2)  // a 1 b 2 c 3

If you would like to use it, you can find it here https://github.com/shomali11/util


来源: stackexchange

问:
JBoss5: Cannot deploy due to java.util.zip.ZipException: error in opening zip file
I have a web client and a EJB project, which I created with Eclipse 3.4.
When I want to deploy it on Jboss 5.0.1, I receive the error below. I searched a lot but I wasn't able to find a solution to this.

```<code>18:21:21,899 INFO  [ServerImpl] Starting JBoss (Microcontainer)...
18:21:21,900 INFO  [ServerImpl] Release ID: JBoss [Morpheus] 5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221)
18:21:21,900 INFO  [ServerImpl] Bootstrap URL: null
18:21:21,900 INFO  [ServerImpl] Home Dir: /Applications/jboss-5.0.1.GA
18:21:21,900 INFO  [ServerImpl] Home URL: file:/Applications/jboss-5.0.1.GA/
18:21:21,901 INFO  [ServerImpl] Library URL: file:/Applications/jboss-5.0.1.GA/lib/
18:21:21,901 INFO  [ServerImpl] Patch URL: null
18:21:21,901 INFO  [ServerImpl] Common Base URL: file:/Applications/jboss-5.0.1.GA/common/
18:21:21,902 INFO  [ServerImpl] Common Library URL: file:/Applications/jboss-5.0.1.GA/common/lib/
18:21:21,902 INFO  [ServerImpl] Server Name: default
18:21:21,902 INFO  [ServerImpl] Server Base Dir: /Applications/jboss-5.0.1.GA/server
18:21:21,902 INFO  [ServerImpl] Server Base URL: file:/Applications/jboss-5.0.1.GA/server/
18:21:21,902 INFO  [ServerImpl] Server Config URL: file:/Applications/jboss-5.0.1.GA/server/default/conf/
18:21:21,902 INFO  [ServerImpl] Server Home Dir: /Applications/jboss-5.0.1.GA/server/default
18:21:21,902 INFO  [ServerImpl] Server Home URL: file:/Applications/jboss-5.0.1.GA/server/default/
18:21:21,903 INFO  [ServerImpl] Server Data Dir: /Applications/jboss-5.0.1.GA/server/default/data
18:21:21,903 INFO  [ServerImpl] Server Library URL: file:/Applications/jboss-5.0.1.GA/server/default/lib/
18:21:21,903 INFO  [ServerImpl] Server Log Dir: /Applications/jboss-5.0.1.GA/server/default/log
18:21:21,903 INFO  [ServerImpl] Server Native Dir: /Applications/jboss-5.0.1.GA/server/default/tmp/native
18:21:21,903 INFO  [ServerImpl] Server Temp Dir: /Applications/jboss-5.0.1.GA/server/default/tmp
18:21:21,903 INFO  [ServerImpl] Server Temp Deploy Dir: /Applications/jboss-5.0.1.GA/server/default/tmp/deploy
18:21:22,669 INFO  [ServerImpl] Starting Microcontainer, bootstrapURL=file:/Applications/jboss-5.0.1.GA/server/default/conf/bootstrap.xml
18:21:23,535 INFO  [VFSCacheFactory] Initializing VFSCache [org.jboss.virtual.plugins.cache.CombinedVFSCache]
18:21:23,541 INFO  [VFSCacheFactory] Using VFSCache [CombinedVFSCache[real-cache: null]]
18:21:23,942 INFO  [CopyMechanism] VFS temp dir: /Applications/jboss-5.0.1.GA/server/default/tmp
18:21:23,943 INFO  [ZipEntryContext] VFS force nested jars copy-mode is enabled.
18:21:26,263 INFO  [ServerInfo] Java version: 1.5.0_16,Apple Inc.
18:21:26,264 INFO  [ServerInfo] Java Runtime: Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284)
18:21:26,264 INFO  [ServerInfo] Java VM: Java HotSpot(TM) Server VM 1.5.0_16-133,Apple Inc.
18:21:26,264 INFO  [ServerInfo] OS-System: Mac OS X 10.5.6,i386
18:21:26,336 INFO  [JMXKernel] Legacy JMX core initialized
18:21:30,432 INFO  [ProfileServiceImpl] Loading profile: default from: org.jboss.system.server.profileservice.repository.SerializableDeploymentRepository@e1d5d9(root=/Applications/jboss-5.0.1.GA/server, key=org.jboss.profileservice.spi.ProfileKey@143b82c3[domain=default,server=default,name=default])
18:21:30,436 INFO  [ProfileImpl] Using repository:org.jboss.system.server.profileservice.repository.SerializableDeploymentRepository@e1d5d9(root=/Applications/jboss-5.0.1.GA/server, key=org.jboss.profileservice.spi.ProfileKey@143b82c3[domain=default,server=default,name=default])
18:21:30,436 INFO  [ProfileServiceImpl] Loaded profile: ProfileImpl@ae002e{key=org.jboss.profileservice.spi.ProfileKey@143b82c3[domain=default,server=default,name=default]}
18:21:32,935 INFO  [WebService] Using RMI server codebase: http://localhost:8083/
18:21:42,572 INFO  [NativeServerConfig] JBoss Web Services - Stack Native Core
18:21:42,573 INFO  [NativeServerConfig] 3.0.5.GA
18:21:52,836 ERROR [AbstractKernelController] Error installing to ClassLoader: name=vfsfile:/Applications/jboss-5.0.1.GA/server/default/deploy/TwitterEAR.ear/ state=Describe mode=Manual requiredState=ClassLoader
org.jboss.deployers.spi.DeploymentException: Error creating classloader for vfsfile:/Applications/jboss-5.0.1.GA/server/default/deploy/TwitterEAR.ear/
    at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49)
    at org.jboss.deployers.structure.spi.helpers.AbstractDeploymentContext.createClassLoader(AbstractDeploymentContext.java:576)
    at org.jboss.deployers.structure.spi.helpers.AbstractDeploymentUnit.createClassLoader(AbstractDeploymentUnit.java:159)
    at org.jboss.deployers.spi.deployer.helpers.AbstractClassLoaderDeployer.deploy(AbstractClassLoaderDeployer.java:53)
    at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
    at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1598)
    at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1062)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
    at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:698)
    at org.jboss.system.server.profileservice.ProfileServiceBootstrap.loadProfile(ProfileServiceBootstrap.java:304)
    at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:205)
    at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:405)
    at org.jboss.Main.boot(Main.java:209)
    at org.jboss.Main$1.run(Main.java:547)
    at java.lang.Thread.run(Thread.java:613)
Caused by: java.lang.Error: Error visiting FileHandler@5567366[path=TwitterEAR.ear/TwitterPoCEJB.jar context=file:/Applications/jboss-5.0.1.GA/server/default/deploy/ real=file:/Applications/jboss-5.0.1.GA/server/default/deploy/TwitterEAR.ear/TwitterPoCEJB.jar/]
    at org.jboss.classloading.plugins.vfs.PackageVisitor.determineAllPackages(PackageVisitor.java:98)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.determineCapabilities(VFSDeploymentClassLoaderPolicyModule.java:108)
    at org.jboss.classloading.spi.dependency.Module.getCapabilities(Module.java:654)
    at org.jboss.classloading.spi.dependency.Module.determinePackageNames(Module.java:713)
    at org.jboss.classloading.spi.dependency.Module.getPackageNames(Module.java:698)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.determinePolicy(VFSDeploymentClassLoaderPolicyModule.java:129)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.determinePolicy(VFSDeploymentClassLoaderPolicyModule.java:48)
    at org.jboss.classloading.spi.dependency.policy.ClassLoaderPolicyModule.getPolicy(ClassLoaderPolicyModule.java:195)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.getPolicy(VFSDeploymentClassLoaderPolicyModule.java:122)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.getPolicy(VFSDeploymentClassLoaderPolicyModule.java:48)
    at org.jboss.classloading.spi.dependency.policy.ClassLoaderPolicyModule.registerClassLoaderPolicy(ClassLoaderPolicyModule.java:131)
    at org.jboss.deployers.plugins.classloading.AbstractLevelClassLoaderSystemDeployer.createClassLoader(AbstractLevelClassLoaderSystemDeployer.java:120)
    at org.jboss.deployers.structure.spi.helpers.AbstractDeploymentContext.createClassLoader(AbstractDeploymentContext.java:562)
    ... 21 more
Caused by: java.lang.RuntimeException: java.util.zip.ZipException: error in opening zip file
    at org.jboss.virtual.plugins.context.AbstractExceptionHandler.handleZipEntriesInitException(AbstractExceptionHandler.java:39)
    at org.jboss.virtual.plugins.context.helpers.NamesExceptionHandler.handleZipEntriesInitException(NamesExceptionHandler.java:63)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.ensureEntries(ZipEntryContext.java:610)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.checkIfModified(ZipEntryContext.java:757)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.getChildren(ZipEntryContext.java:829)
    at org.jboss.virtual.plugins.context.zip.ZipEntryHandler.getChildren(ZipEntryHandler.java:159)
    at org.jboss.virtual.plugins.context.DelegatingHandler.getChildren(DelegatingHandler.java:121)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.getChildren(AbstractVFSContext.java:211)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.visit(AbstractVFSContext.java:328)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.visit(AbstractVFSContext.java:298)
    at org.jboss.virtual.VFS.visit(VFS.java:433)
    at org.jboss.virtual.VirtualFile.visit(VirtualFile.java:437)
    at org.jboss.virtual.VirtualFile.getChildren(VirtualFile.java:386)
    at org.jboss.virtual.VirtualFile.getChildren(VirtualFile.java:367)
    at org.jboss.classloading.plugins.vfs.PackageVisitor.visit(PackageVisitor.java:200)
    at org.jboss.virtual.plugins.vfs.helpers.WrappingVirtualFileHandlerVisitor.visit(WrappingVirtualFileHandlerVisitor.java:62)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.visit(AbstractVFSContext.java:353)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.visit(AbstractVFSContext.java:298)
    at org.jboss.virtual.VFS.visit(VFS.java:433)
    at org.jboss.virtual.VirtualFile.visit(VirtualFile.java:437)
    at org.jboss.classloading.plugins.vfs.PackageVisitor.determineAllPackages(PackageVisitor.java:94)
    ... 33 more
Caused by: java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:203)
    at java.util.zip.ZipFile.<init>(ZipFile.java:234)
    at org.jboss.virtual.plugins.context.zip.ZipFileWrapper.ensureZipFile(ZipFileWrapper.java:175)
    at org.jboss.virtual.plugins.context.zip.ZipFileWrapper.acquire(ZipFileWrapper.java:245)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.initEntries(ZipEntryContext.java:470)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.ensureEntries(ZipEntryContext.java:603)
    ... 51 more
18:21:56,772 INFO  [JMXConnectorServerService] JMX Connector server: service:jmx:rmi://localhost/jndi/rmi://localhost:1090/jmxconnector
18:21:56,959 INFO  [MailService] Mail Service bound to java:/Mail
18:21:59,450 WARN  [JBossASSecurityMetadataStore] WARNING! POTENTIAL SECURITY RISK. It has been detected that the MessageSucker component which sucks messages from one node to another has not had its password changed from the installation default. Please see the JBoss Messaging user guide for instructions on how to do this.
18:21:59,489 WARN  [AnnotationCreator] No ClassLoader provided, using TCCL: org.jboss.managed.api.annotation.ManagementComponent
18:21:59,789 INFO  [TransactionManagerService] JBossTS Transaction Service (JTA version) - JBoss Inc.
18:21:59,789 INFO  [TransactionManagerService] Setting up property manager MBean and JMX layer
18:22:00,040 INFO  [TransactionManagerService] Initializing recovery manager
18:22:00,160 INFO  [TransactionManagerService] Recovery manager configured
18:22:00,160 INFO  [TransactionManagerService] Binding TransactionManager JNDI Reference
18:22:00,184 INFO  [TransactionManagerService] Starting transaction recovery manager
18:22:01,243 INFO  [Http11Protocol] Initializing Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
18:22:01,244 INFO  [AjpProtocol] Initializing Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009
18:22:01,244 INFO  [StandardService] Starting service jboss.web
18:22:01,247 INFO  [StandardEngine] Starting Servlet Engine: JBoss Web/2.1.2.GA
18:22:01,336 INFO  [Catalina] Server startup in 161 ms
18:22:01,360 INFO  [TomcatDeployment] deploy, ctxPath=/invoker
18:22:02,014 INFO  [TomcatDeployment] deploy, ctxPath=/web-console
18:22:02,459 INFO  [TomcatDeployment] deploy, ctxPath=/jbossws
18:22:02,570 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/jboss-local-jdbc.rar/META-INF/ra.xml
18:22:02,586 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/jboss-xa-jdbc.rar/META-INF/ra.xml
18:22:02,645 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/jms-ra.rar/META-INF/ra.xml
18:22:02,663 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/mail-ra.rar/META-INF/ra.xml
18:22:02,705 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/quartz-ra.rar/META-INF/ra.xml
18:22:02,801 INFO  [SimpleThreadPool] Job execution threads will use class loader of thread: main
18:22:02,850 INFO  [QuartzScheduler] Quartz Scheduler v.1.5.2 created.
18:22:02,857 INFO  [RAMJobStore] RAMJobStore initialized.
18:22:02,858 INFO  [StdSchedulerFactory] Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
18:22:02,858 INFO  [StdSchedulerFactory] Quartz scheduler version: 1.5.2
18:22:02,859 INFO  [QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
18:22:03,888 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=DefaultDS' to JNDI name 'java:DefaultDS'
18:22:04,530 INFO  [ServerPeer] JBoss Messaging 1.4.1.GA server [0] started
18:22:04,624 INFO  [QueueService] Queue[/queue/DLQ] started, fullSize=200000, pageSize=2000, downCacheSize=2000
18:22:04,632 WARN  [ConnectionFactoryJNDIMapper] supportsFailover attribute is true on connection factory: jboss.messaging.connectionfactory:service=ClusteredConnectionFactory but post office is non clustered. So connection factory will *not* support failover
18:22:04,632 WARN  [ConnectionFactoryJNDIMapper] supportsLoadBalancing attribute is true on connection factory: jboss.messaging.connectionfactory:service=ClusteredConnectionFactory but post office is non clustered. So connection factory will *not* support load balancing
18:22:04,742 INFO  [ConnectionFactory] Connector bisocket://localhost:4457 has leasing enabled, lease period 10000 milliseconds
18:22:04,742 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@6af9ad started
18:22:04,746 INFO  [QueueService] Queue[/queue/ExpiryQueue] started, fullSize=200000, pageSize=2000, downCacheSize=2000
18:22:04,747 INFO  [ConnectionFactory] Connector bisocket://localhost:4457 has leasing enabled, lease period 10000 milliseconds
18:22:04,747 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@5ac953 started
18:22:04,750 INFO  [ConnectionFactory] Connector bisocket://localhost:4457 has leasing enabled, lease period 10000 milliseconds
18:22:04,750 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@e8fa3a started
18:22:05,050 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=ConnectionFactoryBinding,name=JmsXA' to JNDI name 'java:JmsXA'
18:22:05,073 INFO  [TomcatDeployment] deploy, ctxPath=/
18:22:05,178 INFO  [TomcatDeployment] deploy, ctxPath=/jmx-console
18:22:05,290 ERROR [ProfileServiceBootstrap] Failed to load profile: Summary of incomplete deployments (SEE PREVIOUS ERRORS FOR DETAILS):

DEPLOYMENTS IN ERROR:
  Deployment "vfsfile:/Applications/jboss-5.0.1.GA/server/default/deploy/TwitterEAR.ear/" is in error due to the following reason(s): java.util.zip.ZipException: error in opening zip file

18:22:05,301 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
18:22:05,364 INFO  [AjpProtocol] Starting Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009
18:22:05,373 INFO  [ServerImpl] JBoss (Microcontainer) [5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221)] Started in 43s:467ms
</code>```

The mentioned ear and war file are both in the deploy directory.

Does anybody have hints?

答:
I had the same problem with a "big" EAR deployed via ANT using a copy task.
It seems that JBoss was trying to unzip it before it was totally copied.
I solved the pb using a move task instead of a copy (taking care that the source folder for the move was on the same disk partition)</p>

OwnerDisplayName: Andreas

ContentLicense: CC BY-SA 2.5

Body:
I have a web client and a EJB project, which I created with Eclipse 3.4.
When I want to deploy it on Jboss 5.0.1, I receive the error below. I searched a lot but I wasn't able to find a solution to this.

18:21:21,899 INFO  [ServerImpl] Starting JBoss (Microcontainer)...
18:21:21,900 INFO  [ServerImpl] Release ID: JBoss [Morpheus] 5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221)
18:21:21,900 INFO  [ServerImpl] Bootstrap URL: null
18:21:21,900 INFO  [ServerImpl] Home Dir: /Applications/jboss-5.0.1.GA
18:21:21,900 INFO  [ServerImpl] Home URL: file:/Applications/jboss-5.0.1.GA/
18:21:21,901 INFO  [ServerImpl] Library URL: file:/Applications/jboss-5.0.1.GA/lib/
18:21:21,901 INFO  [ServerImpl] Patch URL: null
18:21:21,901 INFO  [ServerImpl] Common Base URL: file:/Applications/jboss-5.0.1.GA/common/
18:21:21,902 INFO  [ServerImpl] Common Library URL: file:/Applications/jboss-5.0.1.GA/common/lib/
18:21:21,902 INFO  [ServerImpl] Server Name: default
18:21:21,902 INFO  [ServerImpl] Server Base Dir: /Applications/jboss-5.0.1.GA/server
18:21:21,902 INFO  [ServerImpl] Server Base URL: file:/Applications/jboss-5.0.1.GA/server/
18:21:21,902 INFO  [ServerImpl] Server Config URL: file:/Applications/jboss-5.0.1.GA/server/default/conf/
18:21:21,902 INFO  [ServerImpl] Server Home Dir: /Applications/jboss-5.0.1.GA/server/default
18:21:21,902 INFO  [ServerImpl] Server Home URL: file:/Applications/jboss-5.0.1.GA/server/default/
18:21:21,903 INFO  [ServerImpl] Server Data Dir: /Applications/jboss-5.0.1.GA/server/default/data
18:21:21,903 INFO  [ServerImpl] Server Library URL: file:/Applications/jboss-5.0.1.GA/server/default/lib/
18:21:21,903 INFO  [ServerImpl] Server Log Dir: /Applications/jboss-5.0.1.GA/server/default/log
18:21:21,903 INFO  [ServerImpl] Server Native Dir: /Applications/jboss-5.0.1.GA/server/default/tmp/native
18:21:21,903 INFO  [ServerImpl] Server Temp Dir: /Applications/jboss-5.0.1.GA/server/default/tmp
18:21:21,903 INFO  [ServerImpl] Server Temp Deploy Dir: /Applications/jboss-5.0.1.GA/server/default/tmp/deploy
18:21:22,669 INFO  [ServerImpl] Starting Microcontainer, bootstrapURL=file:/Applications/jboss-5.0.1.GA/server/default/conf/bootstrap.xml
18:21:23,535 INFO  [VFSCacheFactory] Initializing VFSCache [org.jboss.virtual.plugins.cache.CombinedVFSCache]
18:21:23,541 INFO  [VFSCacheFactory] Using VFSCache [CombinedVFSCache[real-cache: null]]
18:21:23,942 INFO  [CopyMechanism] VFS temp dir: /Applications/jboss-5.0.1.GA/server/default/tmp
18:21:23,943 INFO  [ZipEntryContext] VFS force nested jars copy-mode is enabled.
18:21:26,263 INFO  [ServerInfo] Java version: 1.5.0_16,Apple Inc.
18:21:26,264 INFO  [ServerInfo] Java Runtime: Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284)
18:21:26,264 INFO  [ServerInfo] Java VM: Java HotSpot(TM) Server VM 1.5.0_16-133,Apple Inc.
18:21:26,264 INFO  [ServerInfo] OS-System: Mac OS X 10.5.6,i386
18:21:26,336 INFO  [JMXKernel] Legacy JMX core initialized
18:21:30,432 INFO  [ProfileServiceImpl] Loading profile: default from: org.jboss.system.server.profileservice.repository.SerializableDeploymentRepository@e1d5d9(root=/Applications/jboss-5.0.1.GA/server, key=org.jboss.profileservice.spi.ProfileKey@143b82c3[domain=default,server=default,name=default])
18:21:30,436 INFO  [ProfileImpl] Using repository:org.jboss.system.server.profileservice.repository.SerializableDeploymentRepository@e1d5d9(root=/Applications/jboss-5.0.1.GA/server, key=org.jboss.profileservice.spi.ProfileKey@143b82c3[domain=default,server=default,name=default])
18:21:30,436 INFO  [ProfileServiceImpl] Loaded profile: ProfileImpl@ae002e{key=org.jboss.profileservice.spi.ProfileKey@143b82c3[domain=default,server=default,name=default]}
18:21:32,935 INFO  [WebService] Using RMI server codebase: http://localhost:8083/
18:21:42,572 INFO  [NativeServerConfig] JBoss Web Services - Stack Native Core
18:21:42,573 INFO  [NativeServerConfig] 3.0.5.GA
18:21:52,836 ERROR [AbstractKernelController] Error installing to ClassLoader: name=vfsfile:/Applications/jboss-5.0.1.GA/server/default/deploy/TwitterEAR.ear/ state=Describe mode=Manual requiredState=ClassLoader
org.jboss.deployers.spi.DeploymentException: Error creating classloader for vfsfile:/Applications/jboss-5.0.1.GA/server/default/deploy/TwitterEAR.ear/
    at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49)
    at org.jboss.deployers.structure.spi.helpers.AbstractDeploymentContext.createClassLoader(AbstractDeploymentContext.java:576)
    at org.jboss.deployers.structure.spi.helpers.AbstractDeploymentUnit.createClassLoader(AbstractDeploymentUnit.java:159)
    at org.jboss.deployers.spi.deployer.helpers.AbstractClassLoaderDeployer.deploy(AbstractClassLoaderDeployer.java:53)
    at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
    at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
    at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1598)
    at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1062)
    at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
    at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
    at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:698)
    at org.jboss.system.server.profileservice.ProfileServiceBootstrap.loadProfile(ProfileServiceBootstrap.java:304)
    at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:205)
    at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:405)
    at org.jboss.Main.boot(Main.java:209)
    at org.jboss.Main$1.run(Main.java:547)
    at java.lang.Thread.run(Thread.java:613)
Caused by: java.lang.Error: Error visiting FileHandler@5567366[path=TwitterEAR.ear/TwitterPoCEJB.jar context=file:/Applications/jboss-5.0.1.GA/server/default/deploy/ real=file:/Applications/jboss-5.0.1.GA/server/default/deploy/TwitterEAR.ear/TwitterPoCEJB.jar/]
    at org.jboss.classloading.plugins.vfs.PackageVisitor.determineAllPackages(PackageVisitor.java:98)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.determineCapabilities(VFSDeploymentClassLoaderPolicyModule.java:108)
    at org.jboss.classloading.spi.dependency.Module.getCapabilities(Module.java:654)
    at org.jboss.classloading.spi.dependency.Module.determinePackageNames(Module.java:713)
    at org.jboss.classloading.spi.dependency.Module.getPackageNames(Module.java:698)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.determinePolicy(VFSDeploymentClassLoaderPolicyModule.java:129)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.determinePolicy(VFSDeploymentClassLoaderPolicyModule.java:48)
    at org.jboss.classloading.spi.dependency.policy.ClassLoaderPolicyModule.getPolicy(ClassLoaderPolicyModule.java:195)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.getPolicy(VFSDeploymentClassLoaderPolicyModule.java:122)
    at org.jboss.deployers.vfs.plugins.classloader.VFSDeploymentClassLoaderPolicyModule.getPolicy(VFSDeploymentClassLoaderPolicyModule.java:48)
    at org.jboss.classloading.spi.dependency.policy.ClassLoaderPolicyModule.registerClassLoaderPolicy(ClassLoaderPolicyModule.java:131)
    at org.jboss.deployers.plugins.classloading.AbstractLevelClassLoaderSystemDeployer.createClassLoader(AbstractLevelClassLoaderSystemDeployer.java:120)
    at org.jboss.deployers.structure.spi.helpers.AbstractDeploymentContext.createClassLoader(AbstractDeploymentContext.java:562)
    ... 21 more
Caused by: java.lang.RuntimeException: java.util.zip.ZipException: error in opening zip file
    at org.jboss.virtual.plugins.context.AbstractExceptionHandler.handleZipEntriesInitException(AbstractExceptionHandler.java:39)
    at org.jboss.virtual.plugins.context.helpers.NamesExceptionHandler.handleZipEntriesInitException(NamesExceptionHandler.java:63)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.ensureEntries(ZipEntryContext.java:610)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.checkIfModified(ZipEntryContext.java:757)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.getChildren(ZipEntryContext.java:829)
    at org.jboss.virtual.plugins.context.zip.ZipEntryHandler.getChildren(ZipEntryHandler.java:159)
    at org.jboss.virtual.plugins.context.DelegatingHandler.getChildren(DelegatingHandler.java:121)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.getChildren(AbstractVFSContext.java:211)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.visit(AbstractVFSContext.java:328)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.visit(AbstractVFSContext.java:298)
    at org.jboss.virtual.VFS.visit(VFS.java:433)
    at org.jboss.virtual.VirtualFile.visit(VirtualFile.java:437)
    at org.jboss.virtual.VirtualFile.getChildren(VirtualFile.java:386)
    at org.jboss.virtual.VirtualFile.getChildren(VirtualFile.java:367)
    at org.jboss.classloading.plugins.vfs.PackageVisitor.visit(PackageVisitor.java:200)
    at org.jboss.virtual.plugins.vfs.helpers.WrappingVirtualFileHandlerVisitor.visit(WrappingVirtualFileHandlerVisitor.java:62)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.visit(AbstractVFSContext.java:353)
    at org.jboss.virtual.plugins.context.AbstractVFSContext.visit(AbstractVFSContext.java:298)
    at org.jboss.virtual.VFS.visit(VFS.java:433)
    at org.jboss.virtual.VirtualFile.visit(VirtualFile.java:437)
    at org.jboss.classloading.plugins.vfs.PackageVisitor.determineAllPackages(PackageVisitor.java:94)
    ... 33 more
Caused by: java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:203)
    at java.util.zip.ZipFile.<init>(ZipFile.java:234)
    at org.jboss.virtual.plugins.context.zip.ZipFileWrapper.ensureZipFile(ZipFileWrapper.java:175)
    at org.jboss.virtual.plugins.context.zip.ZipFileWrapper.acquire(ZipFileWrapper.java:245)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.initEntries(ZipEntryContext.java:470)
    at org.jboss.virtual.plugins.context.zip.ZipEntryContext.ensureEntries(ZipEntryContext.java:603)
    ... 51 more
18:21:56,772 INFO  [JMXConnectorServerService] JMX Connector server: service:jmx:rmi://localhost/jndi/rmi://localhost:1090/jmxconnector
18:21:56,959 INFO  [MailService] Mail Service bound to java:/Mail
18:21:59,450 WARN  [JBossASSecurityMetadataStore] WARNING! POTENTIAL SECURITY RISK. It has been detected that the MessageSucker component which sucks messages from one node to another has not had its password changed from the installation default. Please see the JBoss Messaging user guide for instructions on how to do this.
18:21:59,489 WARN  [AnnotationCreator] No ClassLoader provided, using TCCL: org.jboss.managed.api.annotation.ManagementComponent
18:21:59,789 INFO  [TransactionManagerService] JBossTS Transaction Service (JTA version) - JBoss Inc.
18:21:59,789 INFO  [TransactionManagerService] Setting up property manager MBean and JMX layer
18:22:00,040 INFO  [TransactionManagerService] Initializing recovery manager
18:22:00,160 INFO  [TransactionManagerService] Recovery manager configured
18:22:00,160 INFO  [TransactionManagerService] Binding TransactionManager JNDI Reference
18:22:00,184 INFO  [TransactionManagerService] Starting transaction recovery manager
18:22:01,243 INFO  [Http11Protocol] Initializing Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
18:22:01,244 INFO  [AjpProtocol] Initializing Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009
18:22:01,244 INFO  [StandardService] Starting service jboss.web
18:22:01,247 INFO  [StandardEngine] Starting Servlet Engine: JBoss Web/2.1.2.GA
18:22:01,336 INFO  [Catalina] Server startup in 161 ms
18:22:01,360 INFO  [TomcatDeployment] deploy, ctxPath=/invoker
18:22:02,014 INFO  [TomcatDeployment] deploy, ctxPath=/web-console
18:22:02,459 INFO  [TomcatDeployment] deploy, ctxPath=/jbossws
18:22:02,570 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/jboss-local-jdbc.rar/META-INF/ra.xml
18:22:02,586 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/jboss-xa-jdbc.rar/META-INF/ra.xml
18:22:02,645 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/jms-ra.rar/META-INF/ra.xml
18:22:02,663 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/mail-ra.rar/META-INF/ra.xml
18:22:02,705 INFO  [RARDeployment] Required license terms exist, view vfszip:/Applications/jboss-5.0.1.GA/server/default/deploy/quartz-ra.rar/META-INF/ra.xml
18:22:02,801 INFO  [SimpleThreadPool] Job execution threads will use class loader of thread: main
18:22:02,850 INFO  [QuartzScheduler] Quartz Scheduler v.1.5.2 created.
18:22:02,857 INFO  [RAMJobStore] RAMJobStore initialized.
18:22:02,858 INFO  [StdSchedulerFactory] Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
18:22:02,858 INFO  [StdSchedulerFactory] Quartz scheduler version: 1.5.2
18:22:02,859 INFO  [QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
18:22:03,888 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=DefaultDS' to JNDI name 'java:DefaultDS'
18:22:04,530 INFO  [ServerPeer] JBoss Messaging 1.4.1.GA server [0] started
18:22:04,624 INFO  [QueueService] Queue[/queue/DLQ] started, fullSize=200000, pageSize=2000, downCacheSize=2000
18:22:04,632 WARN  [ConnectionFactoryJNDIMapper] supportsFailover attribute is true on connection factory: jboss.messaging.connectionfactory:service=ClusteredConnectionFactory but post office is non clustered. So connection factory will *not* support failover
18:22:04,632 WARN  [ConnectionFactoryJNDIMapper] supportsLoadBalancing attribute is true on connection factory: jboss.messaging.connectionfactory:service=ClusteredConnectionFactory but post office is non clustered. So connection factory will *not* support load balancing
18:22:04,742 INFO  [ConnectionFactory] Connector bisocket://localhost:4457 has leasing enabled, lease period 10000 milliseconds
18:22:04,742 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@6af9ad started
18:22:04,746 INFO  [QueueService] Queue[/queue/ExpiryQueue] started, fullSize=200000, pageSize=2000, downCacheSize=2000
18:22:04,747 INFO  [ConnectionFactory] Connector bisocket://localhost:4457 has leasing enabled, lease period 10000 milliseconds
18:22:04,747 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@5ac953 started
18:22:04,750 INFO  [ConnectionFactory] Connector bisocket://localhost:4457 has leasing enabled, lease period 10000 milliseconds
18:22:04,750 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@e8fa3a started
18:22:05,050 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=ConnectionFactoryBinding,name=JmsXA' to JNDI name 'java:JmsXA'
18:22:05,073 INFO  [TomcatDeployment] deploy, ctxPath=/
18:22:05,178 INFO  [TomcatDeployment] deploy, ctxPath=/jmx-console
18:22:05,290 ERROR [ProfileServiceBootstrap] Failed to load profile: Summary of incomplete deployments (SEE PREVIOUS ERRORS FOR DETAILS):

DEPLOYMENTS IN ERROR:
  Deployment "vfsfile:/Applications/jboss-5.0.1.GA/server/default/deploy/TwitterEAR.ear/" is in error due to the following reason(s): java.util.zip.ZipException: error in opening zip file

18:22:05,301 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
18:22:05,364 INFO  [AjpProtocol] Starting Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009
18:22:05,373 INFO  [ServerImpl] JBoss (Microcontainer) [5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221)] Started in 43s:467ms

The mentioned ear and war file are both in the deploy directory.

Does anybody have hints?

LastEditorDisplayName: kgiannakakis


问:
How do I use rugged to check if there are uncommited changes in my git repository?
How do I use rugged to check whether there are uncommitted changes in my git repo?

Much like How do I programmatically determine if there are uncommited changes?

答:
Wow. This question has been dead from some time, but thought I'd throw in my 2 cents as I'm using learning/using Rugged currently.

There's a handy method Repository#diff_workdir that exists nowadays.

Suppose you want to compare the working directory to the last commit( the equivalent of what I think of just a plain old git diff). You can get that with this:

```<code>repo.diff_workdir(repo.last_commit)
</code>```

Hope this helps someone!

ContentLicense: CC BY-SA 3.0

Body:
Wow. This question has been dead from some time, but thought I'd throw in my 2 cents as I'm using learning/using Rugged currently.

There's a handy method Repository#diff_workdir that exists nowadays.

Suppose you want to compare the working directory to the last commit( the equivalent of what I think of just a plain old git diff). You can get that with this:

repo.diff_workdir(repo.last_commit)

Hope this helps someone!


答:
Simply reset_index(). Below creates a reproducible example with loc to slice column:

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

np.random.seed(44)
# RANDOM DATA WITH US CLASS I RAILROADS
df = pd.DataFrame({'Name': ['UP', 'BNSF', 'CSX', 'KCS','NSF', 'CN', 'CP']*5,
                   'Other_Sales': np.random.randn(35),
                   'Year': list(range(2007,2014))*5})

table = df.pivot_table('Other_Sales', columns='Name',
                       index='Year', aggfunc='sum')
print(table)
# Name      BNSF        CN        CP       CSX       KCS       NSF        UP
# Year
# 2007       NaN       NaN       NaN       NaN       NaN       NaN -1.785934
# 2008  1.605111       NaN       NaN       NaN       NaN       NaN       NaN
# 2009       NaN       NaN       NaN  1.800014       NaN       NaN       NaN
# 2010       NaN       NaN       NaN       NaN -2.577264       NaN       NaN
# 2011       NaN       NaN       NaN       NaN       NaN  0.899372       NaN
# 2012       NaN -3.988874       NaN       NaN       NaN       NaN       NaN
# 2013       NaN       NaN  1.725111       NaN       NaN       NaN       NaN

table = df.pivot_table('Other_Sales', columns='Name',
                       index='Year', aggfunc='sum').sum(axis=1).reset_index()

print(table)
#    Year         0
# 0  2007 -1.785934
# 1  2008  1.605111
# 2  2009  1.800014
# 3  2010 -2.577264
# 4  2011  0.899372
# 5  2012 -3.988874
# 6  2013  1.725111

print(table.loc[:,0])
# 0   -1.785934
# 1    1.605111
# 2    1.800014
# 3   -2.577264
# 4    0.899372
# 5   -3.988874
# 6    1.725111
# Name: 0, dtype: float64
</code>```

Title: How to extract column from Python Pandas Pivot_table?

Body:
I have the following pandas pivot_table:
print table

Year
1980.0     11.38
1981.0     35.68
1982.0     28.88
1983.0     16.80
1984.0     50.35
1985.0     53.95
1986.0     37.08
1987.0     21.70
1988.0     47.21
1989.0     73.45
1990.0     49.37
1991.0     32.23
1992.0     76.14
1993.0     45.99
1994.0     79.22
1995.0     88.11
1996.0    199.15
1997.0    201.07
1998.0    256.33
1999.0    251.12
2000.0    201.63
2001.0    331.49
2002.0    394.97
2003.0    357.61
2004.0    418.85
2005.0    459.41
2006.0    520.52
2007.0    610.44
2008.0    678.49
2009.0    667.39
2010.0    600.36
2011.0    515.93
2012.0    363.30
2013.0    367.98
2014.0    337.10
2015.0    264.26
dtype: float64

How do I extract the first column of this pivot_table? If I just do table[:,0], it gives me ValueError: Can only tuple-index with a MultiIndex. I am wondering what can I do in order to extract the first column of the table.

Body:
Simply reset_index(). Below creates a reproducible example with loc to slice column:

import numpy as np
import pandas as pd

np.random.seed(44)
# RANDOM DATA WITH US CLASS I RAILROADS
df = pd.DataFrame({'Name': ['UP', 'BNSF', 'CSX', 'KCS','NSF', 'CN', 'CP']*5,
                   'Other_Sales': np.random.randn(35),
                   'Year': list(range(2007,2014))*5})

table = df.pivot_table('Other_Sales', columns='Name',
                       index='Year', aggfunc='sum')
print(table)
# Name      BNSF        CN        CP       CSX       KCS       NSF        UP
# Year
# 2007       NaN       NaN       NaN       NaN       NaN       NaN -1.785934
# 2008  1.605111       NaN       NaN       NaN       NaN       NaN       NaN
# 2009       NaN       NaN       NaN  1.800014       NaN       NaN       NaN
# 2010       NaN       NaN       NaN       NaN -2.577264       NaN       NaN
# 2011       NaN       NaN       NaN       NaN       NaN  0.899372       NaN
# 2012       NaN -3.988874       NaN       NaN       NaN       NaN       NaN
# 2013       NaN       NaN  1.725111       NaN       NaN       NaN       NaN

table = df.pivot_table('Other_Sales', columns='Name',
                       index='Year', aggfunc='sum').sum(axis=1).reset_index()

print(table)
#    Year         0
# 0  2007 -1.785934
# 1  2008  1.605111
# 2  2009  1.800014
# 3  2010 -2.577264
# 4  2011  0.899372
# 5  2012 -3.988874
# 6  2013  1.725111

print(table.loc[:,0])
# 0   -1.785934
# 1    1.605111
# 2    1.800014
# 3   -2.577264
# 4    0.899372
# 5   -3.988874
# 6    1.725111
# Name: 0, dtype: float64


问:
Parsing JSON response in Angular2
```<code>Id  FirstName LastName  Action
1.  Foo       Bar       Edit
2.  Happy     Kid       Edit
</code>```

The json which I get from my backend is [{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}].

Below is my HTML file -

```<code><table datatable class="row-border hover">
  <thead>
    <tr>
      <th>ID</th>
      <th>First name</th>
      <th>Last name</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>

    <tr *ngIf="userList" >
      <td *ngFor="let user of userList">{{user.firstName}}</td>

      <td>
        <button>Edit</button>
      </td>
    </tr>
    </tbody>
</table>
</code>```

The "userList" holds my json response.

Problem :- I get the error "Error trying to diff '[{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}]'. Only arrays and iterables are allowed".

How do I parse my json into my required ui ?

答:
You JSON is invalid. try to keep

```<code>[{id:1,firstName:"Foo",lastName:"Bar"},{id:2,firstName:"Happy",lastName:"Kid"}]
</code>```

If you want to keep keys as a string you need to write pipe to convert.

Title: Parsing JSON response in Angular2

Body:
Id  FirstName LastName  Action
1.  Foo       Bar       Edit
2.  Happy     Kid       Edit

The json which I get from my backend is [{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}].

Below is my HTML file -

      ID
      First name
      Last name
      Action

      {{user.firstName}}

        <button>Edit</button>

The "userList" holds my json response.

Problem :- I get the error "Error trying to diff '[{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}]'. Only arrays and iterables are allowed".

How do I parse my json into my required ui ?

Body:
You JSON is invalid. try to keep

[{id:1,firstName:"Foo",lastName:"Bar"},{id:2,firstName:"Happy",lastName:"Kid"}]

If you want to keep keys as a string you need to write pipe to convert.


问:
Use Jersey Filter in Spring Boot Jersey
I have a Jersey rest API which we are planning to migrate to Spring boot.

I have a filter that implements ContainerRequestFilter and had @Provider annotation in the filter. I registered the filter in ResourceConfig. But still i don't see the filter executing.

However I do get a warning message:-
A provider "My Filter class" registered in SERVER runtime does not implement any provider interfaces applicable in the SERVER runtime. Due to constraint configuration problems the provider "My Filter class" will be ignored.

I wanted to use jersey as servlet so changing the jersey to behave as filter is not working for my app.

Can someone help me on this?

Here is my code

Jersey filter

```<code>@Provider
public class CustomJerseyLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {

    @Override
    public ContainerRequest filter(ContainerRequest request) { }

    @Override
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { }
}

@Component
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
         register(CustomJerseyLoggingFilter.class);
    }
}
</code>```

答:
You're implementing the wrong ContainerRequestFilter. The one you are using is from Jersey 1.x. I don't know why you even have Jersey 1.x jars in your project. The ContainerRequestFilter (for 2.x) that you should be implementing is

javax.ws.rs.container.ContainerRequestFilter
  javax.ws.rs.container.ContainerResponseFilter

Title: Use Jersey Filter in Spring Boot Jersey

Body:
I have a Jersey rest API which we are planning to migrate to Spring boot.

I have a filter that implements ContainerRequestFilter and had @Provider annotation in the filter. I registered the filter in ResourceConfig. But still i don't see the filter executing.

However I do get a warning message:-
A provider "My Filter class" registered in SERVER runtime does not implement any provider interfaces applicable in the SERVER runtime. Due to constraint configuration problems the provider "My Filter class" will be ignored.

I wanted to use jersey as servlet so changing the jersey to behave as filter is not working for my app.

Can someone help me on this?

Here is my code

Jersey filter

@Provider
public class CustomJerseyLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {

    @Override
    public ContainerRequest filter(ContainerRequest request) { }

    @Override
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { }
}

@Component
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
         register(CustomJerseyLoggingFilter.class);
    }
}


问:
jquery val returns jquery function
maybe im just to tired but can someone tell me why this is not working? i have this inputfield with the following jquery function.

```<code><input type="text" id="search" name="search" data-catid="1">

$("#search").on("keyup",function(){
var searchid=$(this).val;
var category=$(this).attr("data-catid");
var dataString=searchid;
alert(dataString)  ;})  ;});
</code>```

alert shows me a what i guess is a 200 character jquery function in return

on the other hand he can correctly show the data-catid attribute, so it seems to be specific about .val. This seems so simple but something is obv. wrong....

答: change $(this).val to $(this).val()</p>

Title: jquery val returns jquery function

Body:
maybe im just to tired but can someone tell me why this is not working? i have this inputfield with the following jquery function.

<input type="text" id="search" name="search" data-catid="1">

$("#search").on("keyup",function(){
var searchid=$(this).val;
var category=$(this).attr("data-catid");
var dataString=searchid;
alert(dataString)  ;})  ;});

alert shows me a what i guess is a 200 character jquery function in return

on the other hand he can correctly show the data-catid attribute, so it seems to be specific about .val. This seems so simple but something is obv. wrong....

Body: change $(this).val to $(this).val()


问:
How to end a program when file does not exist rather than having a large block of text?
I'm trying to end a program without having a block of unseemly text.
I've looked through a few other threads with this topic and have tried to do what was suggested but for some reason it's not working. Thank you for any help.

Error when ran:

My code to end if file does not exist:

答:
As Elliott Frisch said under your post, the solution for your problem is to move the line

```<code>Scanner fInput = new Scanner(inputFile);
</code>```

under the if-statement (line 68).

But why?

When you initialise a Scanner with a File-Object it will try to open a stream to that file. If the file doesn't exist, a FileNotFoundException will be thrown.

Body:
As Elliott Frisch said under your post, the solution for your problem is to move the line

Scanner fInput = new Scanner(inputFile);

under the if-statement (line 68).

But why?

When you initialise a Scanner with a File-Object it will try to open a stream to that file. If the file doesn't exist, a FileNotFoundException will be thrown.


问:
No logs, no output from Google Cloud ML Training Job
I am attempting to run a Training Job on Google's Cloud ML. The signs that I have of my job running are:

Messages such as these indicating the package was built and installed:

INFO  2017-06-07 15:14:01 -0700   master-replica-0        Successfully built
training-job-foo

INFO  2017-06-07 15:14:01
-0700 master-replica-0        Installing collected packages: training-job-foo

INFO  2017-06-07 15:14:01
-0700 master-replica-0        Successfully installed training-job-foo-0.1.dev0

INFO   2017-06-07 15:14:01
-0700 master-replica-0        Running command: pip install --user training-job-foo-0.1.dev0.tar.gz

INFO   2017-06-07 15:14:02
-0700 master-replica-0        Processing ./training-job-foo-0.1.dev0.tar.gz

Messages like this indicating that my job is starting:

INFO  2017-06-07 15:14:03 -0700   master-replica-0        Running command:
python -m training-job-foo.training_routine_bar --job-dir
gs://regional-bucket-similar-to-training-job/output/

A message like this indicating that my scalar summaries are being processed:

INFO  2017-06-07 15:14:21 -0700   master-replica-0        Summary name Total
Accuracy is illegal; using Total_Accuracy instead.

Finally, I also see CPU, Memory usage increase and my consumedMLUnits increase

I should add, I also see the summary Filewriters create the summary files before the jobs are created but I dont see those files increase in size. I also see an initial checkpoint file written to gs://regional-bucket-similar-to-training-job/output/

Other than that I see no further logs or outputs. I should be seeing logs since I print accuracy, loss every so often. I also write summaries and checkpoint files.

What am I missing?

Also what other debugging tools are available in such scenarios? All I am doing currently is streaming logs, watching the job status, CPU Usage, Memory Usage on the Cloud ML console and watching my Cloud Storage bucket for any changes

答:
Sorry that you are experiencing issues. Currently, the available debugging tools are Job logs, metrics and TensorBoard, but seems like all of these can't be used in your case.
If possible, can you please send us your project number and job id to cloudml-feedback@google.com,so that we can take a close look?</p>


问:
Overlay effect works with mouse but not with keyboard
Here is my problem. I'm building portfolio page, and now I want to make it easy to navigate for people that can't use the mouse.

What does the outline property do? It provides visual feedback for
  links that have "focus" when navigating a web document using the TAB
  key (or equivalent). This is especially useful for folks who can't use
  a mouse or have a visual impairment. If you remove the outline you are
  making your site inaccessible to these people.

I built it so you can navigate all the links on my page using TAB key and you can open that link using ENTER key.

But...

I have nice visual effect with overlay. You can see images of apps, and only when you hover the mouse above that picture you can see links.

So TAB is working and you can select a link using keyboard but you can't see active links, because that overlay effect works only with the mouse (while mouse is hovering above particular picture).

It is hard to explain by words, so I recorded a short video:
https://youtu.be/IQbXL7iyG6w?t=5

Any idea how to fix this? Overlay effect should be tiggered by TAB navigation as well.

GitHub code:
https://github.com/elminsterrr/portfolio

答:
You can do this with a simple jquery code. First change your css

CSS

change this:

```<code>#portfolio .inner-content:hover .overlay-content {
  top: 0px;
  z-index: 1;
  background: rgba(0,0,0,0.9);
  transition: all 0.5s ease-out;
  -webkit-transition: all 0.5s ease-out;
  -moz-transition: all 0.5s ease-out;
}
</code>```

with:

```<code>#portfolio .inner-content:hover .overlay-content {
  top: 0px;
  z-index: 1;
  background: rgba(0,0,0,0.9);
}
#portfolio .inner-content .overlay-content.focus_test{
    top: 0px;
  z-index: 1;
  background: rgba(0,0,0,0.9);
}
</code>```

jQuery:

```<code> $('.overlay-content p a').focus(function(){
    $(this).parents('.overlay-content').addClass('focus_test');
  });
  $('.overlay-content p a').blur(function(){
      $(this).parents('.overlay-content').removeClass('focus_test');
  });
</code>```

Body:
You can do this with a simple jquery code. First change your css

CSS

change this:

#portfolio .inner-content:hover .overlay-content {
  top: 0px;
  z-index: 1;
  background: rgba(0,0,0,0.9);
  transition: all 0.5s ease-out;
  -webkit-transition: all 0.5s ease-out;
  -moz-transition: all 0.5s ease-out;
}

with:

#portfolio .inner-content:hover .overlay-content {
  top: 0px;
  z-index: 1;
  background: rgba(0,0,0,0.9);
}
#portfolio .inner-content .overlay-content.focus_test{
    top: 0px;
  z-index: 1;
  background: rgba(0,0,0,0.9);
}

jQuery:

 $('.overlay-content p a').focus(function(){
    $(this).parents('.overlay-content').addClass('focus_test');
  });
  $('.overlay-content p a').blur(function(){
      $(this).parents('.overlay-content').removeClass('focus_test');
  });


问:
how to catch "free(): invalid pointer:"
how to catch/check/test for an invalid pointer?

m_gTest declared in .h file

not initialized

```<code>try
{
    delete m_gTest;
}
catch(...)
{
    std::cout << "catch" << '\n';
}
</code>```

instead of catching it

```<code>free(): invalid pointer: 0x00000000006053b8 ***
</code>```

how to catch/check/test for an invalid pointer?

```<code>temp[i] = m_gTest[i];
</code>```

does not cause error, but if m_gTest is invalid, then anything put in temp will be wrong

o, and have used

```<code>if(m_gTest != NULL)
</code>```

答:
It's generally impossible to check if a pointer is "valid", given only the pointer. Certainly, calling delete on an "invalid" pointer will not throw an exception, except perhaps via undefined behaviour.

Basically, your code needs to explicitly track whether a pointer is "valid" or not. Or better use smart pointers, such as std::unique_ptr.

Title: how to catch "free(): invalid pointer:"

Body:
how to catch/check/test for an invalid pointer?

m_gTest declared in .h file

not initialized

try
{
    delete m_gTest;
}
catch(...)
{
    std::cout << "catch" << '\n';
}

instead of catching it

free(): invalid pointer: 0x00000000006053b8 ***

how to catch/check/test for an invalid pointer?

temp[i] = m_gTest[i];

does not cause error, but if m_gTest is invalid, then anything put in temp will be wrong

o, and have used

if(m_gTest != NULL)


问:
Regular Expression WildCard matching split with java split method
I know there's similar questions like this asked before, but i want to do a custom operation and i don't know how to go about it.
I want to split a string of data with a regular expression like, but this time like i know the starting character and the ending character like:

```<code>String myString="Google is a great search engine<as:...s>";
</code>```

The <as: and s> is the beginning and closing characters
the ... is dynamic which i cant predict its value

I want to be able to split the string from the beginning <as: to the end s>
with the dynamic string in it.

Like:

```<code>myString.split("<as:/*s>");
</code>```

Something like that. I also want to get all the occurrence of the <as:..s> in the string.
i know this can be done with regex, but I've never done it before. I need a simple and neat way to do this.
Thanks in advance

答:
Rather than using a .split(), I would just extract using Pattern and Matcher. This approach finds everything between <as: and s> and extracts it to a capture group. Group 1 then has the text you would like.

```<code>public static void main(String[] args)
{
    final String myString="Google is a great search engine<as:Some stuff heres>";

    Pattern pat = Pattern.compile("^[^<]+<as:(.*)s>$");

    Matcher m = pat.matcher(myString);
    if (m.matches()) {
        System.out.println(m.group(1));
    }
}
</code>```

Output:

Some stuff here

If you need the text at the beginning, you can put it in a capture group as well.

Edit: If there are more than one <as...s> in the input, then the following will gather all of them.
Edit 2: increased the logic. Added checks for emptiness.

```<code>public static List<String> multiEntry(final String myString)
{
    String[] parts = myString.split("<as:");

    List<String> col = new ArrayList<>();
    if (! parts[0].trim().isEmpty()) {
        col.add(parts[0]);
    }

    Pattern pat = Pattern.compile("^(.*?)s>(.*)?");
    for (int i = 1; i < parts.length; ++i) {
        Matcher m = pat.matcher(parts[i]);
        if (m.matches()) {
            for (int j = 1; j <= m.groupCount(); ++j) {
                String s = m.group(j).trim();
                if (! s.isEmpty()) {
                    col.add(s);
                }
            }
        }
    }

    return col;
}
</code>```

Output:

[Google is a great search engine, Some stuff heress, Here is Facebook, More Stuff, Something else at the end]

Edit 3: This approach uses find and looping to do the parsing. It uses optional capture groups as well.

```<code>public static void looping()
{
    final String myString="Google is a great search engine"
            + "<as:Some stuff heresss>Here is Facebook<as:More Stuffs>"
            + "Something else at the end" +
            "<as:Stuffs>" +
            "<as:Yet More Stuffs>";

    Pattern pat = Pattern.compile("([^<]+)?(<as:(.*?)s>)?");

    Matcher m = pat.matcher(myString);
    List<String> col = new ArrayList<>();

    while (m.find()) {
        String prefix = m.group(1);
        String contents = m.group(3);

        if (prefix != null) { col.add(prefix); }
        if (contents != null) { col.add(contents); }
    }

    System.out.println(col);
}
</code>```

Output:

[Google is a great search engine, Some stuff heress, Here is Facebook, More Stuff, Something else at the end, Stuff, Yet More Stuff]

Additional Edit: wrote some quick test cases (with super hacked helper class) to help validate. These all pass (updated) multiEntry:

```<code>public static void main(String[] args)
{
    Input[] inputs = {
            new Input("Google is a great search engine<as:Some stuff heres>", 2),
            new Input("Google is a great search engine"
                    + "<as:Some stuff heresss>Here is Facebook<as:More Stuffs>"
                    + "Something else at the end" +
                    "<as:Stuffs>" +
                    "<as:Yet More Stuffs>" +
                    "ending", 8),
            new Input("Google is a great search engine"
                            + "<as:Some stuff heresss>Here is Facebook<as:More Stuffs>"
                            + "Something else at the end" +
                            "<as:Stuffs>" +
                            "<as:Yet More Stuffs>", 7),
            new Input("No as here", 1),
            new Input("Here is angle < input", 1),
            new Input("Angle < plus <as:Stuff in as:s><as:Other stuff in as:s>", 3),
            new Input("Angle < plus <as:Stuff in as:s><as:Other stuff in as:s>blah", 4),
            new Input("<as:To start with anglass>Some ending", 2),
    };

    List<String> res;
    for (Input inp : inputs) {
        res = multiEntry(inp.inp);
        if (res.size() != inp.cnt) {
            System.err.println("FAIL: " + res.size()
            + " did not match exp of " + inp.cnt
            + " on " + inp.inp);
            System.err.println(res);
            continue;
        }
        System.out.println(res);
    }
}
</code>```

Body:
I know there's similar questions like this asked before, but i want to do a custom operation and i don't know how to go about it.
I want to split a string of data with a regular expression like, but this time like i know the starting character and the ending character like:

String myString="Google is a great search engine<as:...s>";

The <as: and s> is the beginning and closing characters
the ... is dynamic which i cant predict its value

I want to be able to split the string from the beginning <as: to the end s>
with the dynamic string in it.

Like:

myString.split("<as:/*s>");

Something like that. I also want to get all the occurrence of the <as:..s> in the string.
i know this can be done with regex, but I've never done it before. I need a simple and neat way to do this.
Thanks in advance

Body:
Rather than using a .split(), I would just extract using Pattern and Matcher. This approach finds everything between <as: and s> and extracts it to a capture group. Group 1 then has the text you would like.

public static void main(String[] args)
{
    final String myString="Google is a great search engine<as:Some stuff heres>";

    Pattern pat = Pattern.compile("^[^<]+<as:(.*)s>$");

    Matcher m = pat.matcher(myString);
    if (m.matches()) {
        System.out.println(m.group(1));
    }
}

Output:

Some stuff here

If you need the text at the beginning, you can put it in a capture group as well.

Edit: If there are more than one <as...s> in the input, then the following will gather all of them.
Edit 2: increased the logic. Added checks for emptiness.

public static List<String> multiEntry(final String myString)
{
    String[] parts = myString.split("<as:");

    List<String> col = new ArrayList<>();
    if (! parts[0].trim().isEmpty()) {
        col.add(parts[0]);
    }

    Pattern pat = Pattern.compile("^(.*?)s>(.*)?");
    for (int i = 1; i < parts.length; ++i) {
        Matcher m = pat.matcher(parts[i]);
        if (m.matches()) {
            for (int j = 1; j <= m.groupCount(); ++j) {
                String s = m.group(j).trim();
                if (! s.isEmpty()) {
                    col.add(s);
                }
            }
        }
    }

    return col;
}

Output:

[Google is a great search engine, Some stuff heress, Here is Facebook, More Stuff, Something else at the end]

Edit 3: This approach uses find and looping to do the parsing. It uses optional capture groups as well.

public static void looping()
{
    final String myString="Google is a great search engine"
            + "<as:Some stuff heresss>Here is Facebook<as:More Stuffs>"
            + "Something else at the end" +
            "<as:Stuffs>" +
            "<as:Yet More Stuffs>";

    Pattern pat = Pattern.compile("([^<]+)?(<as:(.*?)s>)?");

    Matcher m = pat.matcher(myString);
    List<String> col = new ArrayList<>();

    while (m.find()) {
        String prefix = m.group(1);
        String contents = m.group(3);

        if (prefix != null) { col.add(prefix); }
        if (contents != null) { col.add(contents); }
    }

    System.out.println(col);
}

Output:

[Google is a great search engine, Some stuff heress, Here is Facebook, More Stuff, Something else at the end, Stuff, Yet More Stuff]

Additional Edit: wrote some quick test cases (with super hacked helper class) to help validate. These all pass (updated) multiEntry:

public static void main(String[] args)
{
    Input[] inputs = {
            new Input("Google is a great search engine<as:Some stuff heres>", 2),
            new Input("Google is a great search engine"
                    + "<as:Some stuff heresss>Here is Facebook<as:More Stuffs>"
                    + "Something else at the end" +
                    "<as:Stuffs>" +
                    "<as:Yet More Stuffs>" +
                    "ending", 8),
            new Input("Google is a great search engine"
                            + "<as:Some stuff heresss>Here is Facebook<as:More Stuffs>"
                            + "Something else at the end" +
                            "<as:Stuffs>" +
                            "<as:Yet More Stuffs>", 7),
            new Input("No as here", 1),
            new Input("Here is angle < input", 1),
            new Input("Angle < plus <as:Stuff in as:s><as:Other stuff in as:s>", 3),
            new Input("Angle < plus <as:Stuff in as:s><as:Other stuff in as:s>blah", 4),
            new Input("<as:To start with anglass>Some ending", 2),
    };

    List<String> res;
    for (Input inp : inputs) {
        res = multiEntry(inp.inp);
        if (res.size() != inp.cnt) {
            System.err.println("FAIL: " + res.size()
            + " did not match exp of " + inp.cnt
            + " on " + inp.inp);
            System.err.println(res);
            continue;
        }
        System.out.println(res);
    }
}


问:
Displaying topics associated with a document/query in Gensim
Gensim has a tutorial saying how to, given a document/query string, say what other documents are most similar to it, in descending order:

http://radimrehurek.com/gensim/tut3.html

It can also display what topics are associated with an entire model at all:

How to print the LDA topics models from gensim? Python

But how do you find what topics are associated with a given document/query string? Ideally with some numeric similarity metric for each topic? I haven't been able to find anything on that.

答:
If you want to find the topic distribution of unseen documents then you need to convert the document of interest into a bag of words representation

```<code>from gensim import utils, models
from gensim.corpora import Dictionary
lda = models.LdaModel.load('saved_lda.model') # load saved model
dictionary = Dictionary.load('saved_dictionary.dict') # load saved dict
text = ' '
with open('document', 'r') as inp: # convert file to string
    for line in inp:
        text += line + ' '
tkn_doc = utils.simple_preprocess(text) # filter & tokenize words
doc_bow = dictionary.doc2bow(tkn_doc) # use dictionary to create bow
doc_vec = lda[doc_bow] # this is the topic probability distribution for the document of interest
</code>```

From this code you get a sparse vector where the indices represent the topics 0....n and each 'weight' is the probability that the words in the document belong to that topic in the model.
You can visualize the distribution by creating a bar graph using matplotlib.

```<code>y_axis = []
x_axis = []
for topic_id, dist in enumerate(doc_vec):
    x_axis.append(topic_id + 1)
    y_axis.append(dist)
width = 1
plt.bar(x_axis, y_axis, width, align='center', color='r')
plt.xlabel('Topics')
plt.ylabel('Probability')
plt.title('Topic Distribution for doc')
plt.xticks(np.arange(2, len(x_axis), 2), rotation='vertical', fontsize=7)
plt.subplots_adjust(bottom=0.2)
plt.ylim([0, np.max(y_axis) + .01])
plt.xlim([0, len(x_axis) + 1])
plt.savefig(output_path)
plt.close()
</code>```

If you want to see the topn terms in each topic you can print them like this. Referencing the graph, you can look up the topn words you printed and determine how the document was interpreted by the model.
You can also find distances between two different document probability distribution vectors by using vector calculations like hellinger distance, euclidean, jensen shannon etc.

Body:
If you want to find the topic distribution of unseen documents then you need to convert the document of interest into a bag of words representation

from gensim import utils, models
from gensim.corpora import Dictionary
lda = models.LdaModel.load('saved_lda.model') # load saved model
dictionary = Dictionary.load('saved_dictionary.dict') # load saved dict
text = ' '
with open('document', 'r') as inp: # convert file to string
    for line in inp:
        text += line + ' '
tkn_doc = utils.simple_preprocess(text) # filter & tokenize words
doc_bow = dictionary.doc2bow(tkn_doc) # use dictionary to create bow
doc_vec = lda[doc_bow] # this is the topic probability distribution for the document of interest

From this code you get a sparse vector where the indices represent the topics 0....n and each 'weight' is the probability that the words in the document belong to that topic in the model.
You can visualize the distribution by creating a bar graph using matplotlib.

y_axis = []
x_axis = []
for topic_id, dist in enumerate(doc_vec):
    x_axis.append(topic_id + 1)
    y_axis.append(dist)
width = 1
plt.bar(x_axis, y_axis, width, align='center', color='r')
plt.xlabel('Topics')
plt.ylabel('Probability')
plt.title('Topic Distribution for doc')
plt.xticks(np.arange(2, len(x_axis), 2), rotation='vertical', fontsize=7)
plt.subplots_adjust(bottom=0.2)
plt.ylim([0, np.max(y_axis) + .01])
plt.xlim([0, len(x_axis) + 1])
plt.savefig(output_path)
plt.close()

If you want to see the topn terms in each topic you can print them like this. Referencing the graph, you can look up the topn words you printed and determine how the document was interpreted by the model.
You can also find distances between two different document probability distribution vectors by using vector calculations like hellinger distance, euclidean, jensen shannon etc.


问:
Problem with setReult and onActivityResult
In my android app I'm opening a new activity for result when a button is pressed:

```<code>button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(parent.this.getApplication(), child.class);
startActivityForResult(intent, REQUEST_CODE);
</code>```

My child activity returns a result like this:

```<code>Intent newIntent = new Intent();
newIntent.putExtra("name", "name");
newIntent.putExtra("description", "desc");
setResult(RESULT_OK, newIntent);
finish();
</code>```

My onActivityResult is like this:

```<code>if (requestCode == GOTO_ADDPARKING) {
        if (resultCode == RESULT_OK) {
         String Name = data.getStringExtra("name");
         String Description = data.getStringExtra("description");
</code>```

In the debug mode I can see that in the child activity the newIntent's hash map points to an object, but in the parent activity the hash map points to null.

Any suggestions?

答:
I'm not sure about this, but try to use createPendingResult(int, Intent, int) instead of create creating a new intent

```<code>Intent newIntent = new createPendingResult(...);
</code>```

(from http://developer.android.com/reference/android/app/Activity.html#StartingActivities)

Body:
In my android app I'm opening a new activity for result when a button is pressed:

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(parent.this.getApplication(), child.class);
startActivityForResult(intent, REQUEST_CODE);

My child activity returns a result like this:

Intent newIntent = new Intent();
newIntent.putExtra("name", "name");
newIntent.putExtra("description", "desc");
setResult(RESULT_OK, newIntent);
finish();

My onActivityResult is like this:

if (requestCode == GOTO_ADDPARKING) {
        if (resultCode == RESULT_OK) {
         String Name = data.getStringExtra("name");
         String Description = data.getStringExtra("description");

In the debug mode I can see that in the child activity the newIntent's hash map points to an object, but in the parent activity the hash map points to null.

Any suggestions?

Body:
I'm not sure about this, but try to use createPendingResult(int, Intent, int) instead of create creating a new intent

Intent newIntent = new createPendingResult(...);

(from http://developer.android.com/reference/android/app/Activity.html#StartingActivities)


问:
Why an instance of Typescript execute first the get and after the code in the get?
This is my call

```<code>let sqlLocalSelect = new SqlLocalSelect();
var variable = sqlLocalSelect;
console.log("variable " + JSON.stringify(variable));
</code>```

this is the class i call

```<code>import { SQLite } from 'ionic-native';

export class SqlLocalSelect {

database: SQLite;
private li_sitios: Array<Object> = [];

constructor() {}

get get_li_sitios(): Array<Object> {
this.database = new SQLite();
this.database.openDatabase({name: "data.db", location: "default"}).then(() => {
  this.database.executeSql('SELECT * FROM Markers;', [])
  .then((data) => {
    if(data.rows.length > 0){
      this.li_sitios = [];
      for(var i = 0; i < data.rows.length; i++) {
        var value:string = "no";
        if (data.rows.item(i).synchronised) {
          value = "si";
        } else {
          value = "no";
        }
        this.li_sitios.unshift({
          id: data.rows.item(i).id,
          id_externa: data.rows.item(i).id_externa,
          id_owner: data.rows.item(i).id_owner,
          name: data.rows.item(i).name,
          lat: data.rows.item(i).lat,
          lng: data.rows.item(i).lng,
          draggable: false,
          synchronised: value,
          fecha: data.rows.item(i).fecha,
          hora: data.rows.item(i).hora
        });
      }
    } else {
      console.log("No se encontraron datos");
    }
    console.log("Consulta realizada correctamente");
    console.log("li_sitios "+ JSON.stringify(this.li_sitios));

  }, (error) => {
    console.log("Error ejecutando la consulta: " + JSON.stringify(error));
  });
  }, (error) => {
    console.log("Error al conectar con la base de datos local: " + JSON.stringify(error));
  });
  return this.li_sitios;
  }
}
</code>```

Basically it is a query to an sqlite database, but the data output does not run in console in the correct order

This is my output

06-07 18:23:51.030 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60258)] "variable []", source: file:///android_asset/www/build/main.js (60258)
06-07 18:23:51.120 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(179)] "OPEN database: data.db - OK", source: file:///android_asset/www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js (179)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err: java.sql.SQLException: sqlite3_step failure: cannot rollback - no transaction is active
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.liteglue.SQLiteGlueConnection$SQLGStatement.step(SQLiteGlueConnection.java:135)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSQLiteStatement(SQLiteConnectorDatabase.java:214)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSqlBatch(SQLiteConnectorDatabase.java:114)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLitePlugin$DBRunner.run(SQLitePlugin.java:340)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.lang.Thread.run(Thread.java:831)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err: java.sql.SQLException: sqlite3_step failure: cannot rollback - no transaction is active
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.liteglue.SQLiteGlueConnection$SQLGStatement.step(SQLiteGlueConnection.java:135)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSQLiteStatement(SQLiteConnectorDatabase.java:214)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSqlBatch(SQLiteConnectorDatabase.java:114)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLitePlugin$DBRunner.run(SQLitePlugin.java:340)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.lang.Thread.run(Thread.java:831)
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60834)] "Consulta realizada correctamente", source: file:///android_asset/www/build/main.js (60834)
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60835)] "li_sitios [{"id":4,"id_externa":0,"id_owner":1,"name":"Nombre 4","lat":22.834722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"si","fecha":"2017-6-5","hora":"15:36"},{"id":3,"id_externa":0,"id_owner":1,"name":"Nombre 2","lat":22.534722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"si","fecha":"2017-6-5","hora":"15:29"},{"id":2,"id_externa":15,"id_owner":1,"name":"Nombre 2","lat":22.534722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"no","fecha":"2017-6-5","hora":"15:24"},{"id":1,"id_externa":16,"id_owner":1,"name":"Nombre 1","lat":22.034722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"no","fecha":"2017-6-5","hora":"15:22"}]", source: file:///android_asset/www/build/main.js (60835)

As I mention it first it appears the result of the get empty and then the results of the query is throwing to console.

答:
As I mention it first it appears the result of the get empty and then the results of the query is throwing to console.

This is the nature of async programming. Very similar to a simplified example:

```<code>const arr = [];
setTimeout(()=>{
   arr.push(1);
   console.log(arr); // [1]
}, 1000);
console.log(arr); // []
</code>```

Code order by line number is not necessarily the execution order. This sounds simple (and it really is) but we've seen lots of beginners missing it so worth mentioning.

Body:
This is my call

let sqlLocalSelect = new SqlLocalSelect();
var variable = sqlLocalSelect;
console.log("variable " + JSON.stringify(variable));

this is the class i call

import { SQLite } from 'ionic-native';

export class SqlLocalSelect {

database: SQLite;
private li_sitios: Array<Object> = [];

constructor() {}

get get_li_sitios(): Array<Object> {
this.database = new SQLite();
this.database.openDatabase({name: "data.db", location: "default"}).then(() => {
  this.database.executeSql('SELECT * FROM Markers;', [])
  .then((data) => {
    if(data.rows.length > 0){
      this.li_sitios = [];
      for(var i = 0; i < data.rows.length; i++) {
        var value:string = "no";
        if (data.rows.item(i).synchronised) {
          value = "si";
        } else {
          value = "no";
        }
        this.li_sitios.unshift({
          id: data.rows.item(i).id,
          id_externa: data.rows.item(i).id_externa,
          id_owner: data.rows.item(i).id_owner,
          name: data.rows.item(i).name,
          lat: data.rows.item(i).lat,
          lng: data.rows.item(i).lng,
          draggable: false,
          synchronised: value,
          fecha: data.rows.item(i).fecha,
          hora: data.rows.item(i).hora
        });
      }
    } else {
      console.log("No se encontraron datos");
    }
    console.log("Consulta realizada correctamente");
    console.log("li_sitios "+ JSON.stringify(this.li_sitios));

  }, (error) => {
    console.log("Error ejecutando la consulta: " + JSON.stringify(error));
  });
  }, (error) => {
    console.log("Error al conectar con la base de datos local: " + JSON.stringify(error));
  });
  return this.li_sitios;
  }
}

Basically it is a query to an sqlite database, but the data output does not run in console in the correct order

This is my output

06-07 18:23:51.030 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60258)] "variable []", source: file:///android_asset/www/build/main.js (60258)
06-07 18:23:51.120 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(179)] "OPEN database: data.db - OK", source: file:///android_asset/www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js (179)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err: java.sql.SQLException: sqlite3_step failure: cannot rollback - no transaction is active
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.liteglue.SQLiteGlueConnection$SQLGStatement.step(SQLiteGlueConnection.java:135)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSQLiteStatement(SQLiteConnectorDatabase.java:214)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSqlBatch(SQLiteConnectorDatabase.java:114)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLitePlugin$DBRunner.run(SQLitePlugin.java:340)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.lang.Thread.run(Thread.java:831)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err: java.sql.SQLException: sqlite3_step failure: cannot rollback - no transaction is active
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.liteglue.SQLiteGlueConnection$SQLGStatement.step(SQLiteGlueConnection.java:135)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSQLiteStatement(SQLiteConnectorDatabase.java:214)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSqlBatch(SQLiteConnectorDatabase.java:114)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLitePlugin$DBRunner.run(SQLitePlugin.java:340)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.lang.Thread.run(Thread.java:831)
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60834)] "Consulta realizada correctamente", source: file:///android_asset/www/build/main.js (60834)
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60835)] "li_sitios [{"id":4,"id_externa":0,"id_owner":1,"name":"Nombre 4","lat":22.834722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"si","fecha":"2017-6-5","hora":"15:36"},{"id":3,"id_externa":0,"id_owner":1,"name":"Nombre 2","lat":22.534722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"si","fecha":"2017-6-5","hora":"15:29"},{"id":2,"id_externa":15,"id_owner":1,"name":"Nombre 2","lat":22.534722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"no","fecha":"2017-6-5","hora":"15:24"},{"id":1,"id_externa":16,"id_owner":1,"name":"Nombre 1","lat":22.034722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"no","fecha":"2017-6-5","hora":"15:22"}]", source: file:///android_asset/www/build/main.js (60835)

As I mention it first it appears the result of the get empty and then the results of the query is throwing to console.

Body:
As I mention it first it appears the result of the get empty and then the results of the query is throwing to console.

This is the nature of async programming. Very similar to a simplified example:

const arr = [];
setTimeout(()=>{
   arr.push(1);
   console.log(arr); // [1]
}, 1000);
console.log(arr); // []

Code order by line number is not necessarily the execution order. This sounds simple (and it really is) but we've seen lots of beginners missing it so worth mentioning.


问:
How to map Json to Java object using jackson
I am using jackson to map json which I get from my post rest api to map to a java object.

the json is represent by

```<code>{
  "baseName": "xyz",
  "salary": [
    {
      "id": 1,
      "info": {
        "ename": "john",
        "eid": 143
      }
    },
    {
      "id": 2,
      "info": {
        "ename": "bg",
        "eid": 123
      }
    }
  ]
}
</code>```

The java class are represent by

BaseInfo.java

```<code>class BaseInfo {
     String baseName;
     ArrayList<salary> salaries = new ArrayList<salary>();
}
</code>```

Salary.java

```<code>class Salary {
    int id;
    EmplInfo emp;
}
</code>```

EmplInfo.java

```<code>class EmplInfo{
    String ename;
    int eid;
}
</code>```

But in the when call the api with this json I get the arraylist initialized but contains nothings. What I am doing wrong ? I get other information like baseName,etc

答:
You can use the JsonProperty annotation to rename properties

```<code>class BaseInfo {
    String baseName;
    @JsonProperty("salary")
    ArrayList<salary> salaries = new ArrayList<salary>();
}

class Salary {
    int id;
    @JsonProperty("info")
    EmplInfo emp;
}
</code>```

Body:
I am using jackson to map json which I get from my post rest api to map to a java object.

the json is represent by

{
  "baseName": "xyz",
  "salary": [
    {
      "id": 1,
      "info": {
        "ename": "john",
        "eid": 143
      }
    },
    {
      "id": 2,
      "info": {
        "ename": "bg",
        "eid": 123
      }
    }
  ]
}

The java class are represent by

BaseInfo.java

class BaseInfo {
     String baseName;
     ArrayList<salary> salaries = new ArrayList<salary>();
}

Salary.java

class Salary {
    int id;
    EmplInfo emp;
}

EmplInfo.java

class EmplInfo{
    String ename;
    int eid;
}

But in the when call the api with this json I get the arraylist initialized but contains nothings. What I am doing wrong ? I get other information like baseName,etc

Body:
You can use the JsonProperty annotation to rename properties

class BaseInfo {
    String baseName;
    @JsonProperty("salary")
    ArrayList<salary> salaries = new ArrayList<salary>();
}

class Salary {
    int id;
    @JsonProperty("info")
    EmplInfo emp;
}


问:
file_exists() not working in php5 inside while loop
file_exists isn't working. I've looked at a few examples and still no go. Program does not detect the file. The path of my file is /var/www/osbs/PHPAPI/recording.mp3 and the website root is inside osbs. The location of this file is inside PHPAPI that is why I do not put full path in file_put_contents. The program is able to make the original recording.mp3 but not any appended versions of it.</p>

```<code><?php
$actual_name = pathinfo("PHPAPI/recording.mp3",PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo("PHPAPI/recording.mp3",PATHINFO_EXTENSION);

if ($_GET["RecordingUrl"]) {
     if (file_exists("/var/www/osbs/PHPAPI/".$actual_name.".".$extension)) {
        $actual_name = find_new_name($original_name, $extension);
     }
     else {
        $actual_name = $original_name;
     }
     $name = $actual_name.".".$extension;
     file_put_contents($name, file_get_contents($_GET["RecordingUrl"]));
}

function find_new_name ( $file, $extension ) {
    $name = $file.".".$extension;
    $i = 0;
    while(file_exists("/var/www/osbs/PHPAPI/".$name)){
        $new_name = $file.$i;
        $name = $new_name.".".$extension;
        $i++;
    }
    return $new_name;
}
 ?>
</code>```

答: Are you sure about the path? /PHPAPI looks for the file inside /PHPAPI, not the expected /var/www/osbs/PHPAPI/. You should check for PHPAPI/$filename instead.

Body:
file_exists isn't working. I've looked at a few examples and still no go. Program does not detect the file. The path of my file is /var/www/osbs/PHPAPI/recording.mp3 and the website root is inside osbs. The location of this file is inside PHPAPI that is why I do not put full path in file_put_contents. The program is able to make the original recording.mp3 but not any appended versions of it.

<?php
$actual_name = pathinfo("PHPAPI/recording.mp3",PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo("PHPAPI/recording.mp3",PATHINFO_EXTENSION);

if ($_GET["RecordingUrl"]) {
     if (file_exists("/var/www/osbs/PHPAPI/".$actual_name.".".$extension)) {
        $actual_name = find_new_name($original_name, $extension);
     }
     else {
        $actual_name = $original_name;
     }
     $name = $actual_name.".".$extension;
     file_put_contents($name, file_get_contents($_GET["RecordingUrl"]));
}

function find_new_name ( $file, $extension ) {
    $name = $file.".".$extension;
    $i = 0;
    while(file_exists("/var/www/osbs/PHPAPI/".$name)){
        $new_name = $file.$i;
        $name = $new_name.".".$extension;
        $i++;
    }
    return $new_name;
}
 ?>


问:
Docker missing log4net ConsoleAppender logs
I've got a simple C# program with the following log4net configuration:

```<code><log4net>
    <appender name="stdout" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%%-5level - %message%newline" />
    </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="stdout" />
    </root>
</log4net>
</code>```

And the following code (abbreviated for clarity):

```<code>public static void Main(String[] args)
{
    var log = LogManager.GetLogger("Logger");
    log.Info("Hello From Logger");
    Console.WriteLine("Hello From Console");
}
</code>```

I'm compiling and running this using .NET 4.5 mono on an Ubuntu 16.04 system. When I run the program using the console the output is as expected:

```<code>$ mono Program.exe
INFO - Hello From Logger
Hello From Console
</code>```

However, when I run this same program in a Docker container in detached mode (i.e, "docker run -d") and then check the logs, I only get the log from the Console.WriteLine:

```<code>$ docker logs <container_id>
Hello From Console
</code>```

While trying to track this down, I tried running the program using the daemonize tool (more info here) and it illustrated the same behavior, leading me to believe it was an issue with log4net instead of docker.
I also wrote a custom appender for log4net that only does Console.Write (I believe that's the same functionality as ConsoleAppender, but I wanted to eliminate any other possible variables):

```<code>public class CustomAppender: AppenderSkeleton
{
    protected override void Append(LoggingEvent loggingEvent)
    {
        Console.Write(RenderLoggingEvent(loggingEvent));
    }
}
</code>```

But no luck.
Can anyone with a deep knowledge of log4net point me to where I could be doing something wrong, or explain what log4net could be doing to stdout such that other programs that should be capturing that stream don't?

UPDATE: The plot thickens! I wrote a quick and dirty executable that uses the Process class to execute my example program. It then grabs the stdout from the example program and writes it with Console.WriteLine, like so:

```<code>Process proc = new Process();
proc.StartInfo.FileName = "/path/to/example.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInto.RedirectStandardOutput = true;
proc.Start();
Thread.Sleep(1000);
Console.WriteLine(proc.StandardOutput.ReadToEnd());
</code>```

This works fine when I run it directly from the console, but has the same problem when I run it from docker / daemonize. So now I'm really confused.

答: It's not much of an answer, but in case someone else runs into this problem, I was able to get logging to work by using the NLog library here.</p>

Body:
I've got a simple C# program with the following log4net configuration:

<log4net>
    <appender name="stdout" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%%-5level - %message%newline" />
    </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="stdout" />
    </root>
</log4net>

And the following code (abbreviated for clarity):

public static void Main(String[] args)
{
    var log = LogManager.GetLogger("Logger");
    log.Info("Hello From Logger");
    Console.WriteLine("Hello From Console");
}

I'm compiling and running this using .NET 4.5 mono on an Ubuntu 16.04 system. When I run the program using the console the output is as expected:

$ mono Program.exe
INFO - Hello From Logger
Hello From Console

However, when I run this same program in a Docker container in detached mode (i.e, "docker run -d") and then check the logs, I only get the log from the Console.WriteLine:

$ docker logs <container_id>
Hello From Console

While trying to track this down, I tried running the program using the daemonize tool (more info here) and it illustrated the same behavior, leading me to believe it was an issue with log4net instead of docker.
I also wrote a custom appender for log4net that only does Console.Write (I believe that's the same functionality as ConsoleAppender, but I wanted to eliminate any other possible variables):

public class CustomAppender: AppenderSkeleton
{
    protected override void Append(LoggingEvent loggingEvent)
    {
        Console.Write(RenderLoggingEvent(loggingEvent));
    }
}

But no luck.
Can anyone with a deep knowledge of log4net point me to where I could be doing something wrong, or explain what log4net could be doing to stdout such that other programs that should be capturing that stream don't?

UPDATE: The plot thickens! I wrote a quick and dirty executable that uses the Process class to execute my example program. It then grabs the stdout from the example program and writes it with Console.WriteLine, like so:

Process proc = new Process();
proc.StartInfo.FileName = "/path/to/example.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInto.RedirectStandardOutput = true;
proc.Start();
Thread.Sleep(1000);
Console.WriteLine(proc.StandardOutput.ReadToEnd());

This works fine when I run it directly from the console, but has the same problem when I run it from docker / daemonize. So now I'm really confused.