问:
org.gradle.tooling.BuildException in Android Studio 3.0 Canary 3
After upgrading my AS to 3.0 Canary 3, I am unable to compile my app. Below is the stacktrace:</p>

```<code>* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:packageDevDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:98)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:68)
    at org.gradle.api.internal.tasks.execution.SkipCachedTaskExecuter.execute(SkipCachedTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ResolveBuildCacheKeyExecuter.execute(ResolveBuildCacheKeyExecuter.java:51)
    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:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    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:248)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:239)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:114)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:68)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:239)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:226)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:120)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:77)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:101)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:95)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:527)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:95)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.tooling.BuildException
    at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$10(SplitScope.java:243)
    at com.android.build.gradle.internal.scope.SplitScope.parallelForEachOutput(SplitScope.java:238)
    at com.android.build.gradle.internal.scope.SplitScope.parallelForEachOutput(SplitScope.java:198)
    at com.android.build.gradle.internal.scope.SplitScope.parallelForEachOutput(SplitScope.java:182)
    at com.android.build.gradle.tasks.PackageAndroidArtifact.doFullTaskAction(PackageAndroidArtifact.java:301)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:80)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:161)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:132)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.execute(ExecuteActionsTaskExecuter.java:115)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.execute(ExecuteActionsTaskExecuter.java:109)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:114)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:109)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:90)
    ... 28 more
Caused by: java.lang.NoSuchMethodError
    at com.android.ide.common.internal.WaitableExecutor.waitForAllTasks(WaitableExecutor.java:215)
    at com.android.build.gradle.internal.scope.SplitScope.parallelForEachOutput(SplitScope.java:237)
    ... 43 more
Caused by: java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concurrent/Executor;
    at com.android.apkzlib.zip.ZFile.createSources(ZFile.java:1586)
    at com.android.apkzlib.zip.ZFile.makeStoredEntry(ZFile.java:1546)
    at com.android.apkzlib.zip.ZFile.add(ZFile.java:1625)
    at com.android.apkzlib.zfile.ApkZFileCreator.writeFile(ApkZFileCreator.java:141)
    at com.android.builder.internal.packaging.IncrementalPackager.updateFiles(IncrementalPackager.java:170)
    at com.android.builder.internal.packaging.IncrementalPackager.updateDex(IncrementalPackager.java:138)
    at com.android.build.gradle.tasks.PackageAndroidArtifact.doTask(PackageAndroidArtifact.java:523)
    at com.android.build.gradle.tasks.PackageAndroidArtifact.splitFullAction(PackageAndroidArtifact.java:359)
    at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$6(SplitScope.java:187)
    at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$7(SplitScope.java:204)
    at com.android.build.gradle.internal.scope.SplitScope.lambda$null$8(SplitScope.java:226)
    Suppressed: java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concurrent/Executor;
            at com.android.apkzlib.zip.ZFile.createSources(ZFile.java:1586)
            at com.android.apkzlib.zip.ZFile.makeStoredEntry(ZFile.java:1546)
            at com.android.apkzlib.zip.ZFile.add(ZFile.java:1625)
            at com.android.apkzlib.zip.ZFile.add(ZFile.java:1499)
            at com.android.apkzlib.sign.ManifestGenerationExtension.updateManifest(ManifestGenerationExtension.java:241)
            at com.android.apkzlib.sign.ManifestGenerationExtension.access$000(ManifestGenerationExtension.java:52)
            at com.android.apkzlib.sign.ManifestGenerationExtension$1.lambda$beforeUpdate$0(ManifestGenerationExtension.java:168)
            at com.android.apkzlib.zip.ZFile.notify(ZFile.java:2099)
            at com.android.apkzlib.zip.ZFile.update(ZFile.java:871)
            at com.android.apkzlib.zip.ZFile.close(ZFile.java:1161)
            at com.android.apkzlib.zfile.ApkZFileCreator.close(ApkZFileCreator.java:172)
            at com.google.common.io.Closer.close(Closer.java:213)
            at com.android.builder.internal.packaging.IncrementalPackager.close(IncrementalPackager.java:330)
            at com.android.build.gradle.tasks.PackageAndroidArtifact.doTask(PackageAndroidArtifact.java:535)
            at com.android.build.gradle.tasks.PackageAndroidArtifact.splitFullAction(PackageAndroidArtifact.java:359)
            at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$6(SplitScope.java:187)
            at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$7(SplitScope.java:204)
            at com.android.build.gradle.internal.scope.SplitScope.lambda$null$8(SplitScope.java:226)
            at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
            at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
            at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
            at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
            at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
</code>```

答:
This answer may help you.

To sum up, I had to remove com.google.firebase:firebase-plugins:1.1.0 that was causing this error.

Body:
After upgrading my AS to 3.0 Canary 3, I am unable to compile my app. Below is the stacktrace:

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:packageDevDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:98)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:68)
    at org.gradle.api.internal.tasks.execution.SkipCachedTaskExecuter.execute(SkipCachedTaskExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:60)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ResolveBuildCacheKeyExecuter.execute(ResolveBuildCacheKeyExecuter.java:51)
    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:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    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:248)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:239)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:114)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:68)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:239)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:226)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:120)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:77)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:101)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:95)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:527)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:95)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.tooling.BuildException
    at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$10(SplitScope.java:243)
    at com.android.build.gradle.internal.scope.SplitScope.parallelForEachOutput(SplitScope.java:238)
    at com.android.build.gradle.internal.scope.SplitScope.parallelForEachOutput(SplitScope.java:198)
    at com.android.build.gradle.internal.scope.SplitScope.parallelForEachOutput(SplitScope.java:182)
    at com.android.build.gradle.tasks.PackageAndroidArtifact.doFullTaskAction(PackageAndroidArtifact.java:301)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:80)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:161)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:132)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.execute(ExecuteActionsTaskExecuter.java:115)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.execute(ExecuteActionsTaskExecuter.java:109)
    at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:114)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:109)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:90)
    ... 28 more
Caused by: java.lang.NoSuchMethodError
    at com.android.ide.common.internal.WaitableExecutor.waitForAllTasks(WaitableExecutor.java:215)
    at com.android.build.gradle.internal.scope.SplitScope.parallelForEachOutput(SplitScope.java:237)
    ... 43 more
Caused by: java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concurrent/Executor;
    at com.android.apkzlib.zip.ZFile.createSources(ZFile.java:1586)
    at com.android.apkzlib.zip.ZFile.makeStoredEntry(ZFile.java:1546)
    at com.android.apkzlib.zip.ZFile.add(ZFile.java:1625)
    at com.android.apkzlib.zfile.ApkZFileCreator.writeFile(ApkZFileCreator.java:141)
    at com.android.builder.internal.packaging.IncrementalPackager.updateFiles(IncrementalPackager.java:170)
    at com.android.builder.internal.packaging.IncrementalPackager.updateDex(IncrementalPackager.java:138)
    at com.android.build.gradle.tasks.PackageAndroidArtifact.doTask(PackageAndroidArtifact.java:523)
    at com.android.build.gradle.tasks.PackageAndroidArtifact.splitFullAction(PackageAndroidArtifact.java:359)
    at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$6(SplitScope.java:187)
    at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$7(SplitScope.java:204)
    at com.android.build.gradle.internal.scope.SplitScope.lambda$null$8(SplitScope.java:226)
    Suppressed: java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concurrent/Executor;
            at com.android.apkzlib.zip.ZFile.createSources(ZFile.java:1586)
            at com.android.apkzlib.zip.ZFile.makeStoredEntry(ZFile.java:1546)
            at com.android.apkzlib.zip.ZFile.add(ZFile.java:1625)
            at com.android.apkzlib.zip.ZFile.add(ZFile.java:1499)
            at com.android.apkzlib.sign.ManifestGenerationExtension.updateManifest(ManifestGenerationExtension.java:241)
            at com.android.apkzlib.sign.ManifestGenerationExtension.access$000(ManifestGenerationExtension.java:52)
            at com.android.apkzlib.sign.ManifestGenerationExtension$1.lambda$beforeUpdate$0(ManifestGenerationExtension.java:168)
            at com.android.apkzlib.zip.ZFile.notify(ZFile.java:2099)
            at com.android.apkzlib.zip.ZFile.update(ZFile.java:871)
            at com.android.apkzlib.zip.ZFile.close(ZFile.java:1161)
            at com.android.apkzlib.zfile.ApkZFileCreator.close(ApkZFileCreator.java:172)
            at com.google.common.io.Closer.close(Closer.java:213)
            at com.android.builder.internal.packaging.IncrementalPackager.close(IncrementalPackager.java:330)
            at com.android.build.gradle.tasks.PackageAndroidArtifact.doTask(PackageAndroidArtifact.java:535)
            at com.android.build.gradle.tasks.PackageAndroidArtifact.splitFullAction(PackageAndroidArtifact.java:359)
            at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$6(SplitScope.java:187)
            at com.android.build.gradle.internal.scope.SplitScope.lambda$parallelForEachOutput$7(SplitScope.java:204)
            at com.android.build.gradle.internal.scope.SplitScope.lambda$null$8(SplitScope.java:226)
            at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
            at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
            at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
            at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
            at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)


来源: stackexchange

问:
C++ Template : Choosing overloaded functions using implicit conversion to template instantiated type!
Consider these overloaded functions,

```<code>void fun(Int2Type<1>) {}
void fun(Int2Type<2>) {}
void fun(Int2Type<3>) {}
void fun(Int2Type<4>) {}
</code>```

I want to call these in this way,

```<code>fun(1); // this should call first function
fun(4); // this should call fourth function
</code>```

Is there a way to do that? If yes, so can we do the same with some runtime value, say this,
(please note that in the above calls, the argument is known at compile-time)

```<code>fun(value); // value can be decided at runtime!
</code>```

Or any alternative if that is not possible? The goal is, different function should be called based on different integral value!

EDIT

By the way, I cannot use any of the following:

Using switch(value)

using some SomeFuncTable funTable[] = {fun(Int2Type<1>(), fun(Int2Type<2>()} etc

答:
No, there's no way to use runtime values as a template parameter. The only thing you can do is something like:</p>

```<code>void fun(int x) {
    switch(x) {
    case 1:
        fun(Int2Type<1>());
        break;
    case 2:
        fun(Int2Type<2>());
        break;
    case 3:
        fun(Int2Type<3>());
        break;
    case 4:
        fun(Int2Type<4>());
        break;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Consider these overloaded functions,

void fun(Int2Type<1>) {}
void fun(Int2Type<2>) {}
void fun(Int2Type<3>) {}
void fun(Int2Type<4>) {}

I want to call these in this way,

fun(1); // this should call first function
fun(4); // this should call fourth function

Is there a way to do that? If yes, so can we do the same with some runtime value, say this,
(please note that in the above calls, the argument is known at compile-time)

fun(value); // value can be decided at runtime!

Or any alternative if that is not possible? The goal is, different function should be called based on different integral value!

EDIT

By the way, I cannot use any of the following:

Using switch(value)

using some SomeFuncTable funTable[] = {fun(Int2Type<1>(), fun(Int2Type<2>()} etc

Body:
No, there's no way to use runtime values as a template parameter. The only thing you can do is something like:

void fun(int x) {
    switch(x) {
    case 1:
        fun(Int2Type<1>());
        break;
    case 2:
        fun(Int2Type<2>());
        break;
    case 3:
        fun(Int2Type<3>());
        break;
    case 4:
        fun(Int2Type<4>());
        break;
    }
}


问:
How can I redirect all prints to a email body
I tried to get the prints out to a text file. I got the text file output right. Mail sending is also OK but cannot add all the print texts to email body. First thout to redirect all prints to email body. Then thought to read to output text file for the email body, failed in both.</p>

```<code>import sys, os, arcpy, time
import string, smtplib
from arcpy import env

env.overwriteOutput = True

postFix = time.strftime("%Y%m%d")
LogsLocation = os.getcwd()

Script = sys.argv[0]    # This get the script name
ScriptFile = Script.split('\\')[-1]
LogFileName = ScriptFile.split('.')[0]

def listFcsInGDB():
    # set your arcpy.env.workspace to a gdb before calling
    for fds in arcpy.ListDatasets('','feature') + ['']:
        for fc in arcpy.ListFeatureClasses('','',fds):
            for Owner in OwnerList:
                if fc.split('.')[-2] == Owner:
                    yield os.path.join(fds, fc)

def SendEmail(message,Priority):
    SUBJECT = "Asset length report for Water"
    TO = email
    FROM = "AssetLength.Report@DB.production.com"
    MIMEversion = "1.0"
    ContentType = "text/html"
    BODY = string.join((
            "From: %s" % FROM,
            "To: %s" % TO,
            "Subject: %s" % SUBJECT ,
            "X-Priority: %s" % Priority ,
            "MIME-Version: %s" % MIMEversion,
            "Content-type: %s" % ContentType,
            "",
            message
            ), "\r\n")
    server = smtplib.SMTP('smtpmail',25) #server = smtplib.SMTP(HOST)
    server.sendmail(FROM, [TO], BODY)
    server.quit()

DEBUG = 1

if DEBUG:

    print '\nGenerating asset length report for -\n  Effluent, \n  Sewer and \n  Water ... ...'
    Environment = DEV
    Email = 'email'

    txt = open(LogsLocation + '\\' + postFix + '_' + LogFileName + '_' + Environment + ".txt", 'w')
    sys.stdout = txt

    print "----------------------"  # to email body
    print Script                    # to email body
    print "----------------------"  # to email body

    OwnerList = ['EFFLUENT', 'SEWER']

    if Environment == 'DEV':
        Server = 'DBRZSQL07'

    print "Input: ", Environment    # to email body

    DatabaseConnectionDirectory = r'\\xxx\ConnectionFiles'
    Workspace = env.workspace = DatabaseConnectionDirectory+ '\\' + Server + '\\' + 'Me.sde'
    #print "\nWorkspace: ", Workspace, "\n"

    print 'Effluent Network'    # to email body
    print '----------------'    # to email body

    fcs = listFcsInGDB()
    for fc in fcs:
        if fc.split('.')[-2]+'.'+fc.split('.')[-1] == 'EFFLUENT.Main':
            arcpy.MakeFeatureLayer_management (fc, "EMlyr")
            arcpy.SelectLayerByAttribute_management ("EMlyr", "NEW_SELECTION", " OWNER <> 'OTHER' AND LIFECYCLESTATUS <> 'ABANDONED' ")
            Length=[]
            rows = arcpy.SearchCursor("EMlyr")
            for row in rows:
                Segment = row.getValue("SHAPE.STLength()")
                Length.append(Segment)
            total = sum(Length)
            #totalkm = sum(Length)/1000
            print 'Effluent Main ..                    ', (round(total, 2)), 'meter'    # to email body
            arcpy.Delete_management("EMlyr")

    print '\nSewer Network' # to email body
    print '--------------'  # to email body

    fcs = listFcsInGDB()
    for fc in fcs:
        if fc.split('.')[-1] == 'GravityMain':
            arcpy.MakeFeatureLayer_management (fc, "GMlyr")
            arcpy.SelectLayerByAttribute_management ("GMlyr", "NEW_SELECTION", " OWNER <> 'OTHER' AND LIFECYCLESTATUS <> 'ABANDONED' ")
            Length=[]
            rows = arcpy.SearchCursor("GMlyr")
            for row in rows:
                Segment = row.getValue("SHAPE.STLength()")
                Length.append(Segment)
            total = sum(Length)
            #totalkm = sum(Length)/1000
            print 'Sewer GravityMain ..              ', (round(total, 2)), 'meter'  # to email body
            arcpy.Delete_management("GMlyr")

    print '\n***************************************************\n' # to email body

    message = message() # ??
    Priority = 3
    SendEmail(message,Priority)

else: # Bad arguments
  msg = "\nERROR>> Bad arguments."
  print msg
</code>```

答:
You need to pass the text of the message into the function SendEmail() as a string. So instead of print statements, you need to collect all the lines you want to appear in the body of the message.

Instead of

```<code>print "----------------------"  # to email body
print Script                    # to email body
print "----------------------"  # to email body
</code>```

do this

```<code>payload = []
...
payload.append("----------------------")
payload.append(Script)
payload.append("----------------------")
</code>```

If you have more than one item in your print statement then you need to assemble them into a single formatted string. So instead of

```<code>print 'Sewer GravityMain ..              ', (round(total, 2)), 'meter'  # to email body
</code>```

do

```<code>payload.append("Sewer GravityMain ..%14.2f meter" % total)
</code>```

The list payload is a list of strings. Before sending, create a single string from this list with linefeeds between the elements.

```<code>message = '\n'.join(payload)
SendEmail(message,Priority)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried to get the prints out to a text file. I got the text file output right. Mail sending is also OK but cannot add all the print texts to email body. First thout to redirect all prints to email body. Then thought to read to output text file for the email body, failed in both.

import sys, os, arcpy, time
import string, smtplib
from arcpy import env

env.overwriteOutput = True

postFix = time.strftime("%Y%m%d")
LogsLocation = os.getcwd()

Script = sys.argv[0]    # This get the script name
ScriptFile = Script.split('\\')[-1]
LogFileName = ScriptFile.split('.')[0]

def listFcsInGDB():
    # set your arcpy.env.workspace to a gdb before calling
    for fds in arcpy.ListDatasets('','feature') + ['']:
        for fc in arcpy.ListFeatureClasses('','',fds):
            for Owner in OwnerList:
                if fc.split('.')[-2] == Owner:
                    yield os.path.join(fds, fc)

def SendEmail(message,Priority):
    SUBJECT = "Asset length report for Water"
    TO = email
    FROM = "AssetLength.Report@DB.production.com"
    MIMEversion = "1.0"
    ContentType = "text/html"
    BODY = string.join((
            "From: %s" % FROM,
            "To: %s" % TO,
            "Subject: %s" % SUBJECT ,
            "X-Priority: %s" % Priority ,
            "MIME-Version: %s" % MIMEversion,
            "Content-type: %s" % ContentType,
            "",
            message
            ), "\r\n")
    server = smtplib.SMTP('smtpmail',25) #server = smtplib.SMTP(HOST)
    server.sendmail(FROM, [TO], BODY)
    server.quit()

DEBUG = 1

if DEBUG:

    print '\nGenerating asset length report for -\n  Effluent, \n  Sewer and \n  Water ... ...'
    Environment = DEV
    Email = 'email'

    txt = open(LogsLocation + '\\' + postFix + '_' + LogFileName + '_' + Environment + ".txt", 'w')
    sys.stdout = txt

    print "----------------------"  # to email body
    print Script                    # to email body
    print "----------------------"  # to email body

    OwnerList = ['EFFLUENT', 'SEWER']

    if Environment == 'DEV':
        Server = 'DBRZSQL07'

    print "Input: ", Environment    # to email body

    DatabaseConnectionDirectory = r'\\xxx\ConnectionFiles'
    Workspace = env.workspace = DatabaseConnectionDirectory+ '\\' + Server + '\\' + 'Me.sde'
    #print "\nWorkspace: ", Workspace, "\n"

    print 'Effluent Network'    # to email body
    print '----------------'    # to email body

    fcs = listFcsInGDB()
    for fc in fcs:
        if fc.split('.')[-2]+'.'+fc.split('.')[-1] == 'EFFLUENT.Main':
            arcpy.MakeFeatureLayer_management (fc, "EMlyr")
            arcpy.SelectLayerByAttribute_management ("EMlyr", "NEW_SELECTION", " OWNER <> 'OTHER' AND LIFECYCLESTATUS <> 'ABANDONED' ")
            Length=[]
            rows = arcpy.SearchCursor("EMlyr")
            for row in rows:
                Segment = row.getValue("SHAPE.STLength()")
                Length.append(Segment)
            total = sum(Length)
            #totalkm = sum(Length)/1000
            print 'Effluent Main ..                    ', (round(total, 2)), 'meter'    # to email body
            arcpy.Delete_management("EMlyr")

    print '\nSewer Network' # to email body
    print '--------------'  # to email body

    fcs = listFcsInGDB()
    for fc in fcs:
        if fc.split('.')[-1] == 'GravityMain':
            arcpy.MakeFeatureLayer_management (fc, "GMlyr")
            arcpy.SelectLayerByAttribute_management ("GMlyr", "NEW_SELECTION", " OWNER <> 'OTHER' AND LIFECYCLESTATUS <> 'ABANDONED' ")
            Length=[]
            rows = arcpy.SearchCursor("GMlyr")
            for row in rows:
                Segment = row.getValue("SHAPE.STLength()")
                Length.append(Segment)
            total = sum(Length)
            #totalkm = sum(Length)/1000
            print 'Sewer GravityMain ..              ', (round(total, 2)), 'meter'  # to email body
            arcpy.Delete_management("GMlyr")

    print '\n***************************************************\n' # to email body

    message = message() # ??
    Priority = 3
    SendEmail(message,Priority)

else: # Bad arguments
  msg = "\nERROR>> Bad arguments."
  print msg

Body:
You need to pass the text of the message into the function SendEmail() as a string. So instead of print statements, you need to collect all the lines you want to appear in the body of the message.

Instead of

print "----------------------"  # to email body
print Script                    # to email body
print "----------------------"  # to email body

do this

payload = []
...
payload.append("----------------------")
payload.append(Script)
payload.append("----------------------")

If you have more than one item in your print statement then you need to assemble them into a single formatted string. So instead of

print 'Sewer GravityMain ..              ', (round(total, 2)), 'meter'  # to email body

do

payload.append("Sewer GravityMain ..%14.2f meter" % total)

The list payload is a list of strings. Before sending, create a single string from this list with linefeeds between the elements.

message = '\n'.join(payload)
SendEmail(message,Priority)


问:
how to call the block inside the function, who is waiting for another function's block completion inside itself?
I have a situation where in a class I have 3 functions. a, b and c function. I am calling c function inside b and b function inside a. but here I have 1 question.
where to call b function completion block, once the c's function completion block is executed completely.

for eg:

```<code>typealias fetchCompletionBlock = () -> Void

class abcd {

    func a() {
        b({
            print("b called completed")
        })
    }
    func b(_ onCompletion: @escaping fetchCompletionBlock) {
        c({
            print("c called completed")
        })
    }
    func c(_ onCompletion: @escaping fetchCompletionBlock) {
        print("c called")

        onCompletion()
    }
    //self.a()
}

var data = abcd()
data.a()
</code>```

where to call the b function completion block. i know it will be inside b function body, but i don't know the exact place.

Could some one help in this.

答:
b function completion block should be called with in the c function completion handler.

function b should be like:

```<code>func b(_ onCompletion: @escaping fetchCompletionBlock) {
    c({
        print("c called completed")
        onCompletion()
    })
}
</code>```

Body:
I have a situation where in a class I have 3 functions. a, b and c function. I am calling c function inside b and b function inside a. but here I have 1 question.
where to call b function completion block, once the c's function completion block is executed completely.

for eg:

typealias fetchCompletionBlock = () -> Void

class abcd {

    func a() {
        b({
            print("b called completed")
        })
    }
    func b(_ onCompletion: @escaping fetchCompletionBlock) {
        c({
            print("c called completed")
        })
    }
    func c(_ onCompletion: @escaping fetchCompletionBlock) {
        print("c called")

        onCompletion()
    }
    //self.a()
}

var data = abcd()
data.a()

where to call the b function completion block. i know it will be inside b function body, but i don't know the exact place.

Could some one help in this.

Body:
b function completion block should be called with in the c function completion handler.

function b should be like:

func b(_ onCompletion: @escaping fetchCompletionBlock) {
    c({
        print("c called completed")
        onCompletion()
    })
}


问:
ggplot - ordering x-axis labels by multiple columns
with a table like below

```<code>df <- read.table(textConnection("
tier make model sales
entry Toyota Yeti 10000
entry Honda Jazz 8000
entry Nissan Sunny 5000
entry Honda Amaze 4000
entry Toyota Model10 3500
entry Nissan Beat 2000
Mid Honda Civic 4000
Mid Toyota Corolla 3000
Mid Honda Accord 2500
Mid Nissan Xtrail 2200
Mid Toyota Camry 1800
Mid Nissan Moon 800
"), header = TRUE)

> df
    tier   make   model sales
1  entry Toyota    Yeti 10000
2  entry  Honda    Jazz  8000
3  entry Nissan   Sunny  5000
4  entry  Honda   Amaze  4000
5  entry Toyota Model10  3500
6  entry Nissan    Beat  2000
7    Mid  Honda   Civic  4000
8    Mid Toyota Corolla  3000
9    Mid  Honda  Accord  2500
10   Mid Nissan  Xtrail  2200
11   Mid Toyota   Camry  1800
12   Mid Nissan    Moon   800
</code>```

When I plot the sales by model using ggplot as below I get the plot in the picture

```<code>ggplot(df, aes(x=model, y=sales)) +
  geom_point()
</code>```

As expected the x-axis labels for model are in the ascending order as per their levels - Accord comes first and Yeti the last.

```<code>> str(df)
'data.frame':   12 obs. of  4 variables:
 $ tier : Factor w/ 2 levels "entry","Mid": 1 1 1 1 1 1 2 2 2 2 ...
 $ make : Factor w/ 3 levels "Honda","Nissan",..: 3 1 2 1 3 2 1 3 1 2 ...
 $ model: Factor w/ 12 levels "Accord","Amaze",..: 12 7 10 2 8 3 5 6 1 11 ...
 $ sales: int  10000 8000 5000 4000 3500 2000 4000 3000 2500 2200 ...
>
</code>```

However, I need the plot with a different order of model - which is obtained when the table is ordered by tier, make and sales(descending). I can get this ordering for the table as in the code below - how do I get the same order of x-axis labels for model in the plot ?

```<code>> df[with(df, order(tier, make, -sales)),]
    tier   make   model sales
2  entry  Honda    Jazz  8000
4  entry  Honda   Amaze  4000
3  entry Nissan   Sunny  5000
6  entry Nissan    Beat  2000
1  entry Toyota    Yeti 10000
5  entry Toyota Model10  3500
7    Mid  Honda   Civic  4000
9    Mid  Honda  Accord  2500
10   Mid Nissan  Xtrail  2200
12   Mid Nissan    Moon   800
8    Mid Toyota Corolla  3000
11   Mid Toyota   Camry  1800
>
</code>```

答:
You can change the order of factor levels of the model variable then plot. Like this:

```<code>df <- df[with(df, order(tier, make, -sales)),]
df$model <- factor(df$model, levels = unique(df$model))
ggplot(df, aes(x=model, y=sales)) +
  geom_point()
</code>```

The first line changes the order of rows. The second line is the actual reordering. unique(df$model) is the current order of the variable and by using it as the levels of the factor you can plot the data in this order.

Body:
with a table like below

df <- read.table(textConnection("
tier make model sales
entry Toyota Yeti 10000
entry Honda Jazz 8000
entry Nissan Sunny 5000
entry Honda Amaze 4000
entry Toyota Model10 3500
entry Nissan Beat 2000
Mid Honda Civic 4000
Mid Toyota Corolla 3000
Mid Honda Accord 2500
Mid Nissan Xtrail 2200
Mid Toyota Camry 1800
Mid Nissan Moon 800
"), header = TRUE)

> df
    tier   make   model sales
1  entry Toyota    Yeti 10000
2  entry  Honda    Jazz  8000
3  entry Nissan   Sunny  5000
4  entry  Honda   Amaze  4000
5  entry Toyota Model10  3500
6  entry Nissan    Beat  2000
7    Mid  Honda   Civic  4000
8    Mid Toyota Corolla  3000
9    Mid  Honda  Accord  2500
10   Mid Nissan  Xtrail  2200
11   Mid Toyota   Camry  1800
12   Mid Nissan    Moon   800

When I plot the sales by model using ggplot as below I get the plot in the picture

ggplot(df, aes(x=model, y=sales)) +
  geom_point()

As expected the x-axis labels for model are in the ascending order as per their levels - Accord comes first and Yeti the last.

> str(df)
'data.frame':   12 obs. of  4 variables:
 $ tier : Factor w/ 2 levels "entry","Mid": 1 1 1 1 1 1 2 2 2 2 ...
 $ make : Factor w/ 3 levels "Honda","Nissan",..: 3 1 2 1 3 2 1 3 1 2 ...
 $ model: Factor w/ 12 levels "Accord","Amaze",..: 12 7 10 2 8 3 5 6 1 11 ...
 $ sales: int  10000 8000 5000 4000 3500 2000 4000 3000 2500 2200 ...
>

However, I need the plot with a different order of model - which is obtained when the table is ordered by tier, make and sales(descending). I can get this ordering for the table as in the code below - how do I get the same order of x-axis labels for model in the plot ?

> df[with(df, order(tier, make, -sales)),]
    tier   make   model sales
2  entry  Honda    Jazz  8000
4  entry  Honda   Amaze  4000
3  entry Nissan   Sunny  5000
6  entry Nissan    Beat  2000
1  entry Toyota    Yeti 10000
5  entry Toyota Model10  3500
7    Mid  Honda   Civic  4000
9    Mid  Honda  Accord  2500
10   Mid Nissan  Xtrail  2200
12   Mid Nissan    Moon   800
8    Mid Toyota Corolla  3000
11   Mid Toyota   Camry  1800
>

Body:
You can change the order of factor levels of the model variable then plot. Like this:

df <- df[with(df, order(tier, make, -sales)),]
df$model <- factor(df$model, levels = unique(df$model))
ggplot(df, aes(x=model, y=sales)) +
  geom_point()

The first line changes the order of rows. The second line is the actual reordering. unique(df$model) is the current order of the variable and by using it as the levels of the factor you can plot the data in this order.


问:
trying to convert xls to google spreadsheet using google app script and getting "Empty response" error
I'm trying to convert a xls file to a google spreadsheet with the following code:

```<code>  var searchFor ="fullText contains 'theFile.xls' and '" + FolderId + "' in parents";
  var files = DriveApp.searchFiles(searchFor);
  var file = files.next().getBlob();
  var convertedFileinfo = {
    title: 'theFile',
    parents:[{id: FolderId}]
  };
  Drive.Files.insert(convertedFileinfo, file, {
    convert: true,
    uploadType:'resumable'
  })
</code>```

But i'm getting "Empty response" error on Drive.Files.insert line...

What I'm doing wrong?

答:
I finally get it to work using copy:</p>

```<code>  var searchFor ="fullText contains 'theFile.xls' and '" + FolderId + "' in parents";
  var files = DriveApp.searchFiles(searchFor);
  var xlsFile = files.next();
  Drive.Files.copy({}, xlsFile.getId(), {convert: true});
</code>```

Body:
I'm trying to convert a xls file to a google spreadsheet with the following code:

  var searchFor ="fullText contains 'theFile.xls' and '" + FolderId + "' in parents";
  var files = DriveApp.searchFiles(searchFor);
  var file = files.next().getBlob();
  var convertedFileinfo = {
    title: 'theFile',
    parents:[{id: FolderId}]
  };
  Drive.Files.insert(convertedFileinfo, file, {
    convert: true,
    uploadType:'resumable'
  })

But i'm getting "Empty response" error on Drive.Files.insert line...

What I'm doing wrong?

Body:
I finally get it to work using copy:

  var searchFor ="fullText contains 'theFile.xls' and '" + FolderId + "' in parents";
  var files = DriveApp.searchFiles(searchFor);
  var xlsFile = files.next();
  Drive.Files.copy({}, xlsFile.getId(), {convert: true});


问:
How to exclude a range from another range in Python?
Suppose I've a range (section) and an additional list of ranges to exclude, represented by tuples (start, end):

```<code>section=(1, 100) #Range from 1 to 100

toexclude=[(10,15),(40,50),(80,83)]  #3 sub-ranges
</code>```

I'm looking for an efficient algorithm which returns, from these two inputs, a new list of ranges like:

```<code>[(1,9),(16,39),(51,79),(84,100)]
</code>```

Which is the main range exluding the second list of ranges.

Thanks!

EDIT:

Actually the advice from deceze to use intervaltree seems to be interesting. With a few lines:

```<code>from intervaltree import Interval, IntervalTree
t=IntervalTree()
t[1:100]="main"
t.chop(10,15)
t.chop(40,50)
t.chop(80,83)
t
IntervalTree([Interval(1, 10, 'main'), Interval(15, 40, 'main'), Interval(50, 80, 'main'), Interval(83, 100, 'main')])
</code>```

The intervals are considered closed apparently, but this is a minor issue.

答:
Somethink like this?

```<code>start, end = section

this_start = start
result = []
for exc_start, exc_end in toexclude:
    this_end = exc_start - 1
    result.append((this_start, this_end))
    this_start = exc_end + 1

result.append((this_start, end))
</code>```

EDIT: added if clause to correct according to Paco H. comment

```<code>start, end = section

this_start = start
result = []
for exc_start, exc_end in toexclude:
    if this_end == start:
        start = exc_end + 1
    else:
        this_end = exc_start - 1
        result.append((this_start, this_end))
        this_start = exc_end + 1

if this_end <= end:
    result.append((this_start, end))
</code>```

Body:
Suppose I've a range (section) and an additional list of ranges to exclude, represented by tuples (start, end):

section=(1, 100) #Range from 1 to 100

toexclude=[(10,15),(40,50),(80,83)]  #3 sub-ranges

I'm looking for an efficient algorithm which returns, from these two inputs, a new list of ranges like:

[(1,9),(16,39),(51,79),(84,100)]

Which is the main range exluding the second list of ranges.

Thanks!

EDIT:

Actually the advice from deceze to use intervaltree seems to be interesting. With a few lines:

from intervaltree import Interval, IntervalTree
t=IntervalTree()
t[1:100]="main"
t.chop(10,15)
t.chop(40,50)
t.chop(80,83)
t
IntervalTree([Interval(1, 10, 'main'), Interval(15, 40, 'main'), Interval(50, 80, 'main'), Interval(83, 100, 'main')])

The intervals are considered closed apparently, but this is a minor issue.

Body:
Somethink like this?

start, end = section

this_start = start
result = []
for exc_start, exc_end in toexclude:
    this_end = exc_start - 1
    result.append((this_start, this_end))
    this_start = exc_end + 1

result.append((this_start, end))

EDIT: added if clause to correct according to Paco H. comment

start, end = section

this_start = start
result = []
for exc_start, exc_end in toexclude:
    if this_end == start:
        start = exc_end + 1
    else:
        this_end = exc_start - 1
        result.append((this_start, this_end))
        this_start = exc_end + 1

if this_end <= end:
    result.append((this_start, end))


问:
TCA displayCond - check if specific value in specific select box is set
I have defined a select like this in the TCA file of my model:

```<code>    'test' => array(
        'exclude' => 1,
        'label' => 'test',
        'config' => array(
            'type' => 'select',
            'items' => array(
                array("A", "A"),
                array("Foo", "FOO"),
        ...
</code>```

The input field format should only appear in the backend, if the option "Foo" is selected.

Attempt 1:

```<code>    'format' => array(
        'displayCond' => 'FIELD:test.config.items:=:Foo',
    ...
</code>```

Attempt 2:

```<code>    'format' => array(
        'displayCond' => 'FIELD:test:=:Foo',
    ...
</code>```

Is this possible?

答:
Attempt 2 looks correct to me. Did you add 'requestUpdate' => 'test' to the ['ctrl'] section of the TCA to make the form reload after changing the field "test"?

https://docs.typo3.org/typo3cms/TCAReference/7.6/Reference/Ctrl/Index.html?highlight=requestupdate#requestupdate

Body:
I have defined a select like this in the TCA file of my model:

    'test' => array(
        'exclude' => 1,
        'label' => 'test',
        'config' => array(
            'type' => 'select',
            'items' => array(
                array("A", "A"),
                array("Foo", "FOO"),
        ...

The input field format should only appear in the backend, if the option "Foo" is selected.

Attempt 1:

    'format' => array(
        'displayCond' => 'FIELD:test.config.items:=:Foo',
    ...

Attempt 2:

    'format' => array(
        'displayCond' => 'FIELD:test:=:Foo',
    ...

Is this possible?


问:
Extend Div Into Parent Without Negative Margins
I would like to have a child div extend to be the same width as it's parent's parent. So with HTML structure like this:

```<code><div class="pp">
  <div class="p">
    <p>
    Some text
    </p>
    <div class="c">
      This is the thingy!
    </div>
    <p>
    Some more text
    </p>
  </div>
</div>
</code>```

I would like div.c to extend to the borders of div.pp.

I know this is possible with negative margins, but in my situation I am not aware of the margins of div.pp beforehand. I'm aware I could write some JavaScript to do this, but I am interested in a CSS only solution. I'm also aware that changing the structure of the HTML could solve this problem, however that is also not an option.

Here is fiddle illustrating the HTML and some helpful CSS:

https://jsfiddle.net/y37mLkzu/1/

There is an example there of fixing this with negative margins.

答: Cant you use positions? Just curious to know. If I use position:absolute, it will work.

Body:
I would like to have a child div extend to be the same width as it's parent's parent. So with HTML structure like this:

    Some text

      This is the thingy!

    Some more text

I would like div.c to extend to the borders of div.pp.

I know this is possible with negative margins, but in my situation I am not aware of the margins of div.pp beforehand. I'm aware I could write some JavaScript to do this, but I am interested in a CSS only solution. I'm also aware that changing the structure of the HTML could solve this problem, however that is also not an option.

Here is fiddle illustrating the HTML and some helpful CSS:

https://jsfiddle.net/y37mLkzu/1/

There is an example there of fixing this with negative margins.


问:
Get Value from Win32_Environment WMI Query
How can I get VariableValue3 and put it to $myVariable as a string?

```<code>get-wmiobject -class Win32_Environment | select-object Name, VariableValue

Name                     VariableValue
----                     -------------
ValueName1               VariableValue1
ValueName2               VariableValue2
ValueName3               VariableValue3
ValueName4               VariableValue4
</code>```

答:
```<code>$myVariable = (Get-Wmiobject -class Win32_Environment | Where-Object {$_.Name -eq "ValueName3"}).VariableValue
</code>```

Body:
How can I get VariableValue3 and put it to $myVariable as a string?

get-wmiobject -class Win32_Environment | select-object Name, VariableValue

Name                     VariableValue
----                     -------------
ValueName1               VariableValue1
ValueName2               VariableValue2
ValueName3               VariableValue3
ValueName4               VariableValue4


问:
Devexpress report designer version conflicts
I'm trying to add a DevExpress Report Desginer Wizard to my WPF project but I keep getting an error about versions. I've posted a screenshot to simplify things

This project already contains references to DevExpress controls of a different version.

  The current version is 15.2.4.

  Incorrect reference: DevExpress.Data.v14.1 14.1.8

I've updated the project files per the DevExpress Upgrade notes but this hasn't changed anything.

答:
I resolved the error by removing all references to DevExpress components with a different version than the 15.2 that it was trying to use.

I had to clean and build my solution after doing this because they obstinately kept coming back and causing trouble so if you're here looking for a solution, be aware of that.


问:
Tabs switch back not working with *ngIf oder hidden
I've created tabs with native html and css and I want to use *ngIf to disable some tabs if an specific user is loggedin. Currently I am not able to switch back after I clicked the next tab and it is forwarding me to the start site of my application. What I am doing wrong?

HTML tabs

```<code><div class="col-lg-8  bhoechie-tab-menu">
       <div class="list-group" (click)="callMap();">
          <a href="#" class="list-group-item text-center active " *ngIf="username == 'admin'>
             <h4 class="glyphicon glyphicon-globe"></h4>
             <br/>Test1
          </a>
          <a href="#" class="list-group-item text-center "  >
             <h4 class="glyphicon glyphicon-eye-open" ></h4>
             <br/>Test2
          </a>
          <a href="#" class="list-group-item text-center" >
             <h4 class="glyphicon glyphicon-dashboard"></h4>
             <br/>Test3
          </a>
       </div>
    </div>

<div class="col-lg-12 " >
   <div class="bhoechie-tab">
      <div class="bhoechie-tab-content active " >
         <p>Test
         </p>
      </div>
   </div>
</div>
<div class="col-lg-12 bewerten" >
<div class="bhoechie-tab">
   <div class="bhoechie-tab-content  ">
<p>Test2<p>
   </div>
</div>
</div>
</code>```

CSS

```<code>/* Sidebar Styles */

.sidebar-nav {
    position: fixed;
    top: 0;
    width: 240px;
    padding: 0;
    list-style: none;
    height:100%;
}

.sidebar-nav li {
    text-indent: 20px;
    line-height: 40px;

}

.sidebar-nav li a {
    display: block;
    text-decoration: none;
    color: #4d4d4d;
;
}

.sidebar-nav li a:hover {
    text-decoration: none;
    color: #fff;
    background: rgba(255,255,255,0.2);
}

.sidebar-nav li a:active,
.sidebar-nav li a:focus {
    text-decoration: none;
}

.sidebar-nav > .sidebar-brand {
    height: 65px;
    font-size: 18px;
    line-height: 60px;
}

.sidebar-nav > .sidebar-brand a {
    color: #999999;
}

.sidebar-nav > .sidebar-brand a:hover {
    color: #fff;
    background: none;
}

div.bhoechie-tab-menu{
  padding-right: 0;
  padding-left: 0;
  padding-bottom: 0;
}
div.bhoechie-tab-menu div.list-group{
  /*margin-bottom: 0;*/
}
div.bhoechie-tab-menu div.list-group>a{
  /*margin-bottom: 0;*/
}
div.bhoechie-tab-menu div.list-group>a .glyphicon,
div.bhoechie-tab-menu div.list-group>a .fa {
  color: #FF7F50;
}
div.bhoechie-tab-menu div.list-group>a:first-child{
  border-top-right-radius: 0;
  -moz-border-top-right-radius: 0;
}
div.bhoechie-tab-menu div.list-group>a:last-child{
  border-bottom-right-radius: 0;
  -moz-border-bottom-right-radius: 0;
}
div.bhoechie-tab-menu div.list-group>a.active,
div.bhoechie-tab-menu div.list-group>a.active .glyphicon,
div.bhoechie-tab-menu div.list-group>a.active .fa{
  background-color: #FF7F50;
  border-color: #FF7F50;
  color: #ffffff;
}
div.bhoechie-tab-menu div.list-group>a.active:after{
  content: '';
  position: absolute;
  left: 100%;
  top: 50%;
  margin-top: -13px;
  border-left: 0;
  border-bottom: 13px solid transparent;
  border-top: 13px solid transparent;
  border-left: 10px solid #FF7F50;
}
</code>```

Angular2 Component

```<code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Http, Headers } from '@angular/http';
import {Observable} from 'rxjs/Rx';
declare var $:

@Component({
  selector: 'sidebar',
  styleUrls: ['./sidebar.component.css'],
  templateUrl: './sidebar.component.html'
})

export class SidebarComponent implements OnInit {
  map:any;
 username:any;

constructor(public apiService:APIService, public apiServiceMapEntire:APIGoogleEntireService){}

ngOnInit(){
this.clickedMenu();
this.username = JSON.parse(localStorage.getItem('currentUser')).username;
// console.log(localStorage.getItem('currentUser'));

}
}
</code>```

答:
The problem with your code, is that the username is only fetch during ngOnInit() of your compoment. At a moment, the user is maybe not logged in yet.

I would do it like the following :

template:

```<code>      <a href="#" class="list-group-item text-center active " *ngIf="isAdmin()">
         <h4 class="glyphicon glyphicon-globe"></h4>
         <br/>Test1
      </a>
</code>```

component:

```<code>private isAdmin() {
    let user = JSON.parse(localStorage.getItem('currentUser'));
    return user && user.userName === 'admin';   // In that way, I won't have an error if the user is not in localStorage
}
</code>```

Body:
I've created tabs with native html and css and I want to use *ngIf to disable some tabs if an specific user is loggedin. Currently I am not able to switch back after I clicked the next tab and it is forwarding me to the start site of my application. What I am doing wrong?

HTML tabs

Test1

Test2

Test3

Test

Test2

CSS

/* Sidebar Styles */

.sidebar-nav {
    position: fixed;
    top: 0;
    width: 240px;
    padding: 0;
    list-style: none;
    height:100%;
}

.sidebar-nav li {
    text-indent: 20px;
    line-height: 40px;

}

.sidebar-nav li a {
    display: block;
    text-decoration: none;
    color: #4d4d4d;
;
}

.sidebar-nav li a:hover {
    text-decoration: none;
    color: #fff;
    background: rgba(255,255,255,0.2);
}

.sidebar-nav li a:active,
.sidebar-nav li a:focus {
    text-decoration: none;
}

.sidebar-nav > .sidebar-brand {
    height: 65px;
    font-size: 18px;
    line-height: 60px;
}

.sidebar-nav > .sidebar-brand a {
    color: #999999;
}

.sidebar-nav > .sidebar-brand a:hover {
    color: #fff;
    background: none;
}

div.bhoechie-tab-menu{
  padding-right: 0;
  padding-left: 0;
  padding-bottom: 0;
}
div.bhoechie-tab-menu div.list-group{
  /*margin-bottom: 0;*/
}
div.bhoechie-tab-menu div.list-group>a{
  /*margin-bottom: 0;*/
}
div.bhoechie-tab-menu div.list-group>a .glyphicon,
div.bhoechie-tab-menu div.list-group>a .fa {
  color: #FF7F50;
}
div.bhoechie-tab-menu div.list-group>a:first-child{
  border-top-right-radius: 0;
  -moz-border-top-right-radius: 0;
}
div.bhoechie-tab-menu div.list-group>a:last-child{
  border-bottom-right-radius: 0;
  -moz-border-bottom-right-radius: 0;
}
div.bhoechie-tab-menu div.list-group>a.active,
div.bhoechie-tab-menu div.list-group>a.active .glyphicon,
div.bhoechie-tab-menu div.list-group>a.active .fa{
  background-color: #FF7F50;
  border-color: #FF7F50;
  color: #ffffff;
}
div.bhoechie-tab-menu div.list-group>a.active:after{
  content: '';
  position: absolute;
  left: 100%;
  top: 50%;
  margin-top: -13px;
  border-left: 0;
  border-bottom: 13px solid transparent;
  border-top: 13px solid transparent;
  border-left: 10px solid #FF7F50;
}

Angular2 Component

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Http, Headers } from '@angular/http';
import {Observable} from 'rxjs/Rx';
declare var $:

@Component({
  selector: 'sidebar',
  styleUrls: ['./sidebar.component.css'],
  templateUrl: './sidebar.component.html'
})

export class SidebarComponent implements OnInit {
  map:any;
 username:any;

constructor(public apiService:APIService, public apiServiceMapEntire:APIGoogleEntireService){}

ngOnInit(){
this.clickedMenu();
this.username = JSON.parse(localStorage.getItem('currentUser')).username;
// console.log(localStorage.getItem('currentUser'));

}
}

Body:
The problem with your code, is that the username is only fetch during ngOnInit() of your compoment. At a moment, the user is maybe not logged in yet.

I would do it like the following :

template:

      <a href="#" class="list-group-item text-center active " *ngIf="isAdmin()">
         <h4 class="glyphicon glyphicon-globe"></h4>
         <br/>Test1
      </a>

component:

private isAdmin() {
    let user = JSON.parse(localStorage.getItem('currentUser'));
    return user && user.userName === 'admin';   // In that way, I won't have an error if the user is not in localStorage
}


问:
Design sidebar with border
I have a design in PSD file like that: original design psd

and now, I'm trying convert this design on psd file to html file. This is my result and it isn't look like design: convert to html

答: A bit hard to say without seeing the code, but most likely you should use padding-left instead of margin-left on those list elements to create the distance from the left border of the parent element.

Title: Design sidebar with border


问:
Failed to invoke public okhttp3.RequestBody() with no args
1.This is the time I use retrofit mistakes

first step：

```<code>public interface RequestService {
    @POST ("home/indexThree")
    Call<RequestBody> getHomeinfo(@Body RequestBody info);
}
</code>```

second step:

```<code> Retrofit retrofit = new Retrofit.Builder()
             .baseUrl(url)
             .addConverterFactory(GsonConverterFactory.create())
             .build();
    RequestService requestService = retrofit.create(RequestService.class);
    RequestBody body = RequestBody.create(JSON, jsonObject.toString());
            Call<RequestBody> homeinfo = requestService.getHomeinfo(body);
    homeinfo.enqueue(new Callback<RequestBody>() {
        @Override
        public void onResponse(Call<RequestBody> call, Response<RequestBody> response) {
            System.out.println("response"+response.body().toString());
        }

        @Override
        public void onFailure(Call<RequestBody> call, Throwable t) {
            System.out.println("onFailure"+t.getMessage().toString());
        }
    });
</code>```

I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. thx!

答:
```<code>Call<LoginModel>call=apiService.getForgotPassword(Utill.encodeString(json));call.enqueue(new Callback<LoginModel>() {
        @Override
        public void onResponse(Call<LoginModel> call,
        Response<LoginModel> response) {
            pDialog.dismiss();
            if (response.body() != null) {
                LoginModel clientModel = response.body();
                if (clientModel.getResult().equalsIgnoreCase("OK")) {
                    Utill.showCenteredToast(LoginActivity.this, clientModel.getResult());

                    dialog.dismiss();
                } else {
                    dialog.dismiss();
                    Utill.showCenteredToast(LoginActivity.this, clientModel.getResult());
                }
            }
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
1.This is the time I use retrofit mistakes

first step：

public interface RequestService {
    @POST ("home/indexThree")
    Call<RequestBody> getHomeinfo(@Body RequestBody info);
}

second step:

 Retrofit retrofit = new Retrofit.Builder()
             .baseUrl(url)
             .addConverterFactory(GsonConverterFactory.create())
             .build();
    RequestService requestService = retrofit.create(RequestService.class);
    RequestBody body = RequestBody.create(JSON, jsonObject.toString());
            Call<RequestBody> homeinfo = requestService.getHomeinfo(body);
    homeinfo.enqueue(new Callback<RequestBody>() {
        @Override
        public void onResponse(Call<RequestBody> call, Response<RequestBody> response) {
            System.out.println("response"+response.body().toString());
        }

        @Override
        public void onFailure(Call<RequestBody> call, Throwable t) {
            System.out.println("onFailure"+t.getMessage().toString());
        }
    });

I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. thx!


问:
casperJS: how to access web site using facebook authentication?
i would use casperjs in order to crawl web site pages.
Before this, i must login to the web site. Because web site allow to login using "facebook account", i would like simulate this using casperjs.
I wasn't able to find a sample.

Could any one help me?

Thanks!

答:
//code to setup casper instance
var casper = require('casper').create({
  verbose: true,
  logLevel: "debug",
  waitTimeout: 7000,
  resourceTimeout: 10000,
  viewportSize: {
    width: 1024,
    height: 768
  },
  pageSettings: {
    javascriptEnabled: true,
    loadImages: true,
    loadPlugins: true
  }
});
//varibles required
var url = "https://www.facebook.com";
var utils = require('utils');
var x = require('casper').selectXPath;
//comamd line varibles
var user = casper.cli.args[0];
var pass = casper.cli.args[1];
// first step is to open the online resource
casper.start(url, function(response) {
  console.log(url + ' is opened');
});

// code to login to your facebook account
casper.then(function () {
  this.sendKeys(x('//*[@id="email"]'),user);
  this.sendKeys(x('//*[@id="pass"]'),pass);
  this.click(x('//*[@id="u_0_q"]'));
});

//run the script
casper.run(function() {
  this.then(function () {
    //take a screenshot of login
    this.capture('facebook_screenshot.png');
    this.exit();
  });
});```

The following code will log into Facebook if you could specify the website your scraping I'd be happy to write the additional code necessary to get to the Facebook login page

Body:
//code to setup casper instance
var casper = require('casper').create({
  verbose: true,
  logLevel: "debug",
  waitTimeout: 7000,
  resourceTimeout: 10000,
  viewportSize: {
    width: 1024,
    height: 768
  },
  pageSettings: {
    javascriptEnabled: true,
    loadImages: true,
    loadPlugins: true
  }
});
//varibles required
var url = "https://www.facebook.com";
var utils = require('utils');
var x = require('casper').selectXPath;
//comamd line varibles
var user = casper.cli.args[0];
var pass = casper.cli.args[1];
// first step is to open the online resource
casper.start(url, function(response) {
  console.log(url + ' is opened');
});

// code to login to your facebook account
casper.then(function () {
  this.sendKeys(x('//*[@id="email"]'),user);
  this.sendKeys(x('//*[@id="pass"]'),pass);
  this.click(x('//*[@id="u_0_q"]'));
});

//run the script
casper.run(function() {
  this.then(function () {
    //take a screenshot of login
    this.capture('facebook_screenshot.png');
    this.exit();
  });
});

The following code will log into Facebook if you could specify the website your scraping I'd be happy to write the additional code necessary to get to the Facebook login page


问:
Combining multiple MySQL subqueries into one
I have a query that contains that contains three sub queries:

```<code>select
    *,
    (select count(*) from v2_page_views left join v2_pages on v2_page_views.pageID=v2_pages.pageID where v2_page_views.siteID=1 and userID=v2_users.userID and pageTemperature=0) cold,
    (select count(*) from v2_page_views left join v2_pages on v2_page_views.pageID=v2_pages.pageID where v2_page_views.siteID=1 and userID=v2_users.userID and pageTemperature=1) warm,
    (select count(*) from v2_page_views left join v2_pages on v2_page_views.pageID=v2_pages.pageID where v2_page_views.siteID=1 and userID=v2_users.userID and pageTemperature=2) hot
from v2_page_views
left join v2_users on v2_page_views.userID=v2_users.userID
</code>```

I am trying to improve the speed and it seems like combining the three sub queries into one would be a good idea.

My issue is that I am unsure whether it's even possible to output multiple values from a single sub query ... and how I would go about writing a single query. I suspect it will involve IF, CASE and WHEN but I am unsure ...

答:
Try:

```<code>select v2_page_views.columnThatIsId
       sum(case when pageTemperature=0 then 1 else 0 end) cold,
       sum(case when pageTemperature=1 then 1 else 0 end) warm,
       sum(case when pageTemperature=2 then 1 else 0 end) hot
  from v2_page_views
        left join v2_users
          on v2_page_views.userID=v2_users.userID
 where v2_page_views.siteID=1
 group by v2_page_views.columnThatIsId
</code>```

If you need other columns just join this with the table you need. Be aware to maintain the group by intact to not generate wrong values.

To this specific solution I gave you wont even need the left join because there is nothing from that table. This is just a heads up. If you are still unable to figure out the whole solution let me know, I will edit with it.

Body:
I have a query that contains that contains three sub queries:

select
    *,
    (select count(*) from v2_page_views left join v2_pages on v2_page_views.pageID=v2_pages.pageID where v2_page_views.siteID=1 and userID=v2_users.userID and pageTemperature=0) cold,
    (select count(*) from v2_page_views left join v2_pages on v2_page_views.pageID=v2_pages.pageID where v2_page_views.siteID=1 and userID=v2_users.userID and pageTemperature=1) warm,
    (select count(*) from v2_page_views left join v2_pages on v2_page_views.pageID=v2_pages.pageID where v2_page_views.siteID=1 and userID=v2_users.userID and pageTemperature=2) hot
from v2_page_views
left join v2_users on v2_page_views.userID=v2_users.userID

I am trying to improve the speed and it seems like combining the three sub queries into one would be a good idea.

My issue is that I am unsure whether it's even possible to output multiple values from a single sub query ... and how I would go about writing a single query. I suspect it will involve IF, CASE and WHEN but I am unsure ...

Body:
Try:

select v2_page_views.columnThatIsId
       sum(case when pageTemperature=0 then 1 else 0 end) cold,
       sum(case when pageTemperature=1 then 1 else 0 end) warm,
       sum(case when pageTemperature=2 then 1 else 0 end) hot
  from v2_page_views
        left join v2_users
          on v2_page_views.userID=v2_users.userID
 where v2_page_views.siteID=1
 group by v2_page_views.columnThatIsId

If you need other columns just join this with the table you need. Be aware to maintain the group by intact to not generate wrong values.

To this specific solution I gave you wont even need the left join because there is nothing from that table. This is just a heads up. If you are still unable to figure out the whole solution let me know, I will edit with it.


问:
How to select integer from an object?
I know it's probably a dumb question but I'm unable to go over this.

I have this Object array which looks like this

```<code>stdClass Object
(
[1] => stdClass Object
    (
        [Product] => Brand Manual
        [Type] => Custom
        [Width_(inches)] => 11
        [Depth_(inches)] => 8.5
        [Color_Type] => B/W
        [Artistic_Discretion] => Full Artistic Discretion(AD3)
        [Brief/Instructions] => edasd
         Product Dimension - 8.5" x 11"

        [Copy_Translation] => No
        [Additional_Versions] => 0
    )
 )
</code>```

I want the Brand Manual so I do this $myValue = $myObject->1->Product; It doesn't work. The integer '1' seems to be the problem. I tried adding quotes too but it doesn't work either.Please help.

答:
You have data stored in object format, so you should use object notation to get your specific data as</p>

```<code>$myValue = $myObject->{1}->Product;
</code>```

Title: How to select integer from an object?

Body:
I know it's probably a dumb question but I'm unable to go over this.

I have this Object array which looks like this

stdClass Object
(
[1] => stdClass Object
    (
        [Product] => Brand Manual
        [Type] => Custom
        [Width_(inches)] => 11
        [Depth_(inches)] => 8.5
        [Color_Type] => B/W
        [Artistic_Discretion] => Full Artistic Discretion(AD3)
        [Brief/Instructions] => edasd
         Product Dimension - 8.5" x 11"

        [Copy_Translation] => No
        [Additional_Versions] => 0
    )
 )

I want the Brand Manual so I do this $myValue = $myObject->1->Product; It doesn't work. The integer '1' seems to be the problem. I tried adding quotes too but it doesn't work either.Please help.

Body:
You have data stored in object format, so you should use object notation to get your specific data as

$myValue = $myObject->{1}->Product;


问:
Android Get OTG USB/External SD CARD Storage devices and their paths
I'm using the following code to get the list of all external storage devices either SDCard or USB connected via OTG

```<code>  List<String> paths = new ArrayList<String>();
    File directory = new File("/storage");

    File[] files = directory.listFiles();
</code>```

It reads sdcard in all devices but the USB gets detected in some

What should i use?

答:
There are no filesystem paths that you can use on Android 4.4+, except those that are returned by getExternalFilesDirs(), getExternalCacheDirs(), and getExternalMediaDirs() (all plural, all on Context).

Ideally, you should be using the Storage Access Framework (e.g., ACTION_OPEN_DOCUMENT_TREE), as that provides the user with the greatest flexibility. However, you are no longer working with files and a filesystem, but rather with Uri values, reminiscent of working with Web services.

Body:
I'm using the following code to get the list of all external storage devices either SDCard or USB connected via OTG

  List<String> paths = new ArrayList<String>();
    File directory = new File("/storage");

    File[] files = directory.listFiles();

It reads sdcard in all devices but the USB gets detected in some

What should i use?


问:
Exposing an entire apt repository as a target for bazel?
I would like to build docker images in Bazel. Our current builds do a fair amount of apt-get'ing to pull in packages and their dependencies inside the docker build. This is not ideal because the build system has no real concept of tracking the actual upstream packages we need.

But - we definitely don't want to be manually trying to resolve and sort out every dependency in a docker image for a deb package either.

Is there a module or method which allows me to bring the equivalent of apt-get install [thing into the build environment that will automatically pull down the packages it depends on as well (so I can then install them into the docker image via the various extract functions)?

The ideal endstate is one where the Bazel dependency tree is tracking upstream packages for me against their respective repositories, and where if multiple docker images depend off the same packages it will correctly detect when they all need to be rebuilt.

答: You may want to have a look at the discussion here where we are exploring more or less this exact topic for the purposes of bootstrapping images without the full distro inside.</p>


问:
Redirect domain name in HAProxy while preserving the URL path
I have HAProxy as front layer to our Node.js app and I'm looking for a way to rewrite URL. For example, if customers go to https://aaa.example/product/123, HAProxy will rewrite to URL https://bbb.example/product/123. is this possible to do in HAProxy? The important is we want to preserve the URL path (product/123) and just change the host name.

答:
You say you want to "rewrite" but that is a term that is often misused.  What is your intention?

Do you want to rewrite the incoming URL and then change the address in the browser's address bar with an HTTP redirect?

If so, in proxy configuration:

```<code>http-request redirect prefix https://example.org if { hdr(host) -i example.com }
</code>```

This changes example.com to example.org and tells the browser to ask again.

Test:

```<code>curl -v https://example.com/foo/bar/1234?query=yes
...
< HTTP/1.1 302 Found
< Cache-Control: no-cache
< Content-length: 0
< Location: https://example.org/foo/bar/1234?query=yes
< Connection: close
</code>```

This is the simplest solution if it fits your need, because the net result is that the browser is actually making the correct request itself, reducing the potential for unexpected behavior.

Or do you want to change the Host: header that the backend server sees, but not send a redirect, and leave the browser's address bar as it was?

This changes example.com to example.org in the Host: header that the back-end server sees in the request from HAProxy.

```<code>http-request set-header Host example.org if { hdr(host) -i example.com }
</code>```

This will do exactly what is intended, but it may not have the desired result, particularly if the application is aware of other inconsistencies, such as the incoming Referer: or Origin: being inconsistent with the Host:, or if it's doing non-portable things with cookies, in which case further header rewriting (possibly in both directions) or application changes may be necessary.

Body:
You say you want to "rewrite" but that is a term that is often misused.  What is your intention?

Do you want to rewrite the incoming URL and then change the address in the browser's address bar with an HTTP redirect?

If so, in proxy configuration:

http-request redirect prefix https://example.org if { hdr(host) -i example.com }

This changes example.com to example.org and tells the browser to ask again.

Test:

curl -v https://example.com/foo/bar/1234?query=yes
...
< HTTP/1.1 302 Found
< Cache-Control: no-cache
< Content-length: 0
< Location: https://example.org/foo/bar/1234?query=yes
< Connection: close

This is the simplest solution if it fits your need, because the net result is that the browser is actually making the correct request itself, reducing the potential for unexpected behavior.

Or do you want to change the Host: header that the backend server sees, but not send a redirect, and leave the browser's address bar as it was?

This changes example.com to example.org in the Host: header that the back-end server sees in the request from HAProxy.

http-request set-header Host example.org if { hdr(host) -i example.com }

This will do exactly what is intended, but it may not have the desired result, particularly if the application is aware of other inconsistencies, such as the incoming Referer: or Origin: being inconsistent with the Host:, or if it's doing non-portable things with cookies, in which case further header rewriting (possibly in both directions) or application changes may be necessary.


问:
How can I write a piece of Java an code that checks if any character of a string is convertible to an integer between 0 and 9?
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

```<code>String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}
</code>```

where IntegerFormat Exception is something like

```<code>public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}
</code>```

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

```<code>at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)
</code>```

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

答:
There is already a run time exception for that, use it!</p>

```<code>String s = "8&35";
try {
    int result = Integer.parseInt(s);
    System.out.println("This is parsable: " + result);
} catch (NumberFormatException e) {
    System.err.println("s is  NOT parsable....");
}
</code>```

Body:
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}

where IntegerFormat Exception is something like

public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

Body:
There is already a run time exception for that, use it!

String s = "8&35";
try {
    int result = Integer.parseInt(s);
    System.out.println("This is parsable: " + result);
} catch (NumberFormatException e) {
    System.err.println("s is  NOT parsable....");
}