问:
NDK is missing a "platforms" directory. while trying to build

Executing tasks: [clean]

Configuration on demand is an incubating feature. NDK is missing a
  "platforms" directory. If you are using NDK, verify the ndk.dir is set
  to a valid NDK directory.  It is currently set to
  /Users/ishandutta2007/Library/Android/sdk/ndk-bundle. If you are not
  using NDK, unset the NDK variable from ANDROID_NDK_HOME or
  local.properties to remove this warning.

Configuration 'compile' in project ':app' is deprecated. Use
  'implementation' instead.

FAILURE: Build failed with an exception.

What went wrong: A problem occurred configuring project ':app'.

java.lang.NullPointerException (no error message)

Try: Run with --info or --debug option to get more log output.

Exception is: org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'.  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:87)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:82)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:69)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:33)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:103)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:49)
  at
  org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:651)
  at
  org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:133)
  at
  org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
  at
  org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:62)
  at
  org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:100)
  at
  org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:81)
  at
  org.gradle.execution.commandline.CommandLineTaskParser.parseTasks(CommandLineTaskParser.java:42)
  at
  org.gradle.execution.TaskNameResolvingBuildConfigurationAction.configure(TaskNameResolvingBuildConfigurationAction.java:44)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
  at
  org.gradle.execution.DefaultTasksBuildExecutionAction.configure(DefaultTasksBuildExecutionAction.java:44)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
  at
  org.gradle.execution.ExcludedTaskFilteringBuildConfigurationAction.configure(ExcludedTaskFilteringBuildConfigurationAction.java:47)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.select(DefaultBuildConfigurationActionExecuter.java:36)
  at
  org.gradle.initialization.DefaultGradleLauncher$CalculateTaskGraph.run(DefaultGradleLauncher.java:265)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
  at
  org.gradle.initialization.DefaultGradleLauncher.constructTaskGraph(DefaultGradleLauncher.java:173)
  at
  org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:128)
  at
  org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:107)
  at
  org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
  at
  org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
  at
  org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
  at
  org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
  at
  org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
  at
  org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:53)
  at
  org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
  at
  org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
  at
  org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
  at
  org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
  at
  org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
  at
  org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
  at
  org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:45)
  at
  org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:29)
  at
  org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
  at
  org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
  at
  org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:71)
  at
  org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:45)
  at
  org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:51)
  at
  org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
  at
  org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
  at
  org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
  at
  org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
  at
  org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
  at
  org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
  at
  org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
  at
  org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
  at
  org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
  at
  org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:58)
  at
  org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:33)
  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:37)
  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:62)
  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:82)
  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.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
  at
  org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
  Caused by: java.lang.NullPointerException     at
  com.google.common.base.Preconditions.checkNotNull(Preconditions.java:782)
  at
  com.android.build.gradle.internal.ndk.NdkHandler.getPlatformVersion(NdkHandler.java:158)
  at
  com.android.build.gradle.internal.ndk.NdkHandler.supports64Bits(NdkHandler.java:331)
  at
  com.android.build.gradle.internal.ndk.NdkHandler.getSupportedAbis(NdkHandler.java:397)
  at
  com.android.build.gradle.tasks.ExternalNativeJsonGenerator.create(ExternalNativeJsonGenerator.java:609)
  at
  com.android.build.gradle.internal.TaskManager.createExternalNativeBuildJsonGenerators(TaskManager.java:1532)
  at
  com.android.build.gradle.internal.ApplicationTaskManager.lambda$createTasksForVariantScope$10(ApplicationTaskManager.java:205)
  at
  com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
  at
  com.android.build.gradle.internal.ApplicationTaskManager.createTasksForVariantScope(ApplicationTaskManager.java:200)
  at
  com.android.build.gradle.internal.VariantManager.createTasksForVariantData(VariantManager.java:523)
  at
  com.android.build.gradle.internal.VariantManager.lambda$createAndroidTasks$1(VariantManager.java:338)
  at
  com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
  at
  com.android.build.gradle.internal.VariantManager.createAndroidTasks(VariantManager.java:334)
  at
  com.android.build.gradle.BasePlugin.lambda$createAndroidTasks$5(BasePlugin.java:627)
  at
  com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
  at
  com.android.build.gradle.BasePlugin.createAndroidTasks(BasePlugin.java:622)
  at
  com.android.build.gradle.BasePlugin.lambda$null$3(BasePlugin.java:549)
  at
  com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
  at
  com.android.build.gradle.BasePlugin.lambda$createTasks$4(BasePlugin.java:545)
  at
  org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
  at
  org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
  at
  org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
  at
  org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
  at
  org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
  at
  org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
  at
  org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
  at
  org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
  at
  org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
  at
  org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
  at
  org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
  at com.sun.proxy.$Proxy23.afterEvaluate(Unknown Source)     at
  org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:75)
  ... 95 more

Get more help at https://help.gradle.org

BUILD FAILED in 3s

build.gradle(project)

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta2'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

build.gradle(app):

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.1'
    defaultConfig {
        applicationId 'org.tensorflow.demo'
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName '1.0'

        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
        ndk {
            abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
        }
    }

    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    compile 'org.tensorflow:tensorflow-android:1.3.0'
}
</code>```

Android Studio: 2.3.3

答: I know this is old but just ran into this and the File -> Project Structure -> SDK Location - Android NDK Location setting was missing.  Once I filled it in to the "Recommended" one it gradle sync'd fine</p>

Body:
Executing tasks: [clean]

Configuration on demand is an incubating feature. NDK is missing a
  "platforms" directory. If you are using NDK, verify the ndk.dir is set
  to a valid NDK directory.  It is currently set to
  /Users/ishandutta2007/Library/Android/sdk/ndk-bundle. If you are not
  using NDK, unset the NDK variable from ANDROID_NDK_HOME or
  local.properties to remove this warning.

Configuration 'compile' in project ':app' is deprecated. Use
  'implementation' instead.

FAILURE: Build failed with an exception.

What went wrong: A problem occurred configuring project ':app'.

java.lang.NullPointerException (no error message)

Try: Run with --info or --debug option to get more log output.

Exception is: org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'.  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:87)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:82)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:69)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:33)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:103)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
  at
  org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:49)
  at
  org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:651)
  at
  org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:133)
  at
  org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
  at
  org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:62)
  at
  org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:100)
  at
  org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:81)
  at
  org.gradle.execution.commandline.CommandLineTaskParser.parseTasks(CommandLineTaskParser.java:42)
  at
  org.gradle.execution.TaskNameResolvingBuildConfigurationAction.configure(TaskNameResolvingBuildConfigurationAction.java:44)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
  at
  org.gradle.execution.DefaultTasksBuildExecutionAction.configure(DefaultTasksBuildExecutionAction.java:44)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
  at
  org.gradle.execution.ExcludedTaskFilteringBuildConfigurationAction.configure(ExcludedTaskFilteringBuildConfigurationAction.java:47)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
  at
  org.gradle.execution.DefaultBuildConfigurationActionExecuter.select(DefaultBuildConfigurationActionExecuter.java:36)
  at
  org.gradle.initialization.DefaultGradleLauncher$CalculateTaskGraph.run(DefaultGradleLauncher.java:265)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
  at
  org.gradle.initialization.DefaultGradleLauncher.constructTaskGraph(DefaultGradleLauncher.java:173)
  at
  org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:128)
  at
  org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:107)
  at
  org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
  at
  org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
  at
  org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
  at
  org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
  at
  org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
  at
  org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:53)
  at
  org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
  at
  org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
  at
  org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
  at
  org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
  at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
  at
  org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
  at
  org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
  at
  org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:45)
  at
  org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:29)
  at
  org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
  at
  org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
  at
  org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:71)
  at
  org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:45)
  at
  org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:51)
  at
  org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
  at
  org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
  at
  org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
  at
  org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
  at
  org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
  at
  org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
  at
  org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
  at
  org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
  at
  org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
  at
  org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:58)
  at
  org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:33)
  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:37)
  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:62)
  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:82)
  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.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
  at
  org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
  Caused by: java.lang.NullPointerException     at
  com.google.common.base.Preconditions.checkNotNull(Preconditions.java:782)
  at
  com.android.build.gradle.internal.ndk.NdkHandler.getPlatformVersion(NdkHandler.java:158)
  at
  com.android.build.gradle.internal.ndk.NdkHandler.supports64Bits(NdkHandler.java:331)
  at
  com.android.build.gradle.internal.ndk.NdkHandler.getSupportedAbis(NdkHandler.java:397)
  at
  com.android.build.gradle.tasks.ExternalNativeJsonGenerator.create(ExternalNativeJsonGenerator.java:609)
  at
  com.android.build.gradle.internal.TaskManager.createExternalNativeBuildJsonGenerators(TaskManager.java:1532)
  at
  com.android.build.gradle.internal.ApplicationTaskManager.lambda$createTasksForVariantScope$10(ApplicationTaskManager.java:205)
  at
  com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
  at
  com.android.build.gradle.internal.ApplicationTaskManager.createTasksForVariantScope(ApplicationTaskManager.java:200)
  at
  com.android.build.gradle.internal.VariantManager.createTasksForVariantData(VariantManager.java:523)
  at
  com.android.build.gradle.internal.VariantManager.lambda$createAndroidTasks$1(VariantManager.java:338)
  at
  com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
  at
  com.android.build.gradle.internal.VariantManager.createAndroidTasks(VariantManager.java:334)
  at
  com.android.build.gradle.BasePlugin.lambda$createAndroidTasks$5(BasePlugin.java:627)
  at
  com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
  at
  com.android.build.gradle.BasePlugin.createAndroidTasks(BasePlugin.java:622)
  at
  com.android.build.gradle.BasePlugin.lambda$null$3(BasePlugin.java:549)
  at
  com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
  at
  com.android.build.gradle.BasePlugin.lambda$createTasks$4(BasePlugin.java:545)
  at
  org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
  at
  org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
  at
  org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
  at
  org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
  at
  org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
  at
  org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
  at
  org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
  at
  org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
  at
  org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
  at
  org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
  at
  org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
  at com.sun.proxy.$Proxy23.afterEvaluate(Unknown Source)     at
  org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:75)
  ... 95 more

Get more help at https://help.gradle.org

BUILD FAILED in 3s

build.gradle(project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta2'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(app):

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.1'
    defaultConfig {
        applicationId 'org.tensorflow.demo'
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName '1.0'

        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
        ndk {
            abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
        }
    }

    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    compile 'org.tensorflow:tensorflow-android:1.3.0'
}

Android Studio: 2.3.3


来源: stackexchange

问:
print JSON objects using perl
I am new to perl and i had written below snippet of code to get the JSON objects from the data. But the input data has both hashes and arrays, So how do i get those values for "id" which is an array ?

```<code>  use strict;
  use warnings;
  use Data::Dumper;
  use JSON

 my $data = '{"total":325,"id": [78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';

 print Dumper($data);
 my @hash_ref = from_json($data);

 foreach my $hash_scalar (@hash_ref) {

    foreach (keys %{$hash_scalar}) {
        print "$_ => ${$hash_scalar}{$_}\n";
        }
    }
</code>```

Output Getting

#

```<code>$VAR1 = '{"total":325,"id":
[78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';
id => ARRAY(0x2afee4c)
total => 325
</code>```

答:
The id is a key in the hash reference you get back, and you want to grab its value, which is an array reference. You can either keep that as a reference or grab its elements right away:

```<code>#!perl
use v5.24;
use JSON qw(from_json);

my $data = '{"total":325,"id": [78,234,737]}';

my $json = from_json($data);

# get the hash key to get the hash value, which is an array reference
my $ids_array_ref = $json->{id};

# OR, use the postfix dereference to get the ids as a normal list
my @ids_array = $json->{id}->@*;

# OR, use the older circumfix notation (before Perl v5.24). These are all
# the same:
my @ids_array = @{ $json->{id} };
my @ids_array = @{ $ids_array_ref };
my @ids_array = @$ids_array_ref;
</code>```

For example:

```<code>#!perl
use v5.24;
use JSON qw(from_json);

my $data = '{"total":325,"id": [78,234,737]}';

my $json = from_json($data);

foreach my $id ( $json->{id}->@* ) {
    say "Got id $id";
    }
</code>```

This outputs:

```<code>Got id 78
Got id 234
Got id 737
</code>```

But, you have to handle the other hash value types too. To decide how to print something, you have to check if it's a reference and what sort of reference it is (I ignore the other sorts here):

```<code>#!perl
use v5.24;
use JSON qw(from_json);

my $data = '{"total":325,"id": [78,234,737]}';

my $json = from_json($data);

foreach my $key ( keys $json->%* ) {
    print "$key: ";
    if( ref $json->{$key} eq 'ARRAY' ) {
        say join ' ', $json->{$key}->@*;
        }
    elsif( ref $json->{$key} ) { # all other reference types
        warn "I don't handle this yet"
        }
    else {
        say $json->{$key};
        }
    }
</code>```

But, you might have deeper levels of nesting, so you'd need to think about that too if you want to output everything. If I know what keys I want, I don't try to go through everything in a general way. I go directly to want I want:

```<code>#!perl
use v5.24;
use JSON qw(from_json);

my $data = '{"total":325,"id": [78,234,737]}';

my $json = from_json($data);

say "id: ", join ' ', $json->{id}->@*;
say "total: ", $json->{total};
</code>```

Your original code was doubly complicated. The result of from_json is the reference that represents the JSON data structure. That's a JSON object, which is what Perl calls a hash, so you get a hash reference back.

```<code>my $hash_ref = from_json( $data );
</code>```

Your example almost worked because you got an array of one element, which is that hash reference. The other foreach then iterates over that one element. Get rid of that outer array and you get rid of the outer loop.

We cover references and data structures in Intermediate Perl, although the perldsc is good too. We have a long examples of deeply-nested and recursive data structures.

If you're new, you may want to start with Learning Perl, though.

ContentLicense: CC BY-SA 4.0

Title: print JSON objects using perl

Body:
I am new to perl and i had written below snippet of code to get the JSON objects from the data. But the input data has both hashes and arrays, So how do i get those values for "id" which is an array ?

  use strict;
  use warnings;
  use Data::Dumper;
  use JSON

 my $data = '{"total":325,"id": [78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';

 print Dumper($data);
 my @hash_ref = from_json($data);

 foreach my $hash_scalar (@hash_ref) {

    foreach (keys %{$hash_scalar}) {
        print "$_ => ${$hash_scalar}{$_}\n";
        }
    }

Output Getting

#

$VAR1 = '{"total":325,"id":
[78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';
id => ARRAY(0x2afee4c)
total => 325

Body:
The id is a key in the hash reference you get back, and you want to grab its value, which is an array reference. You can either keep that as a reference or grab its elements right away:

#!perl
use v5.24;
use JSON qw(from_json);

my $data = '{"total":325,"id": [78,234,737]}';

my $json = from_json($data);

# get the hash key to get the hash value, which is an array reference
my $ids_array_ref = $json->{id};

# OR, use the postfix dereference to get the ids as a normal list
my @ids_array = $json->{id}->@*;

# OR, use the older circumfix notation (before Perl v5.24). These are all
# the same:
my @ids_array = @{ $json->{id} };
my @ids_array = @{ $ids_array_ref };
my @ids_array = @$ids_array_ref;

For example:

#!perl
use v5.24;
use JSON qw(from_json);

my $data = '{"total":325,"id": [78,234,737]}';

my $json = from_json($data);

foreach my $id ( $json->{id}->@* ) {
    say "Got id $id";
    }

This outputs:

Got id 78
Got id 234
Got id 737

But, you have to handle the other hash value types too. To decide how to print something, you have to check if it's a reference and what sort of reference it is (I ignore the other sorts here):

#!perl
use v5.24;
use JSON qw(from_json);

my $data = '{"total":325,"id": [78,234,737]}';

my $json = from_json($data);

foreach my $key ( keys $json->%* ) {
    print "$key: ";
    if( ref $json->{$key} eq 'ARRAY' ) {
        say join ' ', $json->{$key}->@*;
        }
    elsif( ref $json->{$key} ) { # all other reference types
        warn "I don't handle this yet"
        }
    else {
        say $json->{$key};
        }
    }

But, you might have deeper levels of nesting, so you'd need to think about that too if you want to output everything. If I know what keys I want, I don't try to go through everything in a general way. I go directly to want I want:

#!perl
use v5.24;
use JSON qw(from_json);

my $data = '{"total":325,"id": [78,234,737]}';

my $json = from_json($data);

say "id: ", join ' ', $json->{id}->@*;
say "total: ", $json->{total};

Your original code was doubly complicated. The result of from_json is the reference that represents the JSON data structure. That's a JSON object, which is what Perl calls a hash, so you get a hash reference back.

my $hash_ref = from_json( $data );

Your example almost worked because you got an array of one element, which is that hash reference. The other foreach then iterates over that one element. Get rid of that outer array and you get rid of the outer loop.

We cover references and data structures in Intermediate Perl, although the perldsc is good too. We have a long examples of deeply-nested and recursive data structures.

If you're new, you may want to start with Learning Perl, though.


问:
Git wrongly mark a file as deleted instead of rewritten
I'm doing several refactors on a project. So sometimes I need to rename the file extension, for example index.js -> index.ts, and change many lines on this file.

Because that git wrongly mark index.js as deleted and index.ts as a new file, that could be bad on code review and logs.

Is there some way to explicitly say to git "hey, I renamed index.js to index.ts"?

Edit

The approach using git add / git rm / git mv didn't work, because git still say that I created a new file and removed other.

Also I should not use two commits to that (one for rename and one for update its content), because the first commit will be broken, since the build steps for a .js file is different than a .ts file

答:
Is there some way to explicitly say to git "hey, I renamed index.js to index.ts"?

No.

That's all there is to it.  Git does not store changes to files.  Git stores snapshots of files.  You had, in snapshot X, a file named index.js.  You have, in snapshot Y, a file named index.ts.

When comparing snapshot X to snapshot Y, you can ask Git to detect renames.  The detection is based on two facts:

In snapshot X, there was a file named index.js and in snapshot Y, that file does not exist, but a new file named index.ts does exist; so these two names can be put into a list of candidates for rename detection.

Now that the list of candidates for rename detection is filled with all file names that vanished from the left (X) commit and appeared in the right (Y) commit, Git will compare each pair of files.  If the content of those two files is sufficiently similar, Git will temporarily pair-up that pair, remembering this similarity index value.  Having run through all possible pairings, Git will take the pairing that has the best similarity index, and call that file "renamed".

Whenever you have Git compare snapshots X and Y—for any commit hashes X and Y, really—you get to tell Git:

Do, or do not, use the rename detector;

If using the rename detector, what's the minimum similarity threshold to temporarily pair-up files?

With the git diff command, the rename detector defaults to off before Git 2.9 and on in Git 2.9 and later.  The similarity threshold value defaults to "50% similar" in all versions of Git.  Use the -M flag to turn the detector on and set the similarity threshold.

When using other Git commands, other flags and arguments may allow you to enable rename detection and set the threshold—or, in some cases, not so much.  For instance, git log --follow turns on the rename detector but limits it to one file name only and does not let you set the threshold.

The git status command used to always enable rename detection and set the threshold to 50%.  It now obeys git config settings for enabling or disabling rename detection, but still has no way to set the threshold.

Again, this rename detection occurs when you compare the two commits.  The commits themselves are just snapshots, of all of your files.  Two different git diff commands, with different rename detection setups, will show different sets of operations that result in replacing the first commit with the second one.  The git diff command does not show what someone actually did.  It shows, instead, some sequence of operations that will produce the same result.


问:
Gurobi Python: How do I do element-wise multiplication on MVar?
How do I do element-wise multiplication in the constraint for a quadratic program?

I have the following implementation

```<code>import gurobipy as gp

m = gp.model("model")
x = m.addMVar(shape=(10), name="x")
y = m.addMVar(shape=(5), name="y")
A = np.random.rand(5, 10)

m.addConstr(A @ x - (y*y) <= A[:,0], name="const")

m.setObjective(x.sum() - (y*y).sum()), GRB.MAXIMIZE)
</code>```

The (y*y) does not work as it does in numpy for element-wise multiplication, and throws the following error.

```<code>Traceback (most recent call last):
  File "/home/usr/test.py", line 21, in solve_QP_gurobi
    m.addConstr(A @ x - (y*y) <= A[:,0], name="const")
  File "mvar.pxi", line 76, in gurobipy.MVar.__mul__
  File "mvar.pxi", line 152, in gurobipy.MVar.scalar_mult
TypeError: float() argument must be a string or a number, not 'MVar'

</code>```

答: Since your "y" is a scalar, you can do y @ y</p>

Body:
How do I do element-wise multiplication in the constraint for a quadratic program?

I have the following implementation

import gurobipy as gp

m = gp.model("model")
x = m.addMVar(shape=(10), name="x")
y = m.addMVar(shape=(5), name="y")
A = np.random.rand(5, 10)

m.addConstr(A @ x - (y*y) <= A[:,0], name="const")

m.setObjective(x.sum() - (y*y).sum()), GRB.MAXIMIZE)

The (y*y) does not work as it does in numpy for element-wise multiplication, and throws the following error.

Traceback (most recent call last):
  File "/home/usr/test.py", line 21, in solve_QP_gurobi
    m.addConstr(A @ x - (y*y) <= A[:,0], name="const")
  File "mvar.pxi", line 76, in gurobipy.MVar.__mul__
  File "mvar.pxi", line 152, in gurobipy.MVar.scalar_mult
TypeError: float() argument must be a string or a number, not 'MVar'


问:
multiple calls to template versus calls inside ng-repeat
I'm working on migrating a HUGE angular form to a new layout (can't change technologies). The current version is drawn from a huge nasty javascript array that gets fed into an ng-repeat and calls various templates. The templates aren't changing in the new form except for some new css stuff. The new/old path that angular follows to generate the form html is controlled by a server side feature toggle (not really import to this question).

For the form, the only difference now is I'm not in a ng-repeat loop and instead I'm doing a ng-include multiple times in a more well defined layout.

The problem I'm having is the values being passed into each ng-include elements only get the ng-init values of the last call on the page, see example below..

```<code><!-- begin template definitions -->
<script type="text/ng-template" id="/templates/currency.html">
    <ul class="input-field-layout">
        <li>
            <input type="text" class="form-control {{field.additionalClasses}}" id="input_{{field.name}}"
                   ng-class="{{field.ngClass}}"
                   ng-model="$ctrl.contract[field.name]"
                   ng-disabled="field.disabled && !$ctrl.overrideSelected"
                   ng-change="field.onChange()"
                   ng-blur="field.onBlur()"
                   ng-readonly="field.readOnly"
            />
            <span class="input-group-btn" ng-if="field.showCalculator && field.canCalculate()">
                <button type="button" class="btn btn-default btn-sm"
                        id="calc_{{field.name}}"
                        ng-click="field.calculate()"
                        tabindex="-1"
                >
                    <i class="glyphicon glyphicon-flash"></i>
                </button>
            </span>
        </li>
        <li class="input-description-text" ng-if="field.descriptionText">
            <span>{{field.descriptionText}}</span>
        </li>
    </ul>
</script>
<!-- end template definitions -->

<!-- begin snippet for old form -->
<div ng-repeat="fieldGroup in $ctrl.fieldGroups">
    <div class="clearfix" ng-if="fieldGroup.clearFixClass == true"></div>
    <div>
        <h3>{{fieldGroup.name}}</h3>
        <hr>
        <div class="form-group form-group-sm"
             ng-repeat="field in fieldGroup.fields">
            <label class="control-label {{field.additionalClasses}}" for="input_{{field.name}}">{{field.field_label}}</label>
            <div ng-include="'/templates/'+field.type+'.html'"></div>
        </div>
    </div>
</div>
<!-- begin snippet for old form -->

<!-- being snippet for new form -->
<div class="flexRow">
    <label class="boldInput" for="input_adjustment">Adjustment</label>
    <div
        ng-init="
        field = {
            name: 'adjustment'
        }
        "
        ng-include="'/templates/currency.html'">
    </div>
</div>
<div class="flexRow">
    <label class="boldInput" for="input_total_due">Total</label>
    <div
        ng-init="
        field = {
            name: 'total',
            descriptionText: 'blah blah blah',
            disabled: $ctrl.disabledCheck.disabled_fields,
            showCalculator: true,
            calculate: $ctrl.calculateTotal,
            canCalculate: $ctrl.canCalculateTotal,
            additionalClasses: 'boldInput'
        }
        "
        ng-include="'/templates/currency.html'">
    </div>
</div>
<!-- end snippet for new form -->
</code>```

The old logic generates what you'd expect, but the new logic generates the following. Notice how both fields have the id input_total and other attributes/values of the final call to the template on the page.

```<code><div class="flexRow">
    <label class="boldInput" for="input_adjustment">Adjustment</label>
    <ul class="input-field-layout ng-scope">
        <li>
            <input type="text" class="form-control boldInput ng-empty ng-touched" id="input_total" ng-class="" ng-model="$ctrl.contract[field.name]" ng-disabled="field.disabled">
            <!-- ngIf: field.showCalculator && field.canCalculate() -->
        </li>
        <!-- ngIf: field.descriptionText --><li class="input-description-text ng-scope" ng-if="field.descriptionText">
            <span class="ng-binding">blah blah blah</span>
        </li><!-- end ngIf: field.descriptionText -->
    </ul>
</div>
<div class="flexRow">
    <label class="boldInput" for="input_total">Total</label>
    <ul class="input-field-layout ng-scope">
        <li>
            <input type="text" class="form-control boldInput ng-empty ng-touched" id="input_total" ng-class="" ng-model="$ctrl.contract[field.name]" ng-disabled="field.disabled">
            <!-- i've removed the calculator html for sake of space in this question -->
        </li>
        <!-- ngIf: field.descriptionText --><li class="input-description-text ng-scope" ng-if="field.descriptionText">
            <span class="ng-binding">blah blah blah</span>
        </li><!-- end ngIf: field.descriptionText -->
    </ul>
</div>
</code>```

I feel like ng-init is not what I should be using to pass-in values for field to the templates in the new form logic, but Uncle Google is failing me.

What should I be using instead of ng-init or how does the scope(?) change inside an ng-repeat versus multiple calls to the templates?

答:
I just found this post: Losing scope when using ng-include

It seems if you add ng-if="true" to the ng-include it causes angular create a new scope!

This is probably taking advantage of a caveat in angular's ng-if but it lets me move forward.

```<code><!-- being modified snippet for new form -->
<div class="flexRow">
    <label class="boldInput" for="input_adjustment">Adjustment</label>
    <div
        ng-if="true"
        ng-init="
        field = {
            name: 'adjustment'
        }
        "
        ng-include="'/templates/currency.html'">
    </div>
</div>
<div class="flexRow">
    <label class="boldInput" for="input_total_due">Total</label>
    <div
        ng-if="true"
        ng-init="
        field = {
            name: 'total',
            descriptionText: 'blah blah blah',
            disabled: $ctrl.disabledCheck.disabled_fields,
            showCalculator: true,
            calculate: $ctrl.calculateTotal,
            canCalculate: $ctrl.canCalculateTotal,
            additionalClasses: 'boldInput'
        }
        "
        ng-include="'/templates/currency.html'">
    </div>
</div>
<!-- end modified snippet for new form -->
</code>```

Body:
I'm working on migrating a HUGE angular form to a new layout (can't change technologies). The current version is drawn from a huge nasty javascript array that gets fed into an ng-repeat and calls various templates. The templates aren't changing in the new form except for some new css stuff. The new/old path that angular follows to generate the form html is controlled by a server side feature toggle (not really import to this question).

For the form, the only difference now is I'm not in a ng-repeat loop and instead I'm doing a ng-include multiple times in a more well defined layout.

The problem I'm having is the values being passed into each ng-include elements only get the ng-init values of the last call on the page, see example below..

{{fieldGroup.name}}

            {{field.field_label}}

    Adjustment

    Total

The old logic generates what you'd expect, but the new logic generates the following. Notice how both fields have the id input_total and other attributes/values of the final call to the template on the page.

    Adjustment

            <input type="text" class="form-control boldInput ng-empty ng-touched" id="input_total" ng-class="" ng-model="$ctrl.contract[field.name]" ng-disabled="field.disabled">

            blah blah blah

    Total

            <input type="text" class="form-control boldInput ng-empty ng-touched" id="input_total" ng-class="" ng-model="$ctrl.contract[field.name]" ng-disabled="field.disabled">

            blah blah blah

I feel like ng-init is not what I should be using to pass-in values for field to the templates in the new form logic, but Uncle Google is failing me.

What should I be using instead of ng-init or how does the scope(?) change inside an ng-repeat versus multiple calls to the templates?

Body:
I just found this post: Losing scope when using ng-include

It seems if you add ng-if="true" to the ng-include it causes angular create a new scope!

This is probably taking advantage of a caveat in angular's ng-if but it lets me move forward.

<!-- being modified snippet for new form -->
<div class="flexRow">
    <label class="boldInput" for="input_adjustment">Adjustment</label>
    <div
        ng-if="true"
        ng-init="
        field = {
            name: 'adjustment'
        }
        "
        ng-include="'/templates/currency.html'">
    </div>
</div>
<div class="flexRow">
    <label class="boldInput" for="input_total_due">Total</label>
    <div
        ng-if="true"
        ng-init="
        field = {
            name: 'total',
            descriptionText: 'blah blah blah',
            disabled: $ctrl.disabledCheck.disabled_fields,
            showCalculator: true,
            calculate: $ctrl.calculateTotal,
            canCalculate: $ctrl.canCalculateTotal,
            additionalClasses: 'boldInput'
        }
        "
        ng-include="'/templates/currency.html'">
    </div>
</div>
<!-- end modified snippet for new form -->


问:
cakePHP - 404- page not found error, when deploying on a different machine
I'm trying to deploy a cakephp application into my peers system and i get 404 error, for all requests. This is not cakephp 404 error, but a normal webserver 404 page not found error. :( . We both use MAC OS 10.6. The same code works on my machine and on the production system. I have followed the steps to deploy on his machine. I'm using cakephp advanced installation, i.e, webroot contain only index.php, css, js,etc. The APP folder and CAKE folder is located elsewhere.

uncommented the line "LoadModule php5_module...." in /etc/apache2/httpd.conf

Changed to AllowOverride All to the Directory - "Library/WebServer/Documents" in /etc/apache2/httpd.conf

uncommented and set date.timezone in /etc/php.ini

Copied the webroot contents to "Library/WebServer/Documents" and modified index.php to adapt to his machine (setup 3 relevant paths to the CORE, APP and CAKE folder)

made sure the DB connection is good.

For debugging purpose, Modified core.php and set Configure::write('debug',3);

The homepage get data from an AJAX call. WHen i goto http://localhost, the header and footer contents from the layouts/default.ctp are rendered, but the ajax call which is for example http://localhost/posts/showmyposts gets a 404 (Not Found) error. If I goto to other URLs like http://localhost/users/login, I get the normal webserver 404 error.

Not Found

The requested URL /users/login/ was not found on this server.

In my apache error log, i get the error as

[Mon May 16 16:19:48 2011] [error] [client ::1] File does not exist: /Library/WebServer/Documents/users, referer: http://localhost/
Is my cakephp installation correct ?

答:
Sounds like an issue with mod_rewrite not working on that machine. What happens when you try to run a default Cake install? Does it load the CSS and all?

Is there a .htaccess file in your app directory (and in your webroot directory)?

Do you have FollowSymLinks turned on in your Apache config files?

ContentLicense: CC BY-SA 3.0


问:
Parsing multiple JSON files with Swift using one Decodable Struct
I have several JSON feeds, for this example let's these two (A & B). Both have different structures but both have an array of structures identifying the elements I'd like to parse, the bike stations.

I'd like to avoid creating a different class for each JSON feed I have to parse and if possible parse the underlying array of structures with the same Decodable struct. The definition of my model is as follows,

```<code>struct Places: Decodable {
    var name: String
    let lat: Double
    let lng: Double
    let id: String
    let bikes: Int

    enum CodingKeys: String, CodingKey {
        case name
        case lat = "latitude"
        case lng = "longitude"
        case id
        case bikes = "free_bikes"
    }
}
</code>```

This model would only serve for one JSON feed and for each I'd have to create different CodingKeys. This is also a problem because the intermediate elements differ from feed to feed.

What I currently have is different parsers used on each feed. My app uses the array of Places to add pins on a map so the defined struct has to be the same for every feed that I parse. This is not a scalable solution for me and I'd like to ask if the following is correct,

Can I have only one parser that fit all my needs?

Can I have only one parser with different root elements and the same Places struct in the end?

Can I build a parser that only accesses the intermediate elements defined in the Places structure and "forget" about the top level differences between the feeds

I asked a similar question here only for the inner elements. While that is still true I now have problems parsing all the documents only to get the array of Places.

答:
One thing right off the top, I would suggest rename your Places struct to Place (singular). I would also suggest using the full names for latitude and longitude.

On to the specific questions:

I think 1 & 2 would be possible, but you might end up with much less maintainable code.

Yes. Doable with the caveat above.

Yes. Challenging, because in the NextBike & CitiBike examples you provided, the IDs are of different types (String id in CitiBike and Int uid), so would need to be mapped.

No, I don't think so, because you'll still need to do the type mapping mentioned above in 2.

For maintainability, I would suggest creating Decodable structs/classes for each of the types of feeds with (possibly) embedded structs/classes to support hierarchy and then provide a map to [Place]. You can use a protocol to enforce compliance.

protocol PlacesProviding {
    var places: [Place] { get }
}

struct Place: Decodable {
    var name: String
    let latitude: Double
    let longitude: Double
    let id: String
    let bikes: Int
```

<p>Using your NextBike & CitiBike examples, you might want to be able to do something like:</p>

<pre class="lang-swift prettyprint-override"><code>let decoder = JSONDecoder()
let nyc = decoder.decode(NYCitiBike.self, from: citiBikeNYC)
let nb = decoder.decode(NextBike.self, from: nextBike)

var places = [Place]()
places.append(contentsOf: nb.places)
places.append(contentsOf: nyc.places)
print(places.count)
</code>```

Here are example Decodable PlaceProviding objects that support this. The structure of these make very clear the expected structure of the associated feed and make it easy to surface additional properties from a feed. This improves maintainability, especially in the longer term.

struct NYCitiBike: Decodable, PlacesProviding {

    struct Network: Decodable {
        let stations: [Station]
    }

    struct Station: Decodable {
        var name: String
        let latitude: Double
        let longitude: Double
        let id: String
        let bikes: Int

        enum CodingKeys: String, CodingKey {
            case name
            case latitude
            case longitude
            case id
            case bikes = "free_bikes"
        }

    }

    let network: Network

    var stations: [Station] { return network.stations }
    var places: [Place] {
        stations.map { Place(name: $0.name, latitude: $0.latitude, longitude: $0.longitude, id: $0.id, bikes: $0.bikes) }
    }
```

<pre class="lang-swift prettyprint-override"><code>struct NextBike: Decodable, PlacesProviding {

    struct Country: Decodable {
        let name: String
        let cities: [City]
    }

    struct City: Decodable {
        let name: String
        let places: [Station]
    }

    struct Station: Decodable {
        let name: String
        let lat: Double
        let lng: Double
        let uid: Int
        let bikes: Int
    }

    let countries: [Country]
    var stations: [Station] {
        return countries
            .flatMap { $0.cities }
            .flatMap { $0.places }
    }
    var places: [Place] {
        stations.map { Place(name: $0.name, latitude: $0.lat, longitude: $0.lng, id: String($0.uid), bikes: $0.bikes) }
    }
</code>```

Body:
I have several JSON feeds, for this example let's these two (A & B). Both have different structures but both have an array of structures identifying the elements I'd like to parse, the bike stations.

I'd like to avoid creating a different class for each JSON feed I have to parse and if possible parse the underlying array of structures with the same Decodable struct. The definition of my model is as follows,

struct Places: Decodable {
    var name: String
    let lat: Double
    let lng: Double
    let id: String
    let bikes: Int

    enum CodingKeys: String, CodingKey {
        case name
        case lat = "latitude"
        case lng = "longitude"
        case id
        case bikes = "free_bikes"
    }
}

This model would only serve for one JSON feed and for each I'd have to create different CodingKeys. This is also a problem because the intermediate elements differ from feed to feed.

What I currently have is different parsers used on each feed. My app uses the array of Places to add pins on a map so the defined struct has to be the same for every feed that I parse. This is not a scalable solution for me and I'd like to ask if the following is correct,

Can I have only one parser that fit all my needs?

Can I have only one parser with different root elements and the same Places struct in the end?

Can I build a parser that only accesses the intermediate elements defined in the Places structure and "forget" about the top level differences between the feeds

I asked a similar question here only for the inner elements. While that is still true I now have problems parsing all the documents only to get the array of Places.

Body:
One thing right off the top, I would suggest rename your Places struct to Place (singular). I would also suggest using the full names for latitude and longitude.

On to the specific questions:

I think 1 & 2 would be possible, but you might end up with much less maintainable code.

Yes. Doable with the caveat above.

Yes. Challenging, because in the NextBike & CitiBike examples you provided, the IDs are of different types (String id in CitiBike and Int uid), so would need to be mapped.

No, I don't think so, because you'll still need to do the type mapping mentioned above in 2.

For maintainability, I would suggest creating Decodable structs/classes for each of the types of feeds with (possibly) embedded structs/classes to support hierarchy and then provide a map to [Place]. You can use a protocol to enforce compliance.

protocol PlacesProviding {
    var places: [Place] { get }
}

struct Place: Decodable {
    var name: String
    let latitude: Double
    let longitude: Double
    let id: String
    let bikes: Int

Using your NextBike & CitiBike examples, you might want to be able to do something like:

let decoder = JSONDecoder()
let nyc = decoder.decode(NYCitiBike.self, from: citiBikeNYC)
let nb = decoder.decode(NextBike.self, from: nextBike)

var places = [Place]()
places.append(contentsOf: nb.places)
places.append(contentsOf: nyc.places)
print(places.count)

Here are example Decodable PlaceProviding objects that support this. The structure of these make very clear the expected structure of the associated feed and make it easy to surface additional properties from a feed. This improves maintainability, especially in the longer term.

struct NYCitiBike: Decodable, PlacesProviding {

    struct Network: Decodable {
        let stations: [Station]
    }

    struct Station: Decodable {
        var name: String
        let latitude: Double
        let longitude: Double
        let id: String
        let bikes: Int

        enum CodingKeys: String, CodingKey {
            case name
            case latitude
            case longitude
            case id
            case bikes = "free_bikes"
        }

    }

    let network: Network

    var stations: [Station] { return network.stations }
    var places: [Place] {
        stations.map { Place(name: $0.name, latitude: $0.latitude, longitude: $0.longitude, id: $0.id, bikes: $0.bikes) }
    }

struct NextBike: Decodable, PlacesProviding {

    struct Country: Decodable {
        let name: String
        let cities: [City]
    }

    struct City: Decodable {
        let name: String
        let places: [Station]
    }

    struct Station: Decodable {
        let name: String
        let lat: Double
        let lng: Double
        let uid: Int
        let bikes: Int
    }

    let countries: [Country]
    var stations: [Station] {
        return countries
            .flatMap { $0.cities }
            .flatMap { $0.places }
    }
    var places: [Place] {
        stations.map { Place(name: $0.name, latitude: $0.lat, longitude: $0.lng, id: String($0.uid), bikes: $0.bikes) }
    }


问:
Difference between InnoDB and MyISAM?

Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

```<code>$q = ("SELECT * ... );
$r = mysql_query($q);
</code>```

答: My be worthwhile to consider whether you'll be using mostly SELECT queries or INSERT / UPDATE, since InnoDB supports row-level locking (better for insert / update), but MyISAM uses table-level locking (faster if you'll use just select).  See this from ref manual for more info.</p>

Title: Difference between InnoDB and MyISAM?

Body:
Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

$q = ("SELECT * ... );
$r = mysql_query($q);


问:
Save database entrys from array in nodejs
I scrape data from a website and save them to an array. I would like to save this array threw a mysql database.

I am using nodejs as backend framework, mysql database and typeorm as database framework.

This is the code from my express webserver where I want to pass the elements via for-loop threw the database:

```<code>app.get('/dev', async (req, res) => {
console.log(req.body)
const channelData = await scrape.scrapeChannel()
console.log(channelData.namearray.length);

for (i = 0; i < channelData.namearray.length; i++) {
 const creators = await database.insertCreator(channelData.namearray[i], channelData.datearray[i], channelData.imgarray[i])
    res.send(creators)
}});
</code>```

This is my code for the database connection:

```<code>async function insertCreator(training, date, img) {

const connection = await getConnection();

// create
const creator = new Creator();
creator.img = img;
creator.training = training;
creator.date = date;

// save
const creatorRepo = connection.getRepository(Creator);
const res = await creatorRepo.save(creator);
console.log('saved', res);

// return new list
const allCreators = await creatorRepo.find();
connection.close();
return allCreators;}
</code>```

If I run the code I get the following error message:

AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.

It seems like I don't close my database connection. But I don't get where and why.

Hope you can help me.

答:
You are opening and closing connection for each inserts. You are getting this error because new connection attempt made before old connection get closed.

Try to open connection once, pass the connection to insert function, perform all inserts and finally close connection.

```<code>//Pseudo code here
connection = getConnection()
for loop {
  insertCreator(connection, params)
}
connection.close()
</code>```

If this is part of production code, I would recommend to use connectionPool for each requests, so that all request will be served correctly.

Body:
I scrape data from a website and save them to an array. I would like to save this array threw a mysql database.

I am using nodejs as backend framework, mysql database and typeorm as database framework.

This is the code from my express webserver where I want to pass the elements via for-loop threw the database:

app.get('/dev', async (req, res) => {
console.log(req.body)
const channelData = await scrape.scrapeChannel()
console.log(channelData.namearray.length);

for (i = 0; i < channelData.namearray.length; i++) {
 const creators = await database.insertCreator(channelData.namearray[i], channelData.datearray[i], channelData.imgarray[i])
    res.send(creators)
}});

This is my code for the database connection:

async function insertCreator(training, date, img) {

const connection = await getConnection();

// create
const creator = new Creator();
creator.img = img;
creator.training = training;
creator.date = date;

// save
const creatorRepo = connection.getRepository(Creator);
const res = await creatorRepo.save(creator);
console.log('saved', res);

// return new list
const allCreators = await creatorRepo.find();
connection.close();
return allCreators;}

If I run the code I get the following error message:

AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.

It seems like I don't close my database connection. But I don't get where and why.

Hope you can help me.

Body:
You are opening and closing connection for each inserts. You are getting this error because new connection attempt made before old connection get closed.

Try to open connection once, pass the connection to insert function, perform all inserts and finally close connection.

//Pseudo code here
connection = getConnection()
for loop {
  insertCreator(connection, params)
}
connection.close()

If this is part of production code, I would recommend to use connectionPool for each requests, so that all request will be served correctly.


问:
Runnable Jar File doesn't load resources
In IntelliJ I can run:

```<code>ImageIcon icon = new ImageIcon("src/de/therealjan/tools/pictures/pic.png");
</code>```

But in a runnable JAR File that won't work.
I already tried "/pictures/pic.png" but that doesn't work too.

Any ideas?

答:
you should add the image in your classpath or a directory in your classpath
and then load your image like this:</p>

```<code>ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("src/de/therealjan/tools/pictures/pic.png");
ImageIcon icon = new ImageIcon(resource);
</code>```

Body:
In IntelliJ I can run:

ImageIcon icon = new ImageIcon("src/de/therealjan/tools/pictures/pic.png");

But in a runnable JAR File that won't work.
I already tried "/pictures/pic.png" but that doesn't work too.

Any ideas?

Body:
you should add the image in your classpath or a directory in your classpath
and then load your image like this:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("src/de/therealjan/tools/pictures/pic.png");
ImageIcon icon = new ImageIcon(resource);


问:
Use docker without registry for gitlab-ci
My school has a personal gitlab setup, but it doesn't have a registry setup for docker images.

What I want to do is run my pipeline with docker, so that I can build, test etc in a docker environment.

Right now i am trying random stuff because I don't know what I am doing. This is what I have now:

Gitlab-ci:

```<code>image: docker:latest

services:
  - docker:dind

before_script:
  - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY

build-master:
  stage: build
  script:
    - docker build --pull -t "$CI_REGISTRY_IMAGE" .
    - docker push "$CI_REGISTRY_IMAGE"

build:
  stage: build
  script:
    - docker build --pull -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG" .
    - docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG"
</code>```

My secret variables on gitlab:

My error message in the pipeline:

Something else I tried uses a gitlab repo. This uses the docker image for ros correctly, but in my application I also use opencv, so I want to add more to the docker image. If i know how to do that in the example below, thats also an option. On top of this, in the example below i can't run tests.

Gitlab-ci:

```<code>image: ros:kinetic-ros-core

stages:
- build

variables:
  ROS_PACKAGES_TO_INSTALL: ""
  USE_ROSDEP: "true"

cache:
  paths:
    - ccache/

before_script:
 - git clone https://gitlab.com/VictorLamoine/ros_gitlab_ci.git
 - source ros_gitlab_ci/gitlab-ci.bash

catkin_make:
  stage: build
  script:
    - catkin_make

catkin_build:
  stage: build
  script:
    - catkin build --summarize --no-status --force-color
</code>```

As I said I have tried many things, this is just the latest thing I have tried. How can I run my runners and gitlab-ci with docker without a gitlab registry?

答:
Just use it withouth registry.
You just need to insert this to gitlab runner config file:

pull_policy = "if-not-present"

Thats enough, and remove commands like:

docker push ...

docker pull ...

Or even insert "|| true" at the end of the push pull command if you want to keep push pull in case, like this:

docker pull ... || true;

Which keeps your code to continue if command fail.
Just dont forget that : pull_policy = "if-not-present" , which allow You to run docker image withouth pull and push.
As image is in case if mussing builded, this works.

example:

```<code>[[runners]]
  name = "Runner name"
  url = ...
  ...
  executor = "docker"
  [runners.docker]
    image = ...
    pull_policy = "if-not-present"
    ...
</code>```

Body:
My school has a personal gitlab setup, but it doesn't have a registry setup for docker images.

What I want to do is run my pipeline with docker, so that I can build, test etc in a docker environment.

Right now i am trying random stuff because I don't know what I am doing. This is what I have now:

Gitlab-ci:

image: docker:latest

services:
  - docker:dind

before_script:
  - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY

build-master:
  stage: build
  script:
    - docker build --pull -t "$CI_REGISTRY_IMAGE" .
    - docker push "$CI_REGISTRY_IMAGE"

build:
  stage: build
  script:
    - docker build --pull -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG" .
    - docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG"

My secret variables on gitlab:

My error message in the pipeline:

Something else I tried uses a gitlab repo. This uses the docker image for ros correctly, but in my application I also use opencv, so I want to add more to the docker image. If i know how to do that in the example below, thats also an option. On top of this, in the example below i can't run tests.

Gitlab-ci:

image: ros:kinetic-ros-core

stages:
- build

variables:
  ROS_PACKAGES_TO_INSTALL: ""
  USE_ROSDEP: "true"

cache:
  paths:
    - ccache/

before_script:
 - git clone https://gitlab.com/VictorLamoine/ros_gitlab_ci.git
 - source ros_gitlab_ci/gitlab-ci.bash

catkin_make:
  stage: build
  script:
    - catkin_make

catkin_build:
  stage: build
  script:
    - catkin build --summarize --no-status --force-color

As I said I have tried many things, this is just the latest thing I have tried. How can I run my runners and gitlab-ci with docker without a gitlab registry?

Body:
Just use it withouth registry.
You just need to insert this to gitlab runner config file:

pull_policy = "if-not-present"

Thats enough, and remove commands like:

docker push ...

docker pull ...

Or even insert "|| true" at the end of the push pull command if you want to keep push pull in case, like this:

docker pull ... || true;

Which keeps your code to continue if command fail.
Just dont forget that : pull_policy = "if-not-present" , which allow You to run docker image withouth pull and push.
As image is in case if mussing builded, this works.

example:

[[runners]]
  name = "Runner name"
  url = ...
  ...
  executor = "docker"
  [runners.docker]
    image = ...
    pull_policy = "if-not-present"
    ...


问:
How can I remove the legend title in ggplot2?
I have a question concerning the legend in ggplot2.

Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:

```<code>carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
</code>```

I make a simple bar plot:

```<code>require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
</code>```

My question is: is there a way to remove the title ('Type') from the legend?

Thanks!

答:
You've got two good options already, so here's another using scale_fill_manual(). Note this also lets you specify the colors of the bars easily:

```<code>ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
  geom_bar(position="dodge") +
  opts(legend.position="top") +
  scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
</code>```

If you are using the up-to-date (As of January 2015) version of ggplot2 (version 1.0), then the following should work:

```<code>ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
  geom_bar(stat = "identity", position = "dodge") +
  theme(legend.position="top") +
  scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
</code>```

Body:
I have a question concerning the legend in ggplot2.

Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:

carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)

I make a simple bar plot:

require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p

My question is: is there a way to remove the title ('Type') from the legend?

Thanks!

Body:
You've got two good options already, so here's another using scale_fill_manual(). Note this also lets you specify the colors of the bars easily:

ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
  geom_bar(position="dodge") +
  opts(legend.position="top") +
  scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))

If you are using the up-to-date (As of January 2015) version of ggplot2 (version 1.0), then the following should work:

ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
  geom_bar(stat = "identity", position = "dodge") +
  theme(legend.position="top") +
  scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))


问:
Join one row with last foregoing date in Vertica
I want to get the status in table B that was current on the date of an event in table A.

```<code>Table A
Person: Date:       Event
Bob     2020-01-05  Party

Table B
Person:  Date: Status
Bob      2020-01-08     Awake
Bob      2020-01-03     Dinner
Bob      2020-01-01     Cycling
</code>```

So the right result will be

```<code>Bob     2020-01-05  Party Dinner
</code>```

I tried this but got error 'Correlated subquery expression without aggregates and with limit is not supported'.

```<code>SELECT
    A.Person,
    A.Date,
    A.Event,
    (
        SELECT Status FROM B
        WHERE A.Person = B.Person AND B.Date <= A.Date
        ORDER BY B.Date desc
        LIMIT 1
    ) AS Status
FROM A
</code>```

Can anyone tell me what I should do instead? I tried a few other ideas but keep running into other errors.

答:
If you want the result for just one person, you can just sort and limit:

```<code>select
    a.person,
    a.date,
    a.event,
    b.status
from tablea a
inner join tableb b on b.person = a.person
where a.person = 'Bob'
order by b.date desc
limit 1
</code>```

If you want to handle more than than one person at a time, an option is to use window functions:

```<code>select *
from (
    select
        a.person,
        a.date,
        a.event,
        b.status,
        row_number() over(partition by a.person order by b.date desc) rn
    from tablea a
    inner join tableb b on b.person = a.person
) t
where rn = 1
</code>```

Body:
I want to get the status in table B that was current on the date of an event in table A.

Table A
Person: Date:       Event
Bob     2020-01-05  Party

Table B
Person:  Date: Status
Bob      2020-01-08     Awake
Bob      2020-01-03     Dinner
Bob      2020-01-01     Cycling

So the right result will be

Bob     2020-01-05  Party Dinner

I tried this but got error 'Correlated subquery expression without aggregates and with limit is not supported'.

SELECT
    A.Person,
    A.Date,
    A.Event,
    (
        SELECT Status FROM B
        WHERE A.Person = B.Person AND B.Date <= A.Date
        ORDER BY B.Date desc
        LIMIT 1
    ) AS Status
FROM A

Can anyone tell me what I should do instead? I tried a few other ideas but keep running into other errors.

Body:
If you want the result for just one person, you can just sort and limit:

select
    a.person,
    a.date,
    a.event,
    b.status
from tablea a
inner join tableb b on b.person = a.person
where a.person = 'Bob'
order by b.date desc
limit 1

If you want to handle more than than one person at a time, an option is to use window functions:

select *
from (
    select
        a.person,
        a.date,
        a.event,
        b.status,
        row_number() over(partition by a.person order by b.date desc) rn
    from tablea a
    inner join tableb b on b.person = a.person
) t
where rn = 1


问:
WooCommerce Subscription: Don't have the SUSPEND button
On my account page / View subscription, in the ACTION paragraph, I have a CANCEL button but not the SUSPEND button. Do you know if it is normal?

I have traced this function and it returns only the cancel data : wcs_get_all_user_actions_for_subscription

Thanks for help

答:
This is normal Pipoo.

There is an admin setting that allows suspend/suspend options.

https://docs.woocommerce.com/document/subscriptions/store-manager-guide/#misc-settings

I figured this out the hard way myself.

Its possible you may need to update as well if your version of subscriptions is old/outdated.


问:
Is there a tool to check CSS url files exist?
I've just been tasked with migrating a website from a Windows server to a Linux server.

One of the issues I've noticed straight away is that there are a number of CSS url() definitions that don't work because the case in the CSS is not the same as the actual file.

eg:

```<code>background: url(myFile.jpg);
</code>```

while on the server the file is actually MyFile.jpg.

Does anyone know of a simple tool or browser plugin I can use just to scan the CSS file and verify that the url() declarations exist so that I can easily find and fix them?

The site is quite large, so I don't want to have to navigate through the pages to find 404 errors if I can avoid it.

答:
Here's how I would approach this.

Make sure all image requests are handled by a (PHP) script, by adding the following to my .htaccess

RewriteRule .(?:jpe?g|gif|png|bmp)$ /images.php [NC,L]

Use file_exists() to check if the file exists, maybe even try if a lowercase version of the file exists.

Log missing files into a database table or text file.

Use a script to loop through the website's sitemap with curl to get a complete list of requested filenames that resulted in a 404.

Body:
I've just been tasked with migrating a website from a Windows server to a Linux server.

One of the issues I've noticed straight away is that there are a number of CSS url() definitions that don't work because the case in the CSS is not the same as the actual file.

eg:

background: url(myFile.jpg);

while on the server the file is actually MyFile.jpg.

Does anyone know of a simple tool or browser plugin I can use just to scan the CSS file and verify that the url() declarations exist so that I can easily find and fix them?

The site is quite large, so I don't want to have to navigate through the pages to find 404 errors if I can avoid it.