问:
Lint crashes on a Java class reading a Kotlin object
I have a Kotlin data class:

```<code>data class InterviewCreation(
    val candidateId: String,
    val offerId: String,
    val startingDateTime: Long,
    val duration: Long,
    val location: String,
    val description: String?
    )
</code>```

and a Mapper class (in Java) that starts like this:

```<code>public InterviewCreationViewModel toViewModel(InterviewCreation newInterview, String candidateName, String candidatePhotoUrl) {
    String description = newInterview.getDescription();
    String location = newInterview.getLocation();
    long duration = newInterview.getDuration();
    ...
}
</code>```

When running Lint, it crashes in the Mapper class

```<code> ECJ compiler crashed processing .../InterviewCreationViewModelMapper.java
java.lang.NullPointerException
        at org.eclipse.jdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:138)
        at org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.analyseCode(LocalDeclaration.java:89)
        at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:125)
        at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.internalAnalyseCode(TypeDeclaration.java:739)
        at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.analyseCode(TypeDeclaration.java:263)
        at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:118)
        at com.android.tools.lint.EcjParser$NonGeneratingCompiler.process(EcjParser.java:1521)
        at org.eclipse.jdt.internal.compiler.Compiler.processCompiledUnits(Compiler.java:550)
        at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:462)
        at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:417)
        at com.android.tools.lint.EcjParser.parse(EcjParser.java:644)
        at com.android.tools.lint.EcjParser.prepareJavaParse(EcjParser.java:369)
        at com.android.tools.lint.client.api.JavaPsiVisitor.prepare(JavaPsiVisitor.java:347)
        at com.android.tools.lint.client.api.LintDriver.visitJavaFiles(LintDriver.java:1674)
        at com.android.tools.lint.client.api.LintDriver.checkJava(LintDriver.java:1654)
        at com.android.tools.lint.client.api.LintDriver.runFileDetectors(LintDriver.java:1185)
        at com.android.tools.lint.client.api.LintDriver.checkProject(LintDriver.java:1039)
        at com.android.tools.lint.client.api.LintDriver.analyze(LintDriver.java:552)
        at com.android.tools.lint.client.api.LintDriver.analyze(LintDriver.java:483)
        at com.android.tools.lint.LintCliClient.run(LintCliClient.java:143)
        at com.android.build.gradle.internal.LintGradleClient.run(LintGradleClient.java:197)
        at com.android.build.gradle.tasks.Lint.runLint(Lint.java:340)
        at com.android.build.gradle.tasks.Lint.lintSingleVariant(Lint.java:307)
        at com.android.build.gradle.tasks.Lint.lint(Lint.java:119)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:632)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:615)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$RunTasksAction.execute(DefaultGradleLauncher.java:256)
        at org.gradle.initialization.DefaultGradleLauncher$RunTasksAction.execute(DefaultGradleLauncher.java:253)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:175)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:31)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
</code>```

And then it generates a lint report with a lot of false positives (I guess it's just not working right after the exception).

I've tried several things:

using class instead of data class

upgrading everything to last version (tools, sdk, etc)

Changing names of related objects

Replace Kotlin class with a Java class (this case works)

Making the mapper an internal class of another class (this case works)

Move it to another package

Comment all the method and make it return null (this works). Basically, the three first lines are the ones making it crash

replace the all the newInterview.get by constant values, but it also crashes

Obviously, none of these solutions is the desired one, but at this point I'm quite desperate. My two main options are stop using Lint or Kotlin.

Any suggestion is welcome.

答:
Finally found the source of the problem.

The crash is because the whole class was invoked from a lambda, and retrolambda and lint are not friends.

I moved the whole lambda call to a method and it works.

More info on this issue:

https://github.com/evant/gradle-retrolambda/issues/96

Body:
I have a Kotlin data class:

data class InterviewCreation(
    val candidateId: String,
    val offerId: String,
    val startingDateTime: Long,
    val duration: Long,
    val location: String,
    val description: String?
    )

and a Mapper class (in Java) that starts like this:

public InterviewCreationViewModel toViewModel(InterviewCreation newInterview, String candidateName, String candidatePhotoUrl) {
    String description = newInterview.getDescription();
    String location = newInterview.getLocation();
    long duration = newInterview.getDuration();
    ...
}

When running Lint, it crashes in the Mapper class

 ECJ compiler crashed processing .../InterviewCreationViewModelMapper.java
java.lang.NullPointerException
        at org.eclipse.jdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:138)
        at org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.analyseCode(LocalDeclaration.java:89)
        at org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:125)
        at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.internalAnalyseCode(TypeDeclaration.java:739)
        at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.analyseCode(TypeDeclaration.java:263)
        at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:118)
        at com.android.tools.lint.EcjParser$NonGeneratingCompiler.process(EcjParser.java:1521)
        at org.eclipse.jdt.internal.compiler.Compiler.processCompiledUnits(Compiler.java:550)
        at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:462)
        at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:417)
        at com.android.tools.lint.EcjParser.parse(EcjParser.java:644)
        at com.android.tools.lint.EcjParser.prepareJavaParse(EcjParser.java:369)
        at com.android.tools.lint.client.api.JavaPsiVisitor.prepare(JavaPsiVisitor.java:347)
        at com.android.tools.lint.client.api.LintDriver.visitJavaFiles(LintDriver.java:1674)
        at com.android.tools.lint.client.api.LintDriver.checkJava(LintDriver.java:1654)
        at com.android.tools.lint.client.api.LintDriver.runFileDetectors(LintDriver.java:1185)
        at com.android.tools.lint.client.api.LintDriver.checkProject(LintDriver.java:1039)
        at com.android.tools.lint.client.api.LintDriver.analyze(LintDriver.java:552)
        at com.android.tools.lint.client.api.LintDriver.analyze(LintDriver.java:483)
        at com.android.tools.lint.LintCliClient.run(LintCliClient.java:143)
        at com.android.build.gradle.internal.LintGradleClient.run(LintGradleClient.java:197)
        at com.android.build.gradle.tasks.Lint.runLint(Lint.java:340)
        at com.android.build.gradle.tasks.Lint.lintSingleVariant(Lint.java:307)
        at com.android.build.gradle.tasks.Lint.lint(Lint.java:119)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:632)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:615)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$RunTasksAction.execute(DefaultGradleLauncher.java:256)
        at org.gradle.initialization.DefaultGradleLauncher$RunTasksAction.execute(DefaultGradleLauncher.java:253)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:175)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:31)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

And then it generates a lint report with a lot of false positives (I guess it's just not working right after the exception).

I've tried several things:

using class instead of data class

upgrading everything to last version (tools, sdk, etc)

Changing names of related objects

Replace Kotlin class with a Java class (this case works)

Making the mapper an internal class of another class (this case works)

Move it to another package

Comment all the method and make it return null (this works). Basically, the three first lines are the ones making it crash

replace the all the newInterview.get by constant values, but it also crashes

Obviously, none of these solutions is the desired one, but at this point I'm quite desperate. My two main options are stop using Lint or Kotlin.

Any suggestion is welcome.


来源: stackexchange

问:
Doing a Requery on a Form opened with acFormAdd creates a new record
Lets asume a user wants to create a new record and to do so he opens a form. When opening a form with

```<code>DoCmd.OpenForm "FormName", acNormal, "", "", acFormAdd, acDialog
</code>```

Access will open the form with the data pointer set on a new/empty record. The user can now fill the form but some user actions may require a Me.Requery in order to take place. If you do so, the form "looses" the data pointer on the currently created and modified record and jumps to a new, empty record. Even a Me.Dirty = False before the requery wont prevent Access from doing so. Im pretty sure this behavior results from the paramter acFormAdd.

In contrast, opening a form with

```<code>DoCmd.OpenForm "FormName", acNormal, "", "WHERE-CLAUSE", acFormEdit, acDialog
</code>```

resolves the behavior but will only work for existing records.

You can imagine that this unrequested behavior is not what I'm expecting because it forces me to implement an ugly workaround with closing and reopening the from when certain conditions are fulfilled.

So, I'm wondering if there is a much easier way that helps me avoid the behevior described above. I would very much appreciate your assistance!

答:
Maybe a better solution might be to use .recalc instead.</p>

```<code>DoCmd.Save
Me.recalc
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Lets asume a user wants to create a new record and to do so he opens a form. When opening a form with

DoCmd.OpenForm "FormName", acNormal, "", "", acFormAdd, acDialog

Access will open the form with the data pointer set on a new/empty record. The user can now fill the form but some user actions may require a Me.Requery in order to take place. If you do so, the form "looses" the data pointer on the currently created and modified record and jumps to a new, empty record. Even a Me.Dirty = False before the requery wont prevent Access from doing so. Im pretty sure this behavior results from the paramter acFormAdd.

In contrast, opening a form with

DoCmd.OpenForm "FormName", acNormal, "", "WHERE-CLAUSE", acFormEdit, acDialog

resolves the behavior but will only work for existing records.

You can imagine that this unrequested behavior is not what I'm expecting because it forces me to implement an ugly workaround with closing and reopening the from when certain conditions are fulfilled.

So, I'm wondering if there is a much easier way that helps me avoid the behevior described above. I would very much appreciate your assistance!

Body:
Maybe a better solution might be to use .recalc instead.

DoCmd.Save
Me.recalc


问:
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.

I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.

The problem is that I don't know where to start investigating how to do this.  Let's say I have a script called:

file_arranger.py

What do I need to do to have a webpage execute that script?  This isn't meant for public consumption, so anything lightweight would be great.  For bonus points, what do I need to look into to provide the web user with the output from such scripts?

edit:  The first answer made me realize I forgot to include that this is a Win2k3 system.

答:
A simple cgi script (or set of scripts) is all you need to get started. The other answers have covered how to do this so I won't repeat it; instead, I will stress that using plain text will get you a long way. Just output the header (print("Content-type: text/plain\n") plus print adds its own newline to give you the needed blank line) and then run your normal program.

This way, any normal output from your script gets sent to the browser and you don't have to worry about HTML, escaping, frameworks, anything. "Do the simplest thing that could possibly work."

This is especially appropriate for non-interactive private administrative tasks like you describe, and lets you use identical programs from a shell with a minimum of fuss. Your driver, the page with the buttons, can be a static HTML file with single-button forms. Or even a list of links.

To advance from there, look at the logging module (for example, sending INFO messages to the browser but not the command line, or easily categorizing messages by using different loggers, by configuring your handlers), and then start to consider template engines and frameworks.

Don't output your own HTML and skip to using one of the many existing libraries—it'll save a ton of headache even spending a bit of extra time to learn the library. Or at the very least encapsulate your output by effectively writing your own mini-engine.

OwnerDisplayName: Therms

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: J.F. Sebastian

OwnerDisplayName: Roger Pate


问:
Maven systemPath is not added to runtime classpath
I need to add JDK's tools.jar as a project dependency.

Setting it as a normal dependency is not working, because when installing it to the Maven repository, it adds a version number to the jar file. Thereafter, when I need something that needs tools.jar to be in the classpath, it fails.

Using the system scope and setting the path to the jar using < systemPath > should solve the problem. However, although in tests the jar is added to the classpath, at runtime it is not.

Is there a way around this?

Btw, I've added < useManifestOnlyJar >false< /useManifestOnlyJar > to the surefireplugin so that I can see every file in the classpath.

答:
if it is not included in your JDK, use system scope, see the FAQ</p>

```<code><profiles>
  <profile>
    <id>default-tools.jar</id>
    <activation>
      <property>
        <name>java.vendor</name>
        <value>Sun Microsystems Inc.</value>
      </property>
    </activation>
    <dependencies>
      <dependency>
        <groupId>com.sun</groupId>
        <artifactId>tools</artifactId>
        <version>1.4.2</version>
        <scope>system</scope>
        <systemPath>${java.home}/../lib/tools.jar</systemPath>
      </dependency>
    </dependencies>
  </profile>
</profiles>
</code>```

Body:
if it is not included in your JDK, use system scope, see the FAQ

<profiles>
  <profile>
    <id>default-tools.jar</id>
    <activation>
      <property>
        <name>java.vendor</name>
        <value>Sun Microsystems Inc.</value>
      </property>
    </activation>
    <dependencies>
      <dependency>
        <groupId>com.sun</groupId>
        <artifactId>tools</artifactId>
        <version>1.4.2</version>
        <scope>system</scope>
        <systemPath>${java.home}/../lib/tools.jar</systemPath>
      </dependency>
    </dependencies>
  </profile>
</profiles>


问:
Resizing component Rating of gluon
I'm trying to resize a Rating component by css and by code with this instruction:

```<code>Rating rating= new Rating();
rating.setPrefWidht(100);
rating.setPrefHeight(40);
</code>```

But in both cases the rating doesn't resize!
Any helps?
Thanks in advance

答:
As the Rating control seems to ignore the set prefSize, you have to set the size of the rating buttons, e.g.:

```<code>.rating > .container > .button{
    -fx-min-width: 20;
    -fx-min-height: 20;

    -fx-max-width: 20;
    -fx-max-height: 20;
}
</code>```

Title: Resizing component Rating of gluon

Body:
I'm trying to resize a Rating component by css and by code with this instruction:

Rating rating= new Rating();
rating.setPrefWidht(100);
rating.setPrefHeight(40);

But in both cases the rating doesn't resize!
Any helps?
Thanks in advance

Body:
As the Rating control seems to ignore the set prefSize, you have to set the size of the rating buttons, e.g.:

.rating > .container > .button{
    -fx-min-width: 20;
    -fx-min-height: 20;

    -fx-max-width: 20;
    -fx-max-height: 20;
}


问:
How can I make setInterval increase each time when user clicks?
This is from JavaScript for kids, and I am stuck. How can I make setInterval increase each time the user clicks on the header? I have tried several solutions such as setInterval(moveheading,counter) or creating multiple setIntervals but it always seems to choose the fastest one and then proceeds to lose the second slowest (creating the opposite desired effect).

I have read that maybe setTimeOut would be a better solution to this, but I am having a hard time figuring out how. The book 'JavaScript for kids' can be found online as a PDF if you need further reference. The page where this challenge is at is 166.

```<code><!DOCTYPE html>
<html>

<head>
    <title>MouseMove</title>
</head>

<body>
    <h1 id='heading'> Try and click me 10 times.</h1>

    <script src='https://code.jquery.com/jquery-2.1.0.js'></script>

    <script>
        var leftOffset = 0;
        var topOffset = (200, 0);
        var rightOffset = 200;
        var toTheTop = (0, 200);
        var counter = 10;
        var congrats = "Congrats you Win!"

        var moveHeading = function() {

            $('#heading').offset({
                top:0,
                left: leftOffset
            });
            leftOffset++;

            if (leftOffset > 200) {

                $('#heading').offset({
                   top: topOffset,
                    left: 200

                });
                topOffset++;

            }
            if (topOffset > 200) {
                 $('#heading').offset({
                     left:rightOffset,
                     top: 200

            });
           rightOffset--

            };
             if (rightOffset < 0) {
                $('#heading').offset({
                 left:(200,0),
                    top:toTheTop

                });
                toTheTop--;
             }

           <p> ijfsdkfjnlskdjfklsdjfs</P>

        if (toTheTop < 0){
      leftOffset = 0,
        topOffset = (200, 0),
         rightOffset = 200,
          toTheTop= (200);

            }

        };

   var ghost = function () {
       $("#heading").text(counter)
       counter--;
   }

     var chill =function ()  {

  if (counter < 7 )
        clearInterval(nuts);}

    var nuts = setTimeout(moveHeading,1000)

  $("#heading").click(moveHeading)
         $("#heading").click(ghost)

        $("#heading").click(chill);
    </script>

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

答:
Why you can make settimeout as setinterval,

function function1(time) {
    console.log("Time is :" + time); // run this it is actually funny
}
let x;
function runner(time) {
    function1(time);
    x = setTimeout(function() {
        runner(1000);
    }, time);
    clearTimeout(x); // Comment out this clear timeout and see the output
}

runner(100);```

try this type of solution

Body:
This is from JavaScript for kids, and I am stuck. How can I make setInterval increase each time the user clicks on the header? I have tried several solutions such as setInterval(moveheading,counter) or creating multiple setIntervals but it always seems to choose the fastest one and then proceeds to lose the second slowest (creating the opposite desired effect).

I have read that maybe setTimeOut would be a better solution to this, but I am having a hard time figuring out how. The book 'JavaScript for kids' can be found online as a PDF if you need further reference. The page where this challenge is at is 166.

<!DOCTYPE html>

    <title>MouseMove</title>

 Try and click me 10 times.

Body:
Why you can make settimeout as setinterval,

function function1(time) {
    console.log("Time is :" + time); // run this it is actually funny
}
let x;
function runner(time) {
    function1(time);
    x = setTimeout(function() {
        runner(1000);
    }, time);
    clearTimeout(x); // Comment out this clear timeout and see the output
}

runner(100);

try this type of solution


问:
Keypress but not when input or textarea is in focus
I'm using the code below :

```<code>$(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        doStuff();
    }
});
</code>```

What i want is to capture the key 'D' as a shortcut to a function in my page. Problem is , this page has inputs and textarea controls and when i'm'typing on this controls, the 'doStuff()' function is called.

How to avoid it ? I want the key 'D' capture only if the user is not typing anything in editable controls.

Thanks !

答:
Add another check before executing the 'doStuff' function. Check if the user has any input element in focus, and if true then only execute the statement.

Something like this:

```<code>$(document).keypress(function (e) {
    if ( (e.which === 68 || e.which === 100) && (!$(input).is(":focus")) ) {
        doStuff();
    }
});
</code>```

Body:
I'm using the code below :

$(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        doStuff();
    }
});

What i want is to capture the key 'D' as a shortcut to a function in my page. Problem is , this page has inputs and textarea controls and when i'm'typing on this controls, the 'doStuff()' function is called.

How to avoid it ? I want the key 'D' capture only if the user is not typing anything in editable controls.

Thanks !

Body:
Add another check before executing the 'doStuff' function. Check if the user has any input element in focus, and if true then only execute the statement.

Something like this:

$(document).keypress(function (e) {
    if ( (e.which === 68 || e.which === 100) && (!$(input).is(":focus")) ) {
        doStuff();
    }
});


问:
Unique Array for dates Javascript
I see this question asked quite often for regular javascript arrays, however none of the answers seems to work if its an array of dates.

I can likely figure this out through trial an error but I do see some benefit to others if I ask.

Basically if you have a javascript array of dates that might have duplicates and need to filter into an array with no duplicates what is the best way to go about that?

I have tried the ES6 solution of Array.from(new Set(arr)) but it just returns the same array.

Also I tried

```<code>Array.prototype.unique = function() {
    var a = [];
    for (var i=0, l=this.length; i<l; i++)
        if (a.indexOf(this[i]) === -1)
            a.push(this[i]);
    return a;
}
</code>```

both came from Unique values in an array

However neither worked, looks like indexOf does not work on date objects.

Here is how my array is generated atm

```<code>//this is an array generated from ajax data,
//its a year over year comparison with a separate year,
//so to create a reliable date objects I force it to use the same year.
data.map(d => {
   dp = new Date(Date.parse(d.date + '-' + d.year));
   dp.setFullYear(2000);
   return dp;
})
</code>```

It is about 100 or so different days, but it always ends up with about 350 index's.

答:
ES6 way:

```<code>datesArray.filter((date, i, self) =>
  self.findIndex(d => d.getTime() === date.getTime()) === i
)
</code>```

Thanks to https://stackoverflow.com/a/36744732/3161291

Title: Unique Array for dates Javascript

Body:
I see this question asked quite often for regular javascript arrays, however none of the answers seems to work if its an array of dates.

I can likely figure this out through trial an error but I do see some benefit to others if I ask.

Basically if you have a javascript array of dates that might have duplicates and need to filter into an array with no duplicates what is the best way to go about that?

I have tried the ES6 solution of Array.from(new Set(arr)) but it just returns the same array.

Also I tried

Array.prototype.unique = function() {
    var a = [];
    for (var i=0, l=this.length; i<l; i++)
        if (a.indexOf(this[i]) === -1)
            a.push(this[i]);
    return a;
}

both came from Unique values in an array

However neither worked, looks like indexOf does not work on date objects.

Here is how my array is generated atm

//this is an array generated from ajax data,
//its a year over year comparison with a separate year,
//so to create a reliable date objects I force it to use the same year.
data.map(d => {
   dp = new Date(Date.parse(d.date + '-' + d.year));
   dp.setFullYear(2000);
   return dp;
})

It is about 100 or so different days, but it always ends up with about 350 index's.

Body:
ES6 way:

datesArray.filter((date, i, self) =>
  self.findIndex(d => d.getTime() === date.getTime()) === i
)

Thanks to https://stackoverflow.com/a/36744732/3161291


问:
how to select not null values column dynamically?
I created a table like below. I want to select only NOT NULL column dynamically like(NO, NAME,SAL_1). No need to select SAL,SAL_2.

Note: Initially I don't know the columns values.

```<code>create table sample(no integer,name varchar(20),sal integer,sal_1 integer,sal_2 integer);
insert into sample(name,sal_1) values('aaa',10);
insert into sample(no,name,sal_1) values(20,'',20);
insert into sample(sal_1) values(30);

select * from sample;
</code>```

data like below

```<code>NO        NAME    SAL   SAL_1 SAL_2
20       (null)   (null)  20  (null)
(null)    (null)  (null)  30  (null)
(null)    aaa     (null)  10  (null)
</code>```

Expected op:

```<code>NO       NAME   SAL_1
20      (null)  20
(null)  (null)  30
(null)  aaa     10
</code>```

答:
The following query generates the query you want to execute through some dynamic SQL procedure.

Unfortunately I don't know well the Oracle syntax, the following is in PostgreSQL, but I guess you'll only have to change string_agg with the pertinent Oracle function catenating strings.

```<code>WITH columns (c) AS (
  SELECT 'no' WHERE EXISTS (SELECT * FROM sample WHERE no IS NOT NULL)
  UNION
  SELECT 'name' WHERE EXISTS (SELECT * FROM sample WHERE name IS NOT NULL)
  UNION
  SELECT 'sal' WHERE EXISTS (SELECT * FROM sample WHERE sal IS NOT NULL)
  UNION
  SELECT 'sal_1' WHERE EXISTS (SELECT * FROM sample WHERE sal_1 IS NOT NULL)
  UNION
  SELECT 'sal_2' WHERE EXISTS (SELECT * FROM sample WHERE sal_2 IS NOT NULL)
)
SELECT 'SELECT ' || string_agg(c, ', ') || ' FROM sample;' FROM columns;
</code>```

Body:
I created a table like below. I want to select only NOT NULL column dynamically like(NO, NAME,SAL_1). No need to select SAL,SAL_2.

Note: Initially I don't know the columns values.

create table sample(no integer,name varchar(20),sal integer,sal_1 integer,sal_2 integer);
insert into sample(name,sal_1) values('aaa',10);
insert into sample(no,name,sal_1) values(20,'',20);
insert into sample(sal_1) values(30);

select * from sample;

data like below

NO        NAME    SAL   SAL_1 SAL_2
20       (null)   (null)  20  (null)
(null)    (null)  (null)  30  (null)
(null)    aaa     (null)  10  (null)

Expected op:

NO       NAME   SAL_1
20      (null)  20
(null)  (null)  30
(null)  aaa     10

Body:
The following query generates the query you want to execute through some dynamic SQL procedure.

Unfortunately I don't know well the Oracle syntax, the following is in PostgreSQL, but I guess you'll only have to change string_agg with the pertinent Oracle function catenating strings.

WITH columns (c) AS (
  SELECT 'no' WHERE EXISTS (SELECT * FROM sample WHERE no IS NOT NULL)
  UNION
  SELECT 'name' WHERE EXISTS (SELECT * FROM sample WHERE name IS NOT NULL)
  UNION
  SELECT 'sal' WHERE EXISTS (SELECT * FROM sample WHERE sal IS NOT NULL)
  UNION
  SELECT 'sal_1' WHERE EXISTS (SELECT * FROM sample WHERE sal_1 IS NOT NULL)
  UNION
  SELECT 'sal_2' WHERE EXISTS (SELECT * FROM sample WHERE sal_2 IS NOT NULL)
)
SELECT 'SELECT ' || string_agg(c, ', ') || ' FROM sample;' FROM columns;


问:
How can I iterate over a list of lists?
I'm trying to sort through a list of lists. How could I go about printing or iterating over the first and last elements in each list? non-working code below:

```<code>from numpy import *
xs=[[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]]

for i in xs:
    for j in xs[i]:
        print(xs[1],xs[-1])
</code>```

Traceback error if needed:

```<code>runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')
Traceback (most recent call last):

  File "<ipython-input-14-8a28382c7f81>", line 1, in <module>
    runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/Alex/untitled9.py", line 13, in <module>
    for j in xs[i]:

TypeError: list indices must be integers or slices, not list
</code>```

Title: How can I iterate over a list of lists?

Body:
I'm trying to sort through a list of lists. How could I go about printing or iterating over the first and last elements in each list? non-working code below:

from numpy import *
xs=[[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]]

for i in xs:
    for j in xs[i]:
        print(xs[1],xs[-1])

Traceback error if needed:

runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')
Traceback (most recent call last):

  File "<ipython-input-14-8a28382c7f81>", line 1, in <module>
    runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/Alex/untitled9.py", line 13, in <module>
    for j in xs[i]:

TypeError: list indices must be integers or slices, not list

Body:
Try this:

li = []
for i in range(len(xs)):
    li.append([xs[i][0],xs[i][-1]])

output: [[1.0, 3.0], [4.0, 6.0], [7.0, 9.0]]


问:
using literal string for gawk
I thing I'm too close to the problem already that I just can solve it on my own, alltough I'm sure it's easy to solve.

I'm working on a NAS  with a SHELL Script for my Raspberry PI which automaticly collects data and distributes it over my other devices. So I decided to include a delete-option, since otherwise it would be a pain in the ass to delete a file, since the raspberry would always copy it right back from the other devices. While the script runs it creats a file: del_tmp_$ip.txt in which are directorys and files to delete from del_$ip.txt (Not del_TMP_$ip.txt).
It looks like this:

```<code>test/delete_me.txt
test/hello/hello.txt
pi.txt
</code>```

I tried to delete the lines viá awk, and this is how far I got by now:

```<code>while read r; do
 gawk -i inplace '!/^'$r'$/' del_$ip.txt
done <del_tmp_$ip.txt
</code>```

If the line from del_tmp_$ip.txt tells gawk to delete pi.txt it works without problems, but if the string includes a slash like test/delete_me.txt it doesn't work:

"unexpected newline or end of string"

and it points to the last slash then.

I can't escape the forwardslash with a backwardslash manually, since I don't know whether and how many slashes there will be. Depending on the line of the file which contains the information to be deleted.

I hope you can help me!

答:
Never allow a shell variable to expand to become part of the awk script text before awk evaluates it (which is what you're doing with '!/^'$r'$/') and always quote your shell variables (so the correct shell syntax would have been '!/^'"$r"'$/' IF it hadn't been the wrong approach anyway). The correct syntax to write that command would have been

```<code>awk -v r="$r" '$0 !~ "^"r"$"' file
</code>```

but you said you wanted a string comparison, not regexp so then it'd be simply:

```<code>awk -v r="$r" '$0 != r' file
</code>```

and of course you don't need a shell loop at all:

```<code>while read r; do
 gawk -i inplace '!/^'$r'$/' del_$ip.txt
done <del_tmp_$ip.txt
</code>```

you just need 1 awk command:

```<code>gawk -i inplace 'NR==FNR{skip[$0];print;next} !($0 in skip)' "del_tmp_$ip.txt" "del_$ip.txt"
</code>```

Title: using literal string for gawk

Body:
I thing I'm too close to the problem already that I just can solve it on my own, alltough I'm sure it's easy to solve.

I'm working on a NAS  with a SHELL Script for my Raspberry PI which automaticly collects data and distributes it over my other devices. So I decided to include a delete-option, since otherwise it would be a pain in the ass to delete a file, since the raspberry would always copy it right back from the other devices. While the script runs it creats a file: del_tmp_$ip.txt in which are directorys and files to delete from del_$ip.txt (Not del_TMP_$ip.txt).
It looks like this:

test/delete_me.txt
test/hello/hello.txt
pi.txt

I tried to delete the lines viá awk, and this is how far I got by now:

while read r; do
 gawk -i inplace '!/^'$r'$/' del_$ip.txt
done <del_tmp_$ip.txt

If the line from del_tmp_$ip.txt tells gawk to delete pi.txt it works without problems, but if the string includes a slash like test/delete_me.txt it doesn't work:

"unexpected newline or end of string"

and it points to the last slash then.

I can't escape the forwardslash with a backwardslash manually, since I don't know whether and how many slashes there will be. Depending on the line of the file which contains the information to be deleted.

I hope you can help me!

Body:
Never allow a shell variable to expand to become part of the awk script text before awk evaluates it (which is what you're doing with '!/^'$r'$/') and always quote your shell variables (so the correct shell syntax would have been '!/^'"$r"'$/' IF it hadn't been the wrong approach anyway). The correct syntax to write that command would have been

awk -v r="$r" '$0 !~ "^"r"$"' file

but you said you wanted a string comparison, not regexp so then it'd be simply:

awk -v r="$r" '$0 != r' file

and of course you don't need a shell loop at all:

while read r; do
 gawk -i inplace '!/^'$r'$/' del_$ip.txt
done <del_tmp_$ip.txt

you just need 1 awk command:

gawk -i inplace 'NR==FNR{skip[$0];print;next} !($0 in skip)' "del_tmp_$ip.txt" "del_$ip.txt"


问:
PMVS definition of "n-adjacent"
I am currently reading over Yasutaka Furukawa et al.'s Paper "Accurate, Dense, and Robust Multi-View Stereopsis" (PDF available here), where they describe an MVS-algorithm for reconstructing a 3D point-cloud from images.

I do understand the concepts and the main steps, but there is one detail that I am struggling with. This may be because I am not an English native speaker, so maybe a small hint would be enough.

On page 4 of the linked source, in chapter 3.2 "Expansion", there is the definition of "n-adjacent" patches:

```<code>|(c(p)−c(p'))·n(p)|+|(c(p)−c(p'))·n(p')| < 2ρ_2
</code>```

My question is about ρ_2, that is described as in the following:

[...] ρ_2 is determined automatically as the distance at the depth of the
  midpoint of c(p) and c(p') corresponding to an image displacement of β1 pixels
  in R(p).

I do not understand what "distance" in this context should be, and I do not understand the stated correspondence to the image  displacement.

I know that this is a very specific question, but since this paper is somewhat popular I hoped, that there is somebody, that can help me.

答:
Alright, I think I do get it now.

It just means, that ρ_2 is the distance you have to move in a plane, located as far away from the camera (depth) as the midpoint of c(p) and c(p'), so that you get a displacement of β1 pixels in the image showing the scene.

Title: PMVS definition of "n-adjacent"

Body:
I am currently reading over Yasutaka Furukawa et al.'s Paper "Accurate, Dense, and Robust Multi-View Stereopsis" (PDF available here), where they describe an MVS-algorithm for reconstructing a 3D point-cloud from images.

I do understand the concepts and the main steps, but there is one detail that I am struggling with. This may be because I am not an English native speaker, so maybe a small hint would be enough.

On page 4 of the linked source, in chapter 3.2 "Expansion", there is the definition of "n-adjacent" patches:

|(c(p)−c(p'))·n(p)|+|(c(p)−c(p'))·n(p')| < 2ρ_2

My question is about ρ_2, that is described as in the following:

[...] ρ_2 is determined automatically as the distance at the depth of the
  midpoint of c(p) and c(p') corresponding to an image displacement of β1 pixels
  in R(p).

I do not understand what "distance" in this context should be, and I do not understand the stated correspondence to the image  displacement.

I know that this is a very specific question, but since this paper is somewhat popular I hoped, that there is somebody, that can help me.


问:
How to see the spark-launcher command being submitted when using org.apache.spark.launcher.SparkLauncher?
Is there a way to see the spark-launcher CLI command that will be submitted to spark when using the following line in JAVA to send an already configured spark launcher?

```<code>SparkLauncher().launch();
</code>```

Edit: The method "createBuilder" within "SparkLauncher.class" seems to have it, as a list, during the ".launch()" process.
Now this is a matter of finding the way to extract that information from the point there the "SparkLauncher().launch()" is being submitted.

答:
Given you define your sparkLauncher as: "launcher"
You can get the spark-submit command this way:</p>

```<code>String sparkSubmitCommand = StringUtils.join(launcher.createBuilder().command(), " ");
</code>```

Body:
Is there a way to see the spark-launcher CLI command that will be submitted to spark when using the following line in JAVA to send an already configured spark launcher?

SparkLauncher().launch();

Edit: The method "createBuilder" within "SparkLauncher.class" seems to have it, as a list, during the ".launch()" process.
Now this is a matter of finding the way to extract that information from the point there the "SparkLauncher().launch()" is being submitted.

Body:
Given you define your sparkLauncher as: "launcher"
You can get the spark-submit command this way:

String sparkSubmitCommand = StringUtils.join(launcher.createBuilder().command(), " ");


问:
RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am building an application with Django Rest Framework and AngularJs. I am using Django-rest-auth for my authentication purposes, although, I have not been able to set it up. Anyway, I am trying to set up this app with my project. I realized I need to install django-rest-auth-registration to get it running, so I followed this documentation to do the following things:

I ran the commands

pip install django-rest-auth

and

pip install django-allauth

Any my settings.py looks like this:

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 3rd party apps
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'allauth',
    'allauth.account',
    'rest_auth.registration',

    # My app
    'myapp',
]
</code>```

I have also added the authentication backends, context_processors, and the proper urls.

However, when I try to migrate, my terminal throws the following error:

RuntimeError: Model class django.contrib.sites.models.Site doesn't
  declare an explicit app_label and isn't in an application in
  INSTALLED_APPS.

Why do I get this error, and how do I solve it to migrate my project? Thanks!

答:
I got the error above.  However my problem was the in the urls.py.  I was following PyDanny cookiecutter django recipe.  My error was to put in the urls.py this line:

```<code>    url(r'^demo/', include('project.demoapp.urls', namespace='demoapp')),
</code>```

when I corrected to this:

```<code>    url(r'^demo/', include('demoapp.urls', namespace='demoapp')),
</code>```

all was well.  I also changed my local apps (I did this first and so the critical error was the url misconfiguration):

```<code>LOCAL_APPS = [
    # Your stuff: custom apps go here
    'demoapp.apps.DemoAppConfig',
]
</code>```

Body:
I am building an application with Django Rest Framework and AngularJs. I am using Django-rest-auth for my authentication purposes, although, I have not been able to set it up. Anyway, I am trying to set up this app with my project. I realized I need to install django-rest-auth-registration to get it running, so I followed this documentation to do the following things:

I ran the commands

pip install django-rest-auth

and

pip install django-allauth

Any my settings.py looks like this:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 3rd party apps
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'allauth',
    'allauth.account',
    'rest_auth.registration',

    # My app
    'myapp',
]

I have also added the authentication backends, context_processors, and the proper urls.

However, when I try to migrate, my terminal throws the following error:

RuntimeError: Model class django.contrib.sites.models.Site doesn't
  declare an explicit app_label and isn't in an application in
  INSTALLED_APPS.

Why do I get this error, and how do I solve it to migrate my project? Thanks!

Body:
I got the error above.  However my problem was the in the urls.py.  I was following PyDanny cookiecutter django recipe.  My error was to put in the urls.py this line:

    url(r'^demo/', include('project.demoapp.urls', namespace='demoapp')),

when I corrected to this:

    url(r'^demo/', include('demoapp.urls', namespace='demoapp')),

all was well.  I also changed my local apps (I did this first and so the critical error was the url misconfiguration):

LOCAL_APPS = [
    # Your stuff: custom apps go here
    'demoapp.apps.DemoAppConfig',
]


问:
Font weight is changing on displaying as block
I'm trying to create those famous nav bars, but I'm encountering a weird problem...

I've created a JSFiddle that shows my code and my problem : JSFiddle

Basically when I'm hovering the "2" menu so that my dropdown-content is displayed as block (previously it was set to none) my whole document font-weight is changing...

Two things :

When I'm setting my .dropdown-content to display: block I'm not encountering this problem

Second when I'm setting my .head1 position to anything else than fixed I'm not encountering this problem

Thank you in advance for any clue !

And I forgot to mention but this only happens on Safari...

答:
Try adding

```<code>body{
  -webkit-font-smoothing: subpixel-antialiased;
}
</code>```

to your CSS. Worked for me in Safari when I added it in your JSFiddle.

Please have a look at: Font weight turns lighter on Mac/Safari

Body:
Try adding

body{
  -webkit-font-smoothing: subpixel-antialiased;
}

to your CSS. Worked for me in Safari when I added it in your JSFiddle.

Please have a look at: Font weight turns lighter on Mac/Safari


问:
Tiny error mark on my .cshtml page
I got a tiny little red underlining in one of my Razor @helper and when I hover on it it never shows anything. I remembering having had this in the past and sometimes it mysteriously disappears, do you know what it is? Here is a picture, it's just by the continue statement.

Pls help me help this helper :)

答: In razor, in cshtml file every if else codes should  be inside {}

Title: Tiny error mark on my .cshtml page


问:
fire event when touch up inside uiview and outside button
I have a view overlayed to the iPhone's camera view. In this view I have some uibuttons that are displayed in positions depending of values from accelerometer/compass.
I need to fire an event when the user touch up inside the view but he doesn't touch up inside the uibuttons, I mean, the opposite action of touch up inside the uibuttons.
Anyone knows a kind to do this?
Thanks! </p>

答:
you may e.g. assign one event handler (IBAction) to UiVeiw and its UIButtons and then compare sender parameter:</p>

```<code>-(IBAction) viewClicked :(id) sender {
  if (id == myView) ...
}
</code>```

Body:
you may e.g. assign one event handler (IBAction) to UiVeiw and its UIButtons and then compare sender parameter:

-(IBAction) viewClicked :(id) sender {
  if (id == myView) ...
}


答:
```<code>$(document).on('keypress', ':not(:input)', function (e) {
    if (e.which === 68 || e.which === 100) {
        doStuff();
    }
});
</code>```

Title: Keypress but not when input or textarea is in focus

Body:
I'm using the code below :

$(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        doStuff();
    }
});

What i want is to capture the key 'D' as a shortcut to a function in my page. Problem is , this page has inputs and textarea controls and when i'm'typing on this controls, the 'doStuff()' function is called.

How to avoid it ? I want the key 'D' capture only if the user is not typing anything in editable controls.

Thanks !


问:
Move values after comma to newline to text file
I have values in my database that has values with commas. Eg:

Monday,Tuesday,Wednesday,Thursday,Friday. When I call the row from the database where certain id, I want to write the the result to a text file after every comma into a new line as follows:

```<code>Monday
Tuesday
Wednesday
Thursday
Friday
</code>```

One below the other.

Hope this makes sense.

答:
You can use explode function.

explode — Split a string by string

```<code>$days   = "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday";
$weekdays = explode(",", $days);

foreach( $weekdays as $value ){
    echo $value."\n";
}
</code>```

Output:

```<code>Monday
Tuesday
Wednesday
Thursday
Friday
</code>```

I think it will work for you!

Body:
I have values in my database that has values with commas. Eg:

Monday,Tuesday,Wednesday,Thursday,Friday. When I call the row from the database where certain id, I want to write the the result to a text file after every comma into a new line as follows:

Monday
Tuesday
Wednesday
Thursday
Friday

One below the other.

Hope this makes sense.

Body:
You can use explode function.

explode — Split a string by string

$days   = "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday";
$weekdays = explode(",", $days);

foreach( $weekdays as $value ){
    echo $value."\n";
}

Output:

Monday
Tuesday
Wednesday
Thursday
Friday

I think it will work for you!


问:
Refering DBI functions in package - which to use?
When developing package using DBI extension (e.g. RJDBC, RSQLite) which package should I refer to?

```<code>connect_my_db <- function() DBI::dbConnect(RSQLite::SQLite(), "my_db.sqlite")
</code>```

or

```<code>connect_my_db <- function() RSQLite::dbConnect(RSQLite::SQLite(), "my_db.sqlite")
</code>```

?

First method force me to use DBI in Imports, so I prefer second one. But on other side I should call virtual function and let R to decide what to call.

答: From the viewpoint of the end-user, it doesn't matter: RSQLite depends on DBI, so your package will require both RSQLite and DBI to be installed anyway. From a stylistic viewpoint, I'd prefer the first approach, since otherwise you're second-guessing R's method dispatch mechanism.</p>

Body:
When developing package using DBI extension (e.g. RJDBC, RSQLite) which package should I refer to?

connect_my_db <- function() DBI::dbConnect(RSQLite::SQLite(), "my_db.sqlite")

or

connect_my_db <- function() RSQLite::dbConnect(RSQLite::SQLite(), "my_db.sqlite")

?

First method force me to use DBI in Imports, so I prefer second one. But on other side I should call virtual function and let R to decide what to call.


问:
i am using angularjs and django-cors-headers then give "which is disallowed for cross-origin requests that require preflight."
I have a Django local sever that refer to 8000 port number, And a local nginx that load 2080 port number html page.

I install django-cross-header package for resolving cross-domain error.

django-cross-header config in settings.py:

```<code>CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

  CORS_ALLOW_HEADERS = (
         'x-requested-with',
         'content-type',
         'accept',
         'origin',
         'authorization',
         'x-csrftoken'
 )

  CORS_ORIGIN_WHITELIST = (
          '127.0.0.1:2080',
          'localhost:2080'
  )
</code>```

Config angularjs  is like this:

```<code>portman.config(function ($routeProvider, $interpolateProvider, $httpProvider) {
     $routeProvider.otherwise('/');
     $httpProvider.defaults.headers.common['X-CSRFToken'] = csrftoken;
     $interpolateProvider.startSymbol('{$').endSymbol('$}');
     delete $httpProvider.defaults.headers.common['X-Requested-With'];

 });
 portman.constant('ip','http://127.0.0.1:8000/');
</code>```

Get method code in angularjs is:

```<code>$http({
         method: 'GET',
         url: ip+'api/v1/dslam/events',
     }).then(function (result) {
        $scope.dslam_events = result.data;
     }, function (err) {

    });
</code>```

request header is :
Provisional headers are shown

```<code>Accept:application/json, text/plain, */*
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36
X-CSRFToken:ztouFO8vldho97bWzY9mHQioFk3j6h5V
</code>```

After loading the page I see this error:

```<code>XMLHttpRequest cannot load http://127.0.0.1:8000/api/v1/dslam/events.The request was redirected to 'http://127.0.0.1:8000/api/v1/dslam/events/', which is disallowed for cross-origin requests that require preflight.
</code>```

But when i send request from console it will corectly response from django server, my jquery code :

```<code>$.ajax({
            type: 'GET',
            url: "http://5.202.129.160:8020/api/v1/dslam/events/",
            success:function(data){
             console.log(data);
            }
        });
</code>```

request header is:

```<code>Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,fa;q=0.6,pt;q=0.4
Connection:keep-alive
Host:127.0.0.1:8000
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36
</code>```

please help me.

答:
You need to add corsheaders to your installed apps.

```<code>INSTALLED_APPS = [
    ...,
    'corsheaders',
    ...,
]
</code>```

Add corsmiddleware to the middleware classes.

```<code>MIDDLEWARE_CLASSES = [
    ...,
    'corsheaders.middleware.CorsMiddleware',
    ...,
]
</code>```

And finally you are missing one slash at the end of the url "/".
Also you should add the csrf token at your http request so that it works
with unsafe http methods like POST, PATCH, PUT AND DELETE.

```<code>$http({
    method: 'GET',
    url: ip+'api/v1/dslam/events/',
    'X-CSRFToken' : $cookies.get('csrftoken')
}).then(function (result) {
    $scope.dslam_events = result.data;
}, function (err) {

});
</code>```

In order to the $cookies service to work, you need to install the ngCookies angular module and that's it.

Body:
I have a Django local sever that refer to 8000 port number, And a local nginx that load 2080 port number html page.

I install django-cross-header package for resolving cross-domain error.

django-cross-header config in settings.py:

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

  CORS_ALLOW_HEADERS = (
         'x-requested-with',
         'content-type',
         'accept',
         'origin',
         'authorization',
         'x-csrftoken'
 )

  CORS_ORIGIN_WHITELIST = (
          '127.0.0.1:2080',
          'localhost:2080'
  )

Config angularjs  is like this:

portman.config(function ($routeProvider, $interpolateProvider, $httpProvider) {
     $routeProvider.otherwise('/');
     $httpProvider.defaults.headers.common['X-CSRFToken'] = csrftoken;
     $interpolateProvider.startSymbol('{$').endSymbol('$}');
     delete $httpProvider.defaults.headers.common['X-Requested-With'];

 });
 portman.constant('ip','http://127.0.0.1:8000/');

Get method code in angularjs is:

$http({
         method: 'GET',
         url: ip+'api/v1/dslam/events',
     }).then(function (result) {
        $scope.dslam_events = result.data;
     }, function (err) {

    });

request header is :
Provisional headers are shown

Accept:application/json, text/plain, */*
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36
X-CSRFToken:ztouFO8vldho97bWzY9mHQioFk3j6h5V

After loading the page I see this error:

XMLHttpRequest cannot load http://127.0.0.1:8000/api/v1/dslam/events.The request was redirected to 'http://127.0.0.1:8000/api/v1/dslam/events/', which is disallowed for cross-origin requests that require preflight.

But when i send request from console it will corectly response from django server, my jquery code :

$.ajax({
            type: 'GET',
            url: "http://5.202.129.160:8020/api/v1/dslam/events/",
            success:function(data){
             console.log(data);
            }
        });

request header is:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,fa;q=0.6,pt;q=0.4
Connection:keep-alive
Host:127.0.0.1:8000
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36

please help me.

Body:
You need to add corsheaders to your installed apps.

INSTALLED_APPS = [
    ...,
    'corsheaders',
    ...,
]

Add corsmiddleware to the middleware classes.

MIDDLEWARE_CLASSES = [
    ...,
    'corsheaders.middleware.CorsMiddleware',
    ...,
]

And finally you are missing one slash at the end of the url "/".
Also you should add the csrf token at your http request so that it works
with unsafe http methods like POST, PATCH, PUT AND DELETE.

$http({
    method: 'GET',
    url: ip+'api/v1/dslam/events/',
    'X-CSRFToken' : $cookies.get('csrftoken')
}).then(function (result) {
    $scope.dslam_events = result.data;
}, function (err) {

});

In order to the $cookies service to work, you need to install the ngCookies angular module and that's it.


问:
where does back event is handel in swift 3.0
I want to refresh the whole page controller on back press.
I am navigating the viewcontroller using code.

My Code

```<code>let GTC = self.storyboard?.instantiateViewController(withIdentifier: "GoToCart")as! GoToCart
self.navigationController?.pushViewController(GTC, animated: true)
</code>```

答:
A better approach is to use protocol

Create protocol from where you want to pop back(GoToCart)

Create delegate variable in GoToCart

Extend GoToCart protocol in MainViewController

Give reference to GoToCart of MainViewController when
navigate

Define delegate Method in MainViewController

Then you can call delegate method from GoToCart

Example

In GoToCart: Write code below..

```<code>protocol GoCartControllerDelegate
{
 func childViewControllerResponse(parameter)
}

class GoToCart:UIViewController
{
var delegate: ChildViewControllerDelegate?
....
}
</code>```

Then in mainViewController implement the protocol function end extend to the protocol

```<code>class MainViewController:UIViewController,GoCartControllerDelegate
{
// Define Delegate Method
func childViewControllerResponse(parameter)
{

 //...here update what you want to update according to the  situation

}
}
</code>```

2 Important thing

when navigating to the gocart controller  code like this

```<code>let GTC = self.storyboard?.instantiateViewController(withIdentifier: "GoToCart")as! GoToCart
GTC.delegate = self
self.navigationController?.pushViewController(GTC, animated: true)
</code>```

and when popping from gocartViewController
code like this

```<code>self.navigationController?.popViewController(animated:true)
self.delegate?.childViewControllerResponse(parameter)
</code>```

Body:
I want to refresh the whole page controller on back press.
I am navigating the viewcontroller using code.

My Code

let GTC = self.storyboard?.instantiateViewController(withIdentifier: "GoToCart")as! GoToCart
self.navigationController?.pushViewController(GTC, animated: true)

Body:
A better approach is to use protocol

Create protocol from where you want to pop back(GoToCart)

Create delegate variable in GoToCart

Extend GoToCart protocol in MainViewController

Give reference to GoToCart of MainViewController when
navigate

Define delegate Method in MainViewController

Then you can call delegate method from GoToCart

Example

In GoToCart: Write code below..

protocol GoCartControllerDelegate
{
 func childViewControllerResponse(parameter)
}

class GoToCart:UIViewController
{
var delegate: ChildViewControllerDelegate?
....
}

Then in mainViewController implement the protocol function end extend to the protocol

class MainViewController:UIViewController,GoCartControllerDelegate
{
// Define Delegate Method
func childViewControllerResponse(parameter)
{

 //...here update what you want to update according to the  situation

}
}

2 Important thing

when navigating to the gocart controller  code like this

let GTC = self.storyboard?.instantiateViewController(withIdentifier: "GoToCart")as! GoToCart
GTC.delegate = self
self.navigationController?.pushViewController(GTC, animated: true)

and when popping from gocartViewController
code like this

self.navigationController?.popViewController(animated:true)
self.delegate?.childViewControllerResponse(parameter)


问:
Batch processing using PreparedStatement
Am I right when I say that I can only use 1 string sql query for batch processing using PreparedStatement in Java?

For example, this is the batch I want to process using PreparedStatement:

```<code>INSERT INTO tbl_Customer VALUES(?,?,?,?)
INSERT INTO tbl_Order VALUES(?,?,?,?,?)
</code>```

Is there any way to process these statements as a batch? Sorry for my bad English.

答:
You the following template:</p>

```<code>PreparedStatement ps = null;

ps = conn.prepareStatement("INSERT INTO tbl_Customer VALUES(?,?,?,?)");
while () {
    ...
    ps.addBatch();
}
result = ps.executeBatch();
</code>```

Body:
Am I right when I say that I can only use 1 string sql query for batch processing using PreparedStatement in Java?

For example, this is the batch I want to process using PreparedStatement:

INSERT INTO tbl_Customer VALUES(?,?,?,?)
INSERT INTO tbl_Order VALUES(?,?,?,?,?)

Is there any way to process these statements as a batch? Sorry for my bad English.

Body:
You the following template:

PreparedStatement ps = null;

ps = conn.prepareStatement("INSERT INTO tbl_Customer VALUES(?,?,?,?)");
while () {
    ...
    ps.addBatch();
}
result = ps.executeBatch();


答:
Something like that:</p>

```<code>$result   = "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday";
$array = explode(",", $result);

foreach( $array as $key => $value ){
    echo $value."\n";
}
</code>```

Title: Move values after comma to newline to text file

Body:
Something like that:

$result   = "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday";
$array = explode(",", $result);

foreach( $array as $key => $value ){
    echo $value."\n";
}


问:
Count the number of viewed pages that contain an exact string
I would like to count the number of viewed pages that contain some customer tagging, my code is currently returning the same value for all 3 counts and these values are far too high, can anyone suggest what the issue is here?</p>

```<code>SELECT
  Date,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff=" THEN 1 ELSE 0 END) AS Affinity,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff2=" THEN 1 ELSE 0 END) AS Addon_Affinity,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff3=" THEN 1 ELSE 0 END) AS Style_Affinity

FROM `dataset.ga_sessions_*` AS t
  CROSS JOIN UNNEST(hits) AS hits
WHERE (_TABLE_SUFFIX BETWEEN '20170703' AND '20170703')
group by date
</code>```

答:
COUNT will increase its sum by one if its input is not null. You should use SUM or COUNTIF instead:</p>

```<code>SELECT
  Date,
  COUNTIF(hits.page.pagepath LIKE "?aff=") AS Affinity,
  COUNTIF(hits.page.pagepath LIKE "?aff2=") AS Addon_Affinity,
  COUNTIF(hits.page.pagepath LIKE "?aff3=") AS Style_Affinity
FROM `[tablename].ga_sessions_*` AS t
  CROSS JOIN UNNEST(hits) AS hits
WHERE (_TABLE_SUFFIX BETWEEN '20170703' AND '20170703')
group by date
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to count the number of viewed pages that contain some customer tagging, my code is currently returning the same value for all 3 counts and these values are far too high, can anyone suggest what the issue is here?

SELECT
  Date,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff=" THEN 1 ELSE 0 END) AS Affinity,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff2=" THEN 1 ELSE 0 END) AS Addon_Affinity,
  COUNT(CASE WHEN hits.page.pagepath LIKE "?aff3=" THEN 1 ELSE 0 END) AS Style_Affinity

FROM `dataset.ga_sessions_*` AS t
  CROSS JOIN UNNEST(hits) AS hits
WHERE (_TABLE_SUFFIX BETWEEN '20170703' AND '20170703')
group by date

Body:
COUNT will increase its sum by one if its input is not null. You should use SUM or COUNTIF instead:

SELECT
  Date,
  COUNTIF(hits.page.pagepath LIKE "?aff=") AS Affinity,
  COUNTIF(hits.page.pagepath LIKE "?aff2=") AS Addon_Affinity,
  COUNTIF(hits.page.pagepath LIKE "?aff3=") AS Style_Affinity
FROM `[tablename].ga_sessions_*` AS t
  CROSS JOIN UNNEST(hits) AS hits
WHERE (_TABLE_SUFFIX BETWEEN '20170703' AND '20170703')
group by date


问:
Keypress but not when input or textarea is in focus
I'm using the code below :

```<code>$(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        doStuff();
    }
});
</code>```

What i want is to capture the key 'D' as a shortcut to a function in my page. Problem is , this page has inputs and textarea controls and when i'm'typing on this controls, the 'doStuff()' function is called.

How to avoid it ? I want the key 'D' capture only if the user is not typing anything in editable controls.

Thanks !

答:
Another one - </p>

```<code>  $(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        var _node = e.target.nodeName;
        if( _node !== "INPUT" && _node !== "TEXTAREA" ){
          doStuff();
        }
    }
  });
</code>```

Body:
Another one -

  $(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        var _node = e.target.nodeName;
        if( _node !== "INPUT" && _node !== "TEXTAREA" ){
          doStuff();
        }
    }
  });


问:
Elasticsearch converting a string to number
I am new to Elasticsearch and am just starting up with ELK stack. I am collecting key value type logs in my Logstash and passing it to an index in Elasticsearch. I am using the kv filter plugin in Logstash. Due to this, all the fields are string type by default.

When I try to perform aggregation like avg or sum on a numeric field in Elasticsearch, I am getting an Exception: ClassCastException[org.elasticsearch.index.fielddata.plain.PagedBytesIndexFieldData cannot be cast to org.elasticsearch.index.fielddata.IndexNumericFieldData]

When I check the mappings in the index, all the fields except the timestamp ones are marked as string.

Please tell me how to overcome this issue as I have many numeric fields in my log events for aggregation.

Thanks,

Keerthana

答:
In latest Logstash the syntax is as follows

```<code>filter {
  mutate {
    convert => { "fieldname" => "integer" }
  }
}
</code>```

You can visit this link for more detail: https://www.elastic.co/guide/en/logstash/current/plugins-filters-mutate.html#plugins-filters-mutate-convert

Body:
In latest Logstash the syntax is as follows

filter {
  mutate {
    convert => { "fieldname" => "integer" }
  }
}

You can visit this link for more detail: https://www.elastic.co/guide/en/logstash/current/plugins-filters-mutate.html#plugins-filters-mutate-convert


问:
Checking if platform supports Per-Render Target Blending
What would be the best way of checking if platform supports Per-Render Target Blending? In order to implement Weighted Blended Order-Independent
Transparency I need two render targets targets with different blending. On my current platform I am getting black and white in areas where the blending needs to happen. The blending functions are below. </p>

```<code>glEnable(GL_BLEND);
glBlendFunci(0, GL_ONE, GL_ONE);
glBlendFunci(1, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
</code>```

答:
glBlendFunci is supported > 4.x. Here is the supported version's excerpt.

Here is more information about it:
https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBlendFunc.xhtml

Body:
What would be the best way of checking if platform supports Per-Render Target Blending? In order to implement Weighted Blended Order-Independent
Transparency I need two render targets targets with different blending. On my current platform I am getting black and white in areas where the blending needs to happen. The blending functions are below.

glEnable(GL_BLEND);
glBlendFunci(0, GL_ONE, GL_ONE);
glBlendFunci(1, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);


问:
IllegalAccessError when I add a library
When I try to add this lib :

```<code>compile 'com.isupatches:wisefy:1.0.9'
</code>```

I have this error with my app (without using it) :

FATAL EXCEPTION: IntentService[GCM]
                                                   Process: my.app, PID: 7667
                                                   java.lang.IllegalAccessError: Method 'void
  android.support.v4.content.ContextCompat.()' is inaccessible to
  class 'com.google.android.gms.iid.zzd' (declaration of
  'com.google.android.gms.iid.zzd' appears in
  /data/app/my.app-1/base.apk:classes2.dex)
                                                       at com.google.android.gms.iid.zzd.zzdL(Unknown Source)
                                                       at com.google.android.gms.iid.zzd.(Unknown Source)
                                                       at com.google.android.gms.iid.zzd.(Unknown Source)
                                                       at com.google.android.gms.iid.InstanceID.zza(Unknown Source)
                                                       at com.google.android.gms.iid.InstanceID.getInstance(Unknown Source)
                                                       at gcm.RegistrationIntentService.onHandleIntent(RegistrationIntentService.java:54)
                                                       at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:67)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.os.HandlerThread.run(HandlerThread.java:61)

This is the line of the problem :

```<code> InstanceID instanceID = InstanceID.getInstance(this);
</code>```

I have look the reason of this error and it seem it's because I use a version too old of my play-services.

```<code>compile 'com.google.android.gms:play-services:8.3.0'
</code>```

But it's working without adding the lib wisefy so how can I isolate this problem (because I don't want to update my library) ?

答: By adding Wisefy, as it uses support-v4 too (like play-services-gcm), a more recent version of support-v4 will be used in your project which your old play-services-gcm library can not rely on. That's why you get this error.

Title: IllegalAccessError when I add a library

Body:
When I try to add this lib :

compile 'com.isupatches:wisefy:1.0.9'

I have this error with my app (without using it) :

FATAL EXCEPTION: IntentService[GCM]
                                                   Process: my.app, PID: 7667
                                                   java.lang.IllegalAccessError: Method 'void
  android.support.v4.content.ContextCompat.()' is inaccessible to
  class 'com.google.android.gms.iid.zzd' (declaration of
  'com.google.android.gms.iid.zzd' appears in
  /data/app/my.app-1/base.apk:classes2.dex)
                                                       at com.google.android.gms.iid.zzd.zzdL(Unknown Source)
                                                       at com.google.android.gms.iid.zzd.(Unknown Source)
                                                       at com.google.android.gms.iid.zzd.(Unknown Source)
                                                       at com.google.android.gms.iid.InstanceID.zza(Unknown Source)
                                                       at com.google.android.gms.iid.InstanceID.getInstance(Unknown Source)
                                                       at gcm.RegistrationIntentService.onHandleIntent(RegistrationIntentService.java:54)
                                                       at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:67)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.os.HandlerThread.run(HandlerThread.java:61)

This is the line of the problem :

 InstanceID instanceID = InstanceID.getInstance(this);

I have look the reason of this error and it seem it's because I use a version too old of my play-services.

compile 'com.google.android.gms:play-services:8.3.0'

But it's working without adding the lib wisefy so how can I isolate this problem (because I don't want to update my library) ?


问:
Antlr4 parse number failed
I am trying to use antlr4 to parse number (double and integer), but fail to success. Hope some one can help me.

My Test code is:

```<code>public class TestAntlr4 {

    @Test
    public void test() throws IOException {
        String input = "30";

        CharStream inputCharStream = new ANTLRInputStream(new StringReader(input));
        // create a lexer that feeds off of input CharStream
        TokenSource tokenSource = new GqlLexer(inputCharStream);
        // create a buffer of tokens pulled from the lexer
        TokenStream inputTokenStream = new CommonTokenStream(tokenSource);

        // create a parser that feeds off the tokens buffer
        TestAntlr4Parser parser = new TestAntlr4Parser(inputTokenStream);

        parser.removeErrorListeners(); // remove ConsoleErrorListener
        parser.addErrorListener(new VerboseListener());

        parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);

        NumberContext context = parser.number();

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

My antlr4 grammar is:

```<code>grammar TestAntlr4 ;

number
    : INT_NUMBER
    | DOUBLE_NUMBER ;

DOUBLE_NUMBER
    : ('+'|'-')? INTEGER '.' INTEGER? ;

INT_NUMBER
    : ('+'|'-')? INTEGER ;

WS
    : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

fragment INTEGER
    : '0'
    | '1'..'9' ('0'..'9')* ;

fragment DIGIT
    : [0-9] ;
</code>```

The result is:

```<code>rule stack: [number]
line 1:0 at [@0,0:1='30',<31>,1:0]: mismatched input '30' expecting {DOUBLE_NUMBER, INT_NUMBER}
[]
</code>```

Can anyone tell me what is wrong with this?

答:
The grammar seems to be okay.  Lexes and parses fine for me with input "30":

```<code>[@0,0:1='30',<INT_NUMBER>,1:0]
[@1,2:1='<EOF>',<EOF>,1:2]
</code>```

Tried also with a double:

```<code>[@0,0:6='30.3343',<DOUBLE_NUMBER>,1:0]
[@1,7:6='<EOF>',<EOF>,1:7]
</code>```

Parses just fine.

Now, in my environment I'm using the C# target, so my code is a little different from yours.

My (C#) code using the visitor pattern:

```<code>                AntlrInputStream inputStream = new AntlrInputStream(stream);
                Grammar1Lexer lexer = new Grammar1Lexer(inputStream);
                CommonTokenStream tokenStream = new CommonTokenStream(lexer);
                Grammar1Parser parser = new Grammar1Parser(tokenStream);
                IParseTree tree = parser.number();
                Grammar1Visitor visitor = new Grammar1Visitor();
                visitor.Visit(tree);
</code>```

Compiles and works just fine.

UPDATE:

I noticed that your lexer and your parser are named differently, could you have a simple copy/paste error?  Usually when you generate the classes all are named uniformly based on your grammar's name.

Title: Antlr4 parse number failed

Body:
I am trying to use antlr4 to parse number (double and integer), but fail to success. Hope some one can help me.

My Test code is:

public class TestAntlr4 {

    @Test
    public void test() throws IOException {
        String input = "30";

        CharStream inputCharStream = new ANTLRInputStream(new StringReader(input));
        // create a lexer that feeds off of input CharStream
        TokenSource tokenSource = new GqlLexer(inputCharStream);
        // create a buffer of tokens pulled from the lexer
        TokenStream inputTokenStream = new CommonTokenStream(tokenSource);

        // create a parser that feeds off the tokens buffer
        TestAntlr4Parser parser = new TestAntlr4Parser(inputTokenStream);

        parser.removeErrorListeners(); // remove ConsoleErrorListener
        parser.addErrorListener(new VerboseListener());

        parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);

        NumberContext context = parser.number();

        System.out.println(context.toString());
    }
}

My antlr4 grammar is:

grammar TestAntlr4 ;

number
    : INT_NUMBER
    | DOUBLE_NUMBER ;

DOUBLE_NUMBER
    : ('+'|'-')? INTEGER '.' INTEGER? ;

INT_NUMBER
    : ('+'|'-')? INTEGER ;

WS
    : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

fragment INTEGER
    : '0'
    | '1'..'9' ('0'..'9')* ;

fragment DIGIT
    : [0-9] ;

The result is:

rule stack: [number]
line 1:0 at [@0,0:1='30',<31>,1:0]: mismatched input '30' expecting {DOUBLE_NUMBER, INT_NUMBER}
[]

Can anyone tell me what is wrong with this?

Body:
The grammar seems to be okay.  Lexes and parses fine for me with input "30":

[@0,0:1='30',<INT_NUMBER>,1:0]
[@1,2:1='<EOF>',<EOF>,1:2]

Tried also with a double:

[@0,0:6='30.3343',<DOUBLE_NUMBER>,1:0]
[@1,7:6='<EOF>',<EOF>,1:7]

Parses just fine.

Now, in my environment I'm using the C# target, so my code is a little different from yours.

My (C#) code using the visitor pattern:

                AntlrInputStream inputStream = new AntlrInputStream(stream);
                Grammar1Lexer lexer = new Grammar1Lexer(inputStream);
                CommonTokenStream tokenStream = new CommonTokenStream(lexer);
                Grammar1Parser parser = new Grammar1Parser(tokenStream);
                IParseTree tree = parser.number();
                Grammar1Visitor visitor = new Grammar1Visitor();
                visitor.Visit(tree);

Compiles and works just fine.

UPDATE:

I noticed that your lexer and your parser are named differently, could you have a simple copy/paste error?  Usually when you generate the classes all are named uniformly based on your grammar's name.


问:
Ways to send a message from the server to the web browser at any time?
I'm in a situation where I want to be able to notify a visitor to my website of an event occurring at the server.

Think:

Website visitor is waiting for an export or report that takes a long time and is running in the background on the server, need to notify visitor when export is done.

or

Website visitor is waiting for a chat message from a sales rep, need to notify visitor when a message is sent to them.

I can think of a few ways to do this:

Keep an HTTP connection to the server
open forever

Continually polling the
HTTP server every second to check if
there are new messages

Write a Java
applet that holds a connection open
to a Java server process

None of these seem particularly graceful solutions... is there a better way to do this?

答:
As far as I'm concerned, the best way to approach this is to have the client poll the server. I don't know of any way to force information to a client's browser.

I would think polling from some sort of JavaScript/AJAX would be ideal.


问:
What's the difference between identifying and non-identifying relationships?
I haven't been able to fully grasp the differences. Can you describe both concepts and use real world examples?</p>

答:
Bill's answer is correct,
but it is shocking to see that among all the other answers no one points out the most significant aspect.

It has been said over and over again, that in an identifying relationship the child can not exist without the parent. (e.g. user287724). This is true, but completely misses the point. It would be enough for the foreign key to be non-null to achieve this. It does not need to be part of the primary key.

So here is the real reason:

The purpose of an identifying relationship is that the foreign key should NEVER CHANGE, because it is part of the primary key... therefore identifying!!!


问:
Performance : SQL Queries vs Server-Side PHP Loops (MYSQL vs PHP)
I have not seen much info on this topic and require some data . I am new to using complex MySQL queries and i was wondering about the performance costs of Complex queries in comparison to a simple query and then run server side php calculations on it .

E.g :

'Simple' query :

```<code>SELECT id as ID, date(x_date),  v_price as price
                From tableX
                WHERE v_price IN
                (
                    select MIN(v_price) from tableX
                    GROUP BY week(x_date)
                )
            )
</code>```

Now lets say i want to count the number of times similar prices occurred .

I can do it in 2 ways .

A) Use a foreach loop server side php and calculate the data

B) Do another select in sql

```<code>group by price
ORDER BY COUNT(price) DESC
</code>```

Which is the best way to proceed ? via SQL or server code (php)

What are the performance costs , time , server load etc.....

答:
Let' consider following example

```<code>select MIN(v_price) from tableX
</code>```

What this will do is it will look up tableX by an index and find lowest price.

Now let's try to do it outside of DB server. First you have to get data from DB

```<code>select v_price from tableX
</code>```

I hope you are seeing the difference already. It means pulling lot of data from storage on DB side and lot of data transfer. Even if your application and DB will be on the same machine it will mean lot of memory consumed and lot of CPU cycles spent on it.

So simple answer is do it in DB as it is almost always faster and less resource intensive.

Body:
I have not seen much info on this topic and require some data . I am new to using complex MySQL queries and i was wondering about the performance costs of Complex queries in comparison to a simple query and then run server side php calculations on it .

E.g :

'Simple' query :

SELECT id as ID, date(x_date),  v_price as price
                From tableX
                WHERE v_price IN
                (
                    select MIN(v_price) from tableX
                    GROUP BY week(x_date)
                )
            )

Now lets say i want to count the number of times similar prices occurred .

I can do it in 2 ways .

A) Use a foreach loop server side php and calculate the data

B) Do another select in sql

group by price
ORDER BY COUNT(price) DESC

Which is the best way to proceed ? via SQL or server code (php)

What are the performance costs , time , server load etc.....

Body:
Let' consider following example

select MIN(v_price) from tableX

What this will do is it will look up tableX by an index and find lowest price.

Now let's try to do it outside of DB server. First you have to get data from DB

select v_price from tableX

I hope you are seeing the difference already. It means pulling lot of data from storage on DB side and lot of data transfer. Even if your application and DB will be on the same machine it will mean lot of memory consumed and lot of CPU cycles spent on it.

So simple answer is do it in DB as it is almost always faster and less resource intensive.