text:
Q: How to solve "content is not allowed in prolog"? I have checked all my xml files and couldn't find anything out of place.
I've rebuilt project.
I've invalidated the cache and restarted.
I've rn the analyze operation on the app module and nothing came up.
Not sure how to find the issue.
I think this is the relevant log but I am not sure what to do with that.
Caused by: org.xml.sax.SAXParseException; systemId: file:/C:/Users/Yanay/.gradle/caches/modules-2/files-2.1/androidx.databinding/databinding-compiler/3.5.0/6befd1020152445183148625d14748066883a929/databinding-compiler-3.5.0.pom; lineNumber: 2; columnNumber: 1; Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)

THis happened after I've installed some updates suggested by studio for the studio itself, gradle and emulator.
EDIT: after fixing the file according to CommonsWare suggestion, it fails again. I think this is the important part of the log. SHould I just uninstall and reinstall Android Studio?
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve com.android.tools.build:aapt2:3.5.0-5435860.
Required by:
    project :app
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve com.android.tools.build:aapt2:3.5.0-5435860.
Caused by: org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.MetaDataParseException: Could not parse POM https://dl.google.com/dl/android/maven2/com/android/tools/build/aapt2/3.5.0-5435860/aapt2-3.5.0-5435860.pom
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.PomReader$2.transform(PomReader.java:144)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.PomReader$2.transform(PomReader.java:139)
    at org.gradle.internal.resource.local.LocalFileStandInExternalResource.withContentIfPresent(LocalFileStandInExternalResource.java:190)
    at org.gradle.internal.resource.AbstractExternalResource.withContent(AbstractExternalResource.java:38)
    at org.gradle.internal.resource.local.DefaultLocallyAvailableExternalResource.withContent(DefaultLocallyAvailableExternalResource.java:104)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.PomReader.<init>(PomReader.java:139)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.PomReader.<init>(PomReader.java:160)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.GradlePomModuleDescriptorParser.doParseDescriptor(GradlePomModuleDescriptorParser.java:92)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.AbstractModuleDescriptorParser.parseDescriptor(AbstractModuleDescriptorParser.java:48)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.AbstractModuleDescriptorParser.parseMetaData(AbstractModuleDescriptorParser.java:43)
    at org.gradle.api.internal.artifacts.repositories.metadata.DefaultMavenPomMetadataSource.parseMetaDataFromResource(DefaultMavenPomMetadataSource.java:53)
    at org.gradle.api.internal.artifacts.repositories.metadata.AbstractRepositoryMetadataSource.parseMetaDataFromArtifact(AbstractRepositoryMetadataSource.java:73)
    at org.gradle.api.internal.artifacts.repositories.metadata.AbstractRepositoryMetadataSource.create(AbstractRepositoryMetadataSource.java:60)
    at org.gradle.api.internal.artifacts.repositories.metadata.DefaultMavenPomMetadataSource.create(DefaultMavenPomMetadataSource.java:38)
    at org.gradle.api.internal.artifacts.repositories.metadata.RedirectingGradleMetadataModuleMetadataSource.create(RedirectingGradleMetadataModuleMetadataSource.java:51)
    at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver.resolveStaticDependency(ExternalResourceResolver.java:243)
    at org.gradle.api.internal.artifacts.repositories.resolver.MavenResolver.doResolveComponentMetaData(MavenResolver.java:126)
    at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver$RemoteRepositoryAccess.resolveComponentMetaData(ExternalResourceResolver.java:444)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$ResolveAndCacheRepositoryAccess.resolveComponentMetaData(CachingModuleComponentRepository.java:373)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.lambda$resolveComponentMetaData$5(ErrorHandlingModuleComponentRepository.java:158)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.lambda$tryResolveAndMaybeBlacklist$18(ErrorHandlingModuleComponentRepository.java:227)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.tryResolveAndMaybeBlacklist(ErrorHandlingModuleComponentRepository.java:241)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.tryResolveAndMaybeBlacklist(ErrorHandlingModuleComponentRepository.java:226)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.performOperationWithRetries(ErrorHandlingModuleComponentRepository.java:219)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.resolveComponentMetaData(ErrorHandlingModuleComponentRepository.java:157)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ComponentMetaDataResolveState.process(ComponentMetaDataResolveState.java:69)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ComponentMetaDataResolveState.resolve(ComponentMetaDataResolveState.java:61)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.findBestMatch(RepositoryChainComponentMetaDataResolver.java:138)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.findBestMatch(RepositoryChainComponentMetaDataResolver.java:119)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.resolveModule(RepositoryChainComponentMetaDataResolver.java:92)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainComponentMetaDataResolver.resolve(RepositoryChainComponentMetaDataResolver.java:63)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.ComponentResolversChain$ComponentMetaDataResolverChain.resolve(ComponentResolversChain.java:95)
    at org.gradle.api.internal.artifacts.ivyservice.clientmodule.ClientModuleResolver.resolve(ClientModuleResolver.java:63)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.ComponentState.resolve(ComponentState.java:198)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.ComponentState.getMetadata(ComponentState.java:148)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.EdgeState.calculateTargetConfigurations(EdgeState.java:182)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.EdgeState.attachToTargetConfigurations(EdgeState.java:134)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.DependencyGraphBuilder.attachToTargetRevisionsSerially(DependencyGraphBuilder.java:342)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.DependencyGraphBuilder.resolveEdges(DependencyGraphBuilder.java:241)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.DependencyGraphBuilder.traverseGraph(DependencyGraphBuilder.java:180)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder.DependencyGraphBuilder.resolve(DependencyGraphBuilder.java:141)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DefaultArtifactDependencyResolver.resolve(DefaultArtifactDependencyResolver.java:122)
    at org.gradle.api.internal.artifacts.ivyservice.DefaultConfigurationResolver.resolveGraph(DefaultConfigurationResolver.java:171)
    at org.gradle.api.internal.artifacts.ivyservice.ShortCircuitEmptyConfigurationResolver.resolveGraph(ShortCircuitEmptyConfigurationResolver.java:86)
    at org.gradle.api.internal.artifacts.ivyservice.ErrorHandlingConfigurationResolver.resolveGraph(ErrorHandlingConfigurationResolver.java:73)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$7.run(DefaultConfiguration.java:585)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.resolveGraphIfRequired(DefaultConfiguration.java:576)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.access$600(DefaultConfiguration.java:138)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$6.run(DefaultConfiguration.java:556)
    at org.gradle.api.internal.project.DefaultProjectStateRegistry$SafeExclusiveLockImpl.withLock(DefaultProjectStateRegistry.java:244)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.resolveExclusively(DefaultConfiguration.java:552)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.resolveToStateOrLater(DefaultConfiguration.java:547)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.access$2200(DefaultConfiguration.java:138)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationFileCollection.getSelectedArtifacts(DefaultConfiguration.java:1178)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationFileCollection.getFiles(DefaultConfiguration.java:1167)
    at org.gradle.api.internal.file.AbstractFileCollection.iterator(AbstractFileCollection.java:72)
    at org.gradle.api.internal.file.CompositeFileCollection.iterator(CompositeFileCollection.java:64)
    at org.gradle.api.internal.file.AbstractFileCollection.getSingleFile(AbstractFileCollection.java:59)
    at com.android.build.gradle.internal.res.namespaced.Aapt2DaemonManagerService.registerAaptService(Aapt2DaemonManagerService.kt:83)
    at com.android.build.gradle.internal.res.namespaced.Aapt2DaemonManagerService.registerAaptService$default(Aapt2DaemonManagerService.kt:81)
    at com.android.build.gradle.internal.res.namespaced.Aapt2DaemonManagerService.registerAaptService(Aapt2DaemonManagerService.kt)
    at com.android.build.gradle.tasks.MergeResources.getResourceProcessor(MergeResources.java:172)
    at com.android.build.gradle.tasks.MergeResources.doFullTaskAction(MergeResources.java:224)
    at com.android.build.gradle.internal.tasks.IncrementalTask.handleIncrementalInputs(IncrementalTask.kt:107)
    at com.android.build.gradle.internal.tasks.IncrementalTask.access$handleIncrementalInputs(IncrementalTask.kt:64)
    at com.android.build.gradle.internal.tasks.IncrementalTask$taskAction$$inlined$recordTaskAction$1.invoke(AndroidVariantTask.kt:51)
    at com.android.build.gradle.internal.tasks.IncrementalTask$taskAction$$inlined$recordTaskAction$1.invoke(AndroidVariantTask.kt:31)
    at com.android.build.gradle.internal.tasks.Blocks.recordSpan(Blocks.java:91)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction$gradle(IncrementalTask.kt:134)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:103)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskInputsTaskAction.doExecute(IncrementalTaskInputsTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:41)
    at org.gradle.api.internal.project.taskfactory.AbstractIncrementalTaskAction.execute(AbstractIncrementalTaskAction.java:25)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$5.run(ExecuteActionsTaskExecuter.java:404)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:393)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:376)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:213)
    at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$0(ExecuteStep.java:32)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:32)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:58)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:35)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:48)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:33)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:39)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
    at org.gradle.internal.execution.steps.CatchExceptionStep.execute(CatchExceptionStep.java:35)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:45)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:31)
    at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:201)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:70)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:45)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:49)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:43)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:32)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:96)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:89)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:54)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:38)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:77)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:90)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:48)
    at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:120)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java:75)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
    at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:94)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:49)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.xml.sax.SAXParseException; systemId: file:/C:/Users/Yanay/.gradle/caches/modules-2/files-2.1/com.android.tools.build/aapt2/3.5.0-5435860/6c4cbb583680b808bee7e4a01ec9e72dad862a17/aapt2-3.5.0-5435860.pom; lineNumber: 2; columnNumber: 1; Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:150)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.PomReader.parseToDom(PomReader.java:256)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.PomReader.access$100(PomReader.java:60)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.PomReader$2.transform(PomReader.java:142)
    ... 170 more

A: Something must have failed with that download. There may be a recipe to force Gradle to re-download dependencies that it thinks that it already has, but I am not certain how to do that.
The simple thing to try to is to replace that POM file with:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>androidx.databinding</groupId>
  <artifactId>databinding-compiler</artifactId>
  <version>3.5.0</version>
  <name>Data Binding Annotation Processor</name>
  <description>The annotation processor for Data Binding. Generates binding classes for runtime.</description>
  <url>https://developer.android.com/studio</url>
  <inceptionYear>2007</inceptionYear>
  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>
  <developers>
    <developer>
      <name>The Android Open Source Project</name>
    </developer>
  </developers>
  <scm>
    <connection>git://android.googlesource.com/platform/tools/base.git</connection>
    <url>https://android.googlesource.com/platform/tools/base</url>
  </scm>
  <dependencies>
    <dependency>
      <groupId>androidx.databinding</groupId>
      <artifactId>databinding-compiler-common</artifactId>
      <version>3.5.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>androidx.databinding</groupId>
      <artifactId>databinding-common</artifactId>
      <version>3.5.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-stdlib-jdk8</artifactId>
      <version>1.3.41</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.10</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.antlr</groupId>
      <artifactId>antlr4</artifactId>
      <version>4.5.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.googlecode.juniversalchardet</groupId>
      <artifactId>juniversalchardet</artifactId>
      <version>1.0.3</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>

That's the copy from my machine, and presumably it is OK.


text:
Q: creating two inputs of passwords in css I've tried many attempts to solve this one but I am unable to:
I want to make two sample input boxes with value="password" and value ="Confirm password"
In such a way that when you click on it the value type is changed from text to password
I have managed to change one box that is the password one but not the confirm password one.You see the problem is because of the positioning in the input[type="password"]I am only able to add one position to it. When I click on the other confirm text box it directly jumps to password text box
HTML
<input type = "passwords" id="passwords" name="passwords" value ="Password" onclick="passwords();" />
    <input type = "confirm" id="confirm" name="confirm" value ="Confirm Password" onclick="confirms();" />

CSS
input[type="password"]
{
    background: transparent;
    border:none;
    color:#2185c5;
height:41px;
width:273px;
padding-left:35px;
border-radius:3px;
font-size:20px;
position:absolute;
top:690px;
left:353.5px;
position:absolute;
z-index:11;

    }

JS
function passwords()
{
    document.getElementById("passwords").value= "";
    document.getElementById('passwords').type = 'password';

}

function confirms()
{
    document.getElementById("confirm").value= "";
     document.getElementById('confirm').type = 'password';

    }

A: You can't type anything in type. confirm is not a type, and neither is passwords. its password.
HTML
<input type="password" id="passwords" name="passwords" placeholder="Password" onclick="passwords();" />
<input type="password" id="confirm" name="confirm" placeholder="Confirm Password" onclick="confirms();" />

Also, Both of your password elements will overlap. Add this at end of your CSS
CSS
input[type="password"]:nth-child(2) {
    top:690px;
    left:700px;
}

A: <input type="password" placeholder="password" />
<input type="password" placeholder="Confirm password" />

A: You can't use your own type. Passwords & Confirm is not a type. Check here for are the available Input Type : Click Here
This might help you!:)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How many crossings are there in an X-ray of an idealized ball of yarn? This is a second question about statistical geometry. The image https://commons.wikimedia.org/wiki/File:Ball_of_yarn_10.jpg shows a typical ball of yarn. The idealized yarn of the question is assumed to be unstretchable and infinitely flexible.
If I take an X-ray of an average ball of yarn (ball radius $R$, yarn radius $r$), how may crossings will I see, on average?
Probably (but I am not sure), the total length will go like $R^3/r^2$. What can be said about the crossing count?


text:
Q: React Reduxjs toolkit is not reading state in useSelector, using Typescript. Is shows me an error that loggedIn is not a boolean I'm passing to the component  a state from store.tsx file and it shows me an error.
Error is in const loggedIn that state.loggedIn.loggedIn is not a boolean.
Below is the code for component
  import React from "react";
import { StyledNavBar, StyledNavButton } from "./styles";
import { useSelector } from "react-redux";

export const NavBar = () => {
  interface IisLoggedInProp {
    loggedIn: boolean;
  }

  **const loggedIn = useSelector(
    (state: IisLoggedInProp) => state.loggedIn.loggedIn
  );**

  return (
    <StyledNavBar>
      <StyledNavButton>Dodaj Post</StyledNavButton>
      {loggedIn && <StyledNavButton>Dodaj Komentarz</StyledNavButton>}
      <StyledNavButton>Toggluj kolory</StyledNavButton>
      <StyledNavButton>Wyślij wiadomość</StyledNavButton>
    </StyledNavBar>
  );
};

And this is how store.js looks like
I have cancelled logOutSlice from provided code to don't make confusion.
 import { createSlice, configureStore } from "@reduxjs/toolkit";

const initialLoggedInState = {
  loggedIn: false,
};

const loggedInSlice = createSlice({
  name: "loggedIn",
  initialState: initialLoggedInState,
  reducers: {
    withLogIn(state) {
      state.loggedIn = true;
    },
    withoutLogIn(state) {
      state.loggedIn = false;
    },
  },
});

export const loggedInActions = loggedInSlice.actions;

export const store = configureStore({
  reducer: { loggedIn: loggedInSlice.reducer, logOut: logOutSlice.reducer },
});

A: useSelector always reads from your root state, so instead of IisLoggedInProp you have to use your RootState type there.

A: the state type is RootState
Do it this way
const loggedIn = useSelector(
    (state: RootState) => state.loggedIn.loggedIn
  );


text:
Q: How to disable HTTP 1.0 protocol in Apache? HTTP 1.0 has security weakness related to session hijacking.
I want to disable it on my web server.

A: You can check against the SERVER_PROTOCOL variable in a mod-rewrite clause. Be sure to put this rule as the first one.
RewriteEngine On
RewriteCond %{SERVER_PROTOCOL} ^HTTP/1\.0$
RewriteCond %{REQUEST_URI} !^/path/to/403/document.html$
RewriteRule ^ - [F]

The additional negative check for !^/path/to/403/document.html$ is so that the forbidden page can be shown to the users. It would otherwise lead to a recursion.

A: If you are on a name-based virtual host (and each virtual server does not have its own separate IP address), then it is technically impossible to connect to your virtual host using HTTP/1.0; Only the default server --the first virtual server defined-- will be accessible. This is because HTTP/1.0 does not support the HTTP "Host" request header, and the Host header is required on name-based virtual hosts in order to "pick" which virtual host the request is being addressed to. In most cases, the response to a true HTTP/1.0 request will be a 400-Bad Request.If you did manage to get that code working, but you later tried to use custom error documents (see Apache core ErrorDocument directive), then the result of blocking a request would be an 'infinite' loop: The server would try to respond with a 403-Forbidden response code, and to serve the custom 403 error document. But this would result in another 403 error because access to all resources --including the custom 403 page-- is denied. So the server would generate another 403 error and then try to respond to it, creating another 403, and another, and another... This would continue until either the client or the server gave up.
I'd suggest something like:
 SetEnvIf Request_Protocol HTTP/1\.0$ Bad_Req
 SetEnvIf Request_URI ^/path-to-your-custom-403-error-page\.html$
 Allow_Bad_Req
 #Order Deny,Allow
 Deny from env=BadReq
 Allow from env=Allow_Bad_Req

In mod_rewrite, something like:
RewriteCond %{THE_REQUEST} HTTP/1\.0$
RewriteCond %{REQUEST_URI} !^/path-to-your-custom-403-error-page\.html$

A: This will (note the FUTURE tense - as of October 2018) be possible with Apache 2.5, using the PolicyVersion directive in mod_policy.  The PolicyVersion directive sets the lowest level of the HTTP protocol that is accepted by the server, virtual host, or directory structure - depending on where the directive is placed.
First enable the policy module:
a2enmod mod_policy

Then in the server config, vhost, or directory (will not work in .htaccess), add:
PolicyVersion enforce HTTP/1.1

Finally restart the server:
systemctl restart apache2


text:
Q: Robocopy: ERROR : Invalid Parameter #4 : "/MT" I have a server that I am working on that is using Windows 2008 SP2 Enterprise and I have found that the installed version of Robocopy is missing the MT (multithread) switch.
Since I'm working with enterprise hardware, having multiple threads can really help my performance so I'd prefer not to have to remove the switch from the copy operation that I am attempting.
What I don't understand is why the installed version is missing this switch since this is a 2008 windows instance. Was the MT switch introduced in 2008R2?
Is there any way I can safely update this version of robocopy (such as copying the executable from one of my other environments)?
To provide just a little background for contextual purposes this command is being issued as part of an automated backup process developed in SSIS. This process executes normally in other environments, so I'm trying to establish a means of upgrading all the older versions with a more recent version of robocopy to maintain functionality. Otherwise I will have to contextually disable the inclusion of the switch which is a pain.

A: According to the documentation on Technet, the /MT parameter applies to Server 2008 R2 but not Server 2008.  I'm not sure if this is due to just the version of the robocopy executable or some other restriction.
What is the File Version of your robocopy.exe, as shown in the file properties?
You might try to pull the newest version of Robocopy (6.1.7601) out of KB2639043 and see if that works for you. Though, information I found on this thread suggests that newer versions of Robocopy don't work at all on Server 2008.


text:
Q: Download list attachments using lists.asmx webservice I am trying to download SharePoint list attachments using the following code. I am receiving an exception "Column 'Attachment_Text' does not belong to table Attachments". Please help resolve this.
private static void fnDownloadattachment(string id)
    {
        Reference.Lists myservice = new Reference.Lists();
        myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
        myservice.Url = "http://XXXXX/_vti_bin/Lists.asmx";

        XmlNode node = myservice.GetAttachmentCollection("listname", id);
        DataSet ds = new DataSet();
        using (XmlNodeReader reader = new XmlNodeReader(node))
        {
            ds.ReadXml(reader);
        }

        DataTable dtAttachment = ds.Tables[0];

        for (int iCnt = 0; iCnt <= dtAttachment.Rows.Count - 1; iCnt++)
        {

            string sourceUrl = Convert.ToString(dtAttachment.Rows[iCnt]["Attachment_Text"]);

            int strLastIndx = sourceUrl.LastIndexOf(@"/");

            string FileName = sourceUrl.Substring(strLastIndx + 1);

            using (WebClient client = new WebClient())
            {

                client.UseDefaultCredentials = true;
                byte[] response = client.DownloadData(sourceUrl);

                FileStream fStream = new FileStream(@"C:\DummyListAttachments\" + FileName, FileMode.Create, FileAccess.ReadWrite);
                fStream.Write(response, 0, response.Length);
                fStream.Close();

            }
        }

A: This code doesn't work only in case you have one attachment.
The best way to find a workaround is to look at the DataTable when you have only one attachment, and see what is the name of the column instead of "Attachment_Text".
You can do it like this:
foreach (DataColumn column in dtAttachment.Columns)
{
    Console.Write(column.ColumnName);
}

After you do this, just change "Attachment_Text" to the necessary column name.


text:
Q: Boolean 'not' operator not working correctly I managed to fix my code except that I can't figure out how to make the boolean part work. We are supposed to use the not operator, but I am not quite sure what is the right way to use it:
def copy_me(list_input):
    ''' (list) -> list
    A function takes as input a list, and returns a copy
    of the list with the following changes:
    Strings have all their letters converted to upper-case
    Integers and floats have their value increased by 1
    booleans are negated (False becomes True, True becomes False)
    Lists are replaced with the word "List"
    The function should leave the original input list unchanged

    >>> copy_me(["aa", 5, ["well", 4], True)
    ['AA', 6, 'List', False]
    >>> copy_me([20932498, 4], 5.98, "And", False)
    ['List', 6.98, 'AND', True]
    '''

    # if element is a string, change all the letters to upper case
    # if element is an integer or float, have their value increased by 1
    # if element is a boolean, negate it
    # if element is a list, replace it with the word "List"

    new_list = list_input[:]

    for index in range(len(new_list)):
        if isinstance(new_list[index], str):
            new_list[index].upper()
        elif isinstance(new_list[index], int):
            new_list[index] += 1
        elif isinstance(new_list[index], float):
            new_list[index] += 1.0
        elif isinstance(new_list[index], list):
            new_list[index] = "List"
        elif isinstance(new_list[index], bool):
            not new_list[index]

    return new_list

A: not new_list[index] is an expression with no side effects meaning that it is essentially a no op.
You probably mean the following instead:
new_list[index] = not new_list[index]

A: You forgot to actually reassign the value of new_list[index] in these two places:
if isinstance(new_list[index], str):
    new_list[index] = new_list[index].upper()
...
elif isinstance(new_list[index], bool):
    new_list[index] = not new_list[index]

Without the = assignment, the value remains unchanged because neither str.upper nor the not operator work in-place.

A: You just forgot to assign the negation to new_list[index]
Another trick, with booleans:
new_list[index] = (new_list[index] == True)

It returns True if True else False.
But this is not what you need here. Just the assignment was missing as I said.

A: This is hat you need:
for index in range(len(new_list)):
    if isinstance(new_list[index], str):
        new_list[index].upper()
    elif isinstance(new_list[index], int):
        new_list[index] += 1
    elif isinstance(new_list[index], float):
        new_list[index] += 1.0
    elif isinstance(new_list[index], list):
        new_list[index] = "List"
    elif isinstance(new_list[index], bool):
        if new_list[index]:
            new_list[index]=False
        else:new_list[index]=True


text:
Q: Algebra to Series Simplification From the Wikipedia page on Fourier Series
        $\begin{align} \frac{1}{\pi}\int_{-\pi}^{\pi}\frac{\pi}{x}\sin(nx)dx & = -\frac{2}{n \pi}\cos(n \pi) + \frac{2}{n^2 \pi^2}\sin(n \pi) \\ & = \frac{2(-1)^{n+1}}{\pi n} \\ \end{align}$
I understand that the $\sin$ and $\cos$ will alternate between $-1, 0, 1$ but I don't understand the 2nd to 3rd step of simplification. I tried separating out constants but was left with $\cos( n \pi) + \frac{1}{n \pi}\sin(n \pi)$. Any insight?

A: Hint: $\sin(n\pi)=0$ for all $n \in \mathbb{Z}$. What about $\cos(n \pi)$?


text:
Q: How to integrate and use FFmpeg library in iOS with Xcode? I wanted to use FFMpeg library for video processing activities, from 2 days I m working on compiling and integrating this library with Xcode 8 and Swift. I tried following links but with no success. Can anyone please help me how to achieve this?
FFMPEG integration on iphone/ ipad project
https://github.com/chrisballinger/FFmpeg-iOS
http://witcheryne.iteye.com/blog/1734706
How to Build FFMpeg as iOS Framework
https://github.com/ElfSundae/FFmpeg-iOS-build
https://github.com/kolyvan/kxmovie

A: I've tried mobile-ffmpeg, and it works (swift 4.2 - Xcode 10.1)
installation is very easy by cocoapods pod 'mobile-ffmpeg-full-gpl', '~> 4.2'
you can use different binaries if you don't need all features, for example: pod 'mobile-ffmpeg-min', '~> 4.2' link
for using in swift you should add ProjectName-Bridging-Header.h to your project and then import the library in that: #import <mobileffmpeg/MobileFFmpeg.h>
you can run a command like this in swift (converting mkv to mp4):
MobileFFmpeg.execute("-i video.mkv -codec copy video.mp4")


text:
Q: My Multi Theft Auto client doesn't detect VRAM properly, how could I solve this? I'm trying to play Multi Theft Auto: San Andreas, but the custom GUI can't render most of the time, because it says, it's out of VRAM. As you'll see the detected VRAM is around 250MB, but I have 6GB, which should be sufficient for this game. All my drivers are up-to-date.
What could I do, to increase the amount of detected VRAM?
Edit 1: Using the built-in scripting interface, I checked, that the used GPU is my discrete GPU ("NVIDIA GeForce GTX 1660 Ti with Max-Q Design"), and the detected VRAM is 256 MB.
Edit 2: I suspect, that the game can't work with cards, that have more than 4 GB vRAM. Could this be true? Can I temporarily decrease the capacity of my vRAM?
Debug information:
MTADiag


text:
Q: Matlab onCleanup with Compiled applications (windows) I have an application made with matlab compiler.
I want to do some shutdown activities whenever it ends. As it seems to be impossible to catch signals in matlab (or I'm not able to), I checked to use onCleanup (Matlab: Is it possible to create signal handlers (.m scripts)). It is working within matlab (native), but not within the compiled application.
I tried to end the application with CTRL-C and with taskkill (which only work with /f). In both cases the onCleanup-method was NOT executed.
For testing purposes here
function sigtest(varargin)
remainder=onCleanup(@()save('exit.mat'));
b=1;
while true
    disp(datestr(now));
    a=rand(round(5*b));%to be saved
    pause(10);
    b=a(1);
end

my source code, which I compiled via mcc -m -v sigtest.m.
As onether try, I inserted the lines
myexiter=addlistener(System.AppDomain.CurrentDomain,'ProcessExit',...
    @(a,b)save('listexit.mat'));

after line 2, but also this .NET-Event is not working.

A: If you're registering shutdown activities within M-code, they're only going to work on a graceful shutdown of the process. The taskkill /f command will do a "forceful" shutdown, which I think will terminate the process immediately. The Matlab interpreter won't get a chance to run whatever cleanup code is still pending. I think Ctrl-C on a console application (which the compiled sigtest.m will be running as) will have the same effect. Same applies to the .NET-Event: if you forcefully kill the process, that callback never gets a chance to run.
If you want on-exit code, or any other cleanup stuff, to run, you need to find a way for the program to find out when it should exit and initiate a more graceful shutdown itself. For example, in your sigtest example, you could check stdin at the end of every pass through the loop, see if the user has typed 'quit', and if so call exit(). Then your onCleanup stuff should run.
In a GUI compiled Matlab application, this is more straightforward; you have GUI controls to exit the application. I don't know what the canonical way is to make a console compiled Matlab application responsive to user exit requests, or if there even is a good one. You might want to make this a GUI app if you think the user might want to request a graceful abort of its operation.


text:
Q: Property 'foo' is protected and only accesible through an instance of class 'Foo' (in instances of Foo) I have the following code in my Typescript. But it reports the following error in the child._moveDeltaX(delta) line:
ERROR: Property '_moveDeltaX' is protected and only accesible
       through an instance of class 'Container'
INFO:  (method) Drawable._moveDeltaX( delta:number):void

The code is the folowing:
class Drawable {

    private _x:number = 0;

    constructor() {}

    /**
     * Moves the instance a delta X number of pixels
     */
    protected _moveDeltaX( delta:number):void {
        this._x += delta;
    }
}

class Container extends Drawable {
    // List of childrens of the Container object
    private childs:Array<Drawable> = [];

    constructor(){ super();}

    protected _moveDeltaX( delta:number ):void {
        super._moveDeltaX(delta);
        this.childs.forEach( child => {
            // ERROR: Property '_moveDeltaX' is protected and only accesible
            //        through an instance of class 'Container'
            // INFO:  (method) Drawable._moveDeltaX( delta:number):void
            child._moveDeltaX(delta);
        });
    }
}

What do I have wrong? I thought that you can access to a protected method. In other lenguajes this code would work without problem.

A: You "childs" object is not in in visibility of the inherited object. You just made a new instance that cannot access the protected method. You can access the protected methods using super, but not for other instances.
This would fail in c# as well (I think).


text:
Q: How to enter the parameters on the command line for this shell script? I was setting up VMWare ESXi on my laptop for learning purposes. I wanted to automate things and got this very nice shell script. It asks for parameters such as the cpu cores, iso path, ram and disk space. I am a beginner in the shell. I understand that it's a very basic question but couldn't find an answer on the internet. Here's the code.
I don't understand how to enter the values of <|c|i|r|s> — the syntax required is not clear, to be precise.
#paratmers: machine name (required), CPU (number of cores), RAM (memory size in MB), HDD Disk size (in GB), ISO (Location of ISO image, optional)
#default params: CPU: 2, RAM: 4096, DISKSIZE: 20GB, ISO: 'blank'
-
phelp() {
    echo "Script for automatic Virtual Machine creation for ESX"
    echo "Usage: ./create.sh options: n <|c|i|r|s>"
    echo "Where n: Name of VM (required), c: Number of virtual CPUs, i: location of an ISO image, r: RAM size in MB, s: Disk size in GB"
    echo "Default values are: CPU: 2, RAM: 4096MB, HDD-SIZE: 20GB"
}

CPU=2
RAM=4096
SIZE=20
ISO="ISO'S"
FLAG=true
ERR=false
n=vmoo

while getopts n:c:i:r:s: option
 do
    case $option in
            n)
                NAME=${OPTARG};
                FLAG=false;
                if [ -z $NAME ]; then
                    ERR=true
                    MSG="$MSG | Please make sure to enter a VM name."
                fi
                ;;
            c)
                CPU=${OPTARG}
                if [ `echo "$CPU" | egrep "^-?[0-9]+$"` ]; then
                    if [ "$CPU" -le "0" ] || [ "$CPU" -ge "32" ]; then
                        ERR=true
                        MSG="$MSG | The number of cores has to be between 1 and 32."
                    fi
                else
                    ERR=true
                    MSG="$MSG | The CPU core number has to be an integer."
                fi
                ;;
            i)
                ISO=${OPTARG}
                if [ ! `echo "$ISO" | egrep "^.*\.(iso)$"` ]; then
                    ERR=true
                    MSG="$MSG | The extension should be .iso"
                fi
                ;;
            r)
                RAM=${OPTARG}
                if [ `echo "$RAM" | egrep "^-?[0-9]+$"` ]; then
                    if [ "$RAM" -le "0" ]; then
                        ERR=true
                        MSG="$MSG | Please assign more than 1MB memory to the VM."
                    fi
                else
                    ERR=true
                    MSG="$MSG | The RAM size has to be an integer."
                fi
                ;;
            s)
                SIZE=${OPTARG}
                if [ `echo "$SIZE" | egrep "^-?[0-9]+$"` ]; then
                    if [ "$SIZE" -le "0" ]; then
                        ERR=true
                        MSG="$MSG | Please assign more than 1GB for the HDD size."
                    fi
                else
                    ERR=true
                    MSG="$MSG | The HDD size has to be an integer."
                fi
                ;;
            \?) echo "Unknown option: -$OPTARG" >&2; phelp; exit 1;;
            :) echo "Missing option argument for -$OPTARG" >&2; phelp; exit 1;;
            *) echo "Unimplimented option: -$OPTARG" >&2; phelp; exit 1;;
    esac
done

if $FLAG; then
echo "You need to at least specify the name of the machine with the -n parameter."
exit 1
fi

if $ERR; then
echo $MSG
exit 1
fi

if [ -d "$NAME" ]; then
echo "Directory - ${NAME} already exists, can't recreate it."
exit
fi

mkdir ${NAME}

vmkfstools -c "${SIZE}"G -a lsilogic $NAME/$NAME.vmdk

touch $NAME/$NAME.vmx

cat << EOF > $NAME/$NAME.vmx

config.version = "8"
virtualHW.version = "7"
vmci0.present = "TRUE"
displayName = "${NAME}"
floppy0.present = "FALSE"
numvcpus = "${CPU}"
scsi0.present = "TRUE"
scsi0.sharedBus = "none"
scsi0.virtualDev = "lsilogic"
memsize = "${RAM}"
scsi0:0.present = "TRUE"
scsi0:0.fileName = "${NAME}.vmdk"
scsi0:0.deviceType = "scsi-hardDisk"
ide1:0.present = "TRUE"
ide1:0.fileName = "${ISO}"
ide1:0.deviceType = "cdrom-image"
pciBridge0.present = "TRUE"
pciBridge4.present = "TRUE"
pciBridge4.virtualDev = "pcieRootPort"
pciBridge4.functions = "8"
pciBridge5.present = "TRUE"
pciBridge5.virtualDev = "pcieRootPort"
pciBridge5.functions = "8"
pciBridge6.present = "TRUE"
pciBridge6.virtualDev = "pcieRootPort"
pciBridge6.functions = "8"
pciBridge7.present = "TRUE"
pciBridge7.virtualDev = "pcieRootPort"
pciBridge7.functions = "8"
ethernet0.pciSlotNumber = "32"
ethernet0.present = "TRUE"
ethernet0.virtualDev = "e1000"
ethernet0.networkName = "Inside"
ethernet0.generatedAddressOffset = "0"
guestOS = "other26xlinux-64"
EOF

MYVM=`vim-cmd solo/registervm /vmfs/volumes/datastore1/${NAME}/${NAME}.vmx`

vim-cmd vmsvc/power.on $MYVM

echo "The Virtual Machine is now setup & the VM has been started up. Your have the    following configuration:"
echo "Name: ${NAME}"
echo "CPU: ${CPU}"
echo "RAM: ${RAM}"
echo "HDD-size: ${SIZE}"
if [ -n "$ISO" ]; then
echo "ISO: ${ISO}"
else
echo "No ISO added."
fi
echo "Thank you."
exit

A: Enter them as -k value pairs, where k is the letter used to identify the parameter.
For instance:
./create.sh -n vmname -c 2 -i /path/to/file.iso -s 512

This sets the name to vmname, the number of CPUs to 2, the ISO filename to /path/to/file.iso, etc.

A: The usage message is about as unhelpful as you can get and still make an attempt at conveying information. Without the code, I would not have known what to do.  Fortunately, with shell scripts, you can see the code, though.  The usage message should read something more like:
{
echo "Usage: $0 -n 'vm name' [-c cpus][-i iso-image][-r ram][-s disk]"
echo "  -n 'vm name'  Name of VM (required)"
echo "  -c cpus       Number of virtual CPUs"
echo "  -i iso-image  Location of an ISO image"
echo "  -r ram        RAM size in MB"
echo "  -s disk       Disk size in GB"
echo "Default values are: CPU: 2, RAM: 4096MB, HDD-SIZE: 20GB"
} >&2

Take heed: when you write a shell script, ensure that the usage information is clearly documented, either in the usage message or perhaps in comments within the script.  The shell script you show is an example of how not to do it.


text: Q: How does Google Chrome share code across all its app versions? It seems like an aweful lot to re-implement a browser across Desktop, Android, and iOS phones. Does the Chrome team share code across these builds and how can they manage that given the different programming platforms involved.


text:
Q: How to solve the import error in JavaScript function I have the following js code:
function getSlideAnswer(responseId, fpToken, coordinateX, traceData) {

    coordinateX = Math.floor(coordinateX);
    var encryptData = {
        "track": traceData,
        "x": coordinateX + "",
        "p": "0,0",
        "finger": fpToken
    };
    var t = CryptoJS.enc.Utf8.parse(responseId.substr(0, 16));
    return CryptoJS.AES.encrypt(JSON.stringify(encryptData), t, {
        iv: t,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    }).ciphertext.toString().toUpperCase();
}

However, I receive the following error:
execjs._exceptions.ProgramError: TypeError: 'JSON' is undefined

How to solve the error?

A: You can replace strigify by string concatenation in JS or Python.
Not sure about parameter types, but an example in JS:

function getSlideAnswer(responseId, fpToken, coordinateX, traceData) {

    coordinateX = Math.floor(coordinateX);
    var encryptData = '{"track":"' + traceData +
        '","x":"' + coordinateX +
        '","p":"0,0","finger":"' + fpToken +
    '"}';
    var t = CryptoJS.enc.Utf8.parse(responseId.substr(0, 16));
    return CryptoJS.AES.encrypt(encryptData, t, {
        iv: t,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    }).ciphertext.toString().toUpperCase();
}
Test()

function Test() {
    var traceData="foo", coordinateX = 123, fpToken = "bar";
    var encryptData = {
        "track": traceData,
        "x": coordinateX + "",
        "p": "0,0",
        "finger": fpToken
    };
    console.log(JSON.stringify(encryptData));
    var encryptDataStrigified = '{"track":"' + traceData +
        '","x":"' + coordinateX +
        '","p":"0,0","finger":"' + fpToken +
    '"}';
    console.log(encryptDataStrigified);
    console.log(JSON.stringify(encryptData) == encryptDataStrigified);
}


text:
Q: How to insert int variable to firebase with swift 4 I am creating a mobile application that gets data from a firebase database in form of strings
let userID = Auth.auth().currentUser?.uid
            ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
                // Get username
                let value1 = snapshot.value as? NSDictionary
                let username1 = value1?["username"] as? String ?? ""
                let balance1 = value1?["balance"] as? String ?? ""

I have to create some calculations with the balance and so i converted the balance to an integer
// Calculate the new balance
                guard let bal = Int(balance1) else {
                    print("error")
                    return
                }
                let amt = self.amtString
                let intamt = Int(amt)
                //fix math

                let newBalance1 = bal - intamt!

Then finally, after the calculation, i have to pass the data back to the firebase database
 self.ref.child("users").child(userID!).setValue(["username": username1, "balance": newBalance1])

This works fine but the problem is, it goes into the database as an integer and removes the quotes . I have tried
let newBalance1 = "\(bal - intamt!)"

But for some reason, this alters the calculation and gives a completely different value .  Please i need help converting the integer to string without altering the calculation.

A: The approach on this may be the issue. If you need the number as an int, store it as an int.
This line of code...

self.ref.child("users").child(userID!).setValue(["username":
  username1, "balance": newBalance1])

...does not "remove the quotes". newBalance1 is defined as an integer in your code (there are no quotes to start with) and this line writes the integer.... as an integer.
If  you want to convert it to a String and write the string out to Firebase, this code will do it.
self.ref.child("users").child(userID!)
        .setValue(["username": username1, "balance": String(newBalance1)])

I ran both of those lines and the results are
users
  some_uid
    balance:  123 //this is an Int from your code
    username: "some username"

and
users
  some_uid
    balance:  "123" //this is a string from my code
    username: "some username"

It's not clear in the question why you need strings - in general if you are working with Ints, leave them as Ints as, for example, it makes sorting work properly
Sorting a series of strings "1", "2", "3", "10" will results in
1
10
2
3

whereas if they are Int's they will sort correctly.

A: I figured out the problem. It was never the int or string. Those were always correct but the code was looping and thus repeating the calculations multiple times till i manually dismissed it, this was the reason for the inconsistent incorrect answers .


text:
Q: Replacement for Drawing in .NET 6 or .NET 7 Recently I was working on .NET Framework 4.8 and decided to change it to .NET 6
At .NET Framework 4.8 I was using the code below to draw a rectangle around the Listbox and  to make the event DrawItem:
using (Pen penBorder = new Pen(Color.FromArgb(66, 66, 66), 2))
            {
                penBorder.Alignment = PenAlignment.Inset;
                graph.DrawRectangle(penBorder, ModifiersLB.Location.X - 2, ModifiersLB.Location.Y - 2, ModifiersLB.Width + 4F, ModifiersLB.Height + 4F);
            }

private void LB_DrawItem(DrawItemEventArgs e, ListBox LB)
        {
            Color backgroundColor = Color.FromArgb(50, 50, 50);
            Color horizontalColor = Color.FromArgb(100, 100, 100);

            if (e.Index >= 0)
            {
                SolidBrush sb = new SolidBrush(((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? horizontalColor : backgroundColor);
                e.Graphics.FillRectangle(sb, e.Bounds);
                string text = LB.Items[e.Index].ToString();
                SolidBrush tb = new SolidBrush(e.ForeColor);
                e.Graphics.DrawString(text, e.Font, tb, LB.GetItemRectangle(e.Index).Location);
            }
        }

The problem is this code is only supported by Windows.
I decided to make this question because I was receiving a warning. I never really intended to make my app supported on all platforms. I just wanted to ask if there is a better way to do what I was doing so that I don't get the warning.
Is there a better method to do this code or is there a ListBox replacement that I could use?


text:
Q: Eliminating redundant batch script I am new to batch and need some guidance on how to make my script shorter...
it works ok but theres alot of repeated lines .
The script sends 'arp -a' to temp file for parse then goes thorugh the 6 IP address to check if they are static or not .
Any advise to create shorter better method would greatly be appreciated . Thank-you !

@ECHO OFF

cls

ECHO ---------------Check SiteC IP = Static -----------------

ARP -a > O:\temp_log.txt

SET /A var1 = 0
SET /A var2 = 0
SET /A var3 = 0
SET /A var4 = 0
SET /A var5 = 0
SET /A var6 = 0

FOR /F "tokens=1,3 delims= " %%A IN ('findstr "static" "O:\temp_log.txt"') DO IF "%% A"=="192.168.0.11" ECHO %%A = %%B && SET /A var1 = 1
IF %var1% == 1 ( ECHO Match ) ELSE ( ECHO SiteC1 FAIL )

ECHO --

FOR /F "tokens=1,3 delims= " %%A IN ('findstr "static" "O:\temp_log.txt"') DO IF "%%A"=="192.168.0.12" ECHO %%A = %%B && SET /A var2 = 1
IF %var2% == 1 ( ECHO Match ) ELSE ( ECHO SiteC2 FAIL )

ECHO --

FOR /F "tokens=1,3 delims= " %%A IN ('findstr "static" "O:\temp_log.txt"') DO IF "%%A"=="192.168.0.13" ECHO %%A = %%B && SET /A var3 = 1
IF %var3% == 1 ( ECHO Match ) ELSE ( ECHO SiteC2 FAIL )

ECHO --

FOR /F "tokens=1,3 delims= " %%A IN ('findstr "static" "O:\temp_log.txt"') DO IF "%%A"=="192.168.0.14" ECHO %%A = %%B && SET /A var4 = 1
IF %var4% == 1 ( ECHO Match ) ELSE ( ECHO SiteC2 FAIL )

ECHO --

FOR /F "tokens=1,3 delims= " %%A IN ('findstr "static" "O:\temp_log.txt"') DO IF "%%A"=="192.168.0.15" ECHO %%A = %%B && SET /A var5 = 1
IF %var5% == 1 ( ECHO Match ) ELSE ( ECHO SiteC5 FAIL )

ECHO --

FOR /F "tokens=1,3 delims= " %%A IN ('findstr "static" "O:\temp_log.txt"') DO IF "%%A"=="192.168.0.16" ECHO %%A = %%B && SET /A var6 = 1
IF %var6% == 1 ( ECHO Match ) ELSE ( ECHO SiteC6 FAIL )

ECHO.
ECHO.

pause

A: @ECHO OFF
SETLOCAL
FOR /l %%s IN (1,1,6) DO SET "var%%s=Site C%%s FAIL"
FOR /f %%A IN ('arp -a ^|findstr "static"') DO (
 FOR /l %%s IN (1,1,6) DO ( ECHO %%A
  IF %%A==192.168.0.1%%s SET var%%s=Site C%%s Match
 )
)
FOR /l %%s IN (1,1,6) DO CALL ECHO %%var%%s%%
GOTO :EOF

This should substitute.
The first FOR sets VARn to "Site Cn FAIL" for n=1 to 6.
The next FOR interprets the output of ARP, filtered for "static" The caret (^) before the pipe tells batch that the pipe is part of the command, not the FOR.
The neste FOR loops through the strings 192.168.0.1`` to192.168.0.16and if that matches the first token from theARPoutput (in%%A)  then the appropriate variable is set to...Match`
Finally, the contents of var1..var6 are echoed.
There appears to be no reason for token 3, since %%B would only ever be "static", given your filter. Equally, space is a defult delimiter and none of the other defaults would occur in an ARP output line as fitered.


text:
Q: Cannot use list as a function parameter in Python I have a function like this. For *args I want to use a list of different Excel tables.
def my_function(*args):
    for x in args:
        # some code

I use this to get the full paths to the tables and make a list of them. There are only tables in the folder I want to use.
cust_tables = os.listdir(r"my_folder")
cust_path = [r"my_folder" + "\\" + x for x in cust_tables]

This creates a list like this:
['C:\\some\\path\\to\\my\\table_1.xlsx', 'C:\\some\\path\\to\\my\\table_2.xlsx']

When I try to call the function my_function(cust_path), I get this error:
File "C:\Users\my.name\AppData\Local\Continuum\anaconda3\lib\genericpath.py", line 30, in isfile
    st = os.stat(path)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not list

I can call the function when using my_function(cust_path[0],cust_path[1]).
Where did I make a mistake?

A: You need to unpack the list elements when passing as arguments. You can use the splat (*) operator:
my_function(*cust_path)

otherwise, when you do my_function(cust_path), it is passing the whole list as argument; so, args will be a one element tuple containing the list i.e. args will be ([<cust_path_elements ...>],).


text:
Q: Npgsql EF Core (.NET 6) is extremely slow (EF Core + Postgres, Database-First) There is a problem with queries to existing Postgres database using Npgsql EF Core (.NET 6). Even simple EF queries are extremely slow (from 25  sec to several minutes for big expressions). At the same time generated SQL code executes in 20-50 milliseconds. Database is a little bit ugly and not very normalized, but SQL queries execute quite quickly. Also (if it is important) db is not big, smth abount 40.000 rows in some biggest tables.
Here is simple EF query, it takes 24 seconds:
var list = await context.SomeObjects
            .Include(x => x.FirstJoinedEntity)
            .Include(x => x.SecondJoinedEntity)
            .Include(x => x.ThirdJoinedEntity)
            .ToListAsync();

It generates quite simple SQL and it takes about 160 ms to load all rows:
SELECT "A lot of columns"
FROM some_object AS o
     LEFT JOIN first AS f ON o.id = f.object_id
     LEFT JOIN second AS s ON o.id = s.object_id
     LEFT JOIN third AS t ON o.id = t.object_id

Very simple and fast.
Is there any profiler which can show what exactly takes a lot of time in EF Core Npgsql? Or any way how to just understand why EF Core slows so much? I can't change it to code-first and recreate database, but tried Npgsql command to autogenerate Context and all entities for exisiting database to match all Postgres -> C# types:
dotnet ef dbcontext scaffold "Host=my_host;Database=my_db;Username=my_user;Password=my_pw" Npgsql.EntityFrameworkCore.PostgreSQL

But it didn't help: result is the same.
The question is how to diagnose reason of that problem.


text:
Q: Adding image in matplotlib plot creates blank output showing only axis I have been trying to add an image to my matplotlib plot. The image is a legend of my plot. My original graph has too many plots within so, I tried to generalise the legend to make it easy for the eye.
Though I could export the image to matplotlib, I notice that the attached script plots data along with the legend(image) in one window and also opens another blank plot showing only the axis.
What am I doing wrong?
Feel free to add any image of your choice for testing.
`
import matplotlib.pyplot as plt
import numpy as np
import csv
import matplotlib.image as image

axes = plt.gca()

im = image.imread('plot/minPlot/legend.png')
fig, ax = plt.subplots()
ax.imshow(im,aspect='auto', extent=(3,5,2,3), zorder=-1)

plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('')

x1, y1 = [-1,12],[1,4]
x2, y2 = [1,10],[3,2]
plt.plot(x1,y1,x2,y2,marker='o')

plt.show()

`

A: As @DavidG posted, the
'axes = plt.gca()' was causing an additional empty plot. I used the plt.gca() for setting the limits of the x,y axis. After going through https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.ylim.html, I can directly call the xlim and ylim functions from the plt class. So, I can get rid of plt.gca() call.


text:
Q: Find number(s) from current excel file in other excel and copy the row to current excel file I have some numbers in column H from the range H4 to H40. The range and numbers may vary, sometimes there could be 1 or two number sometimes it may be 5, 7, 10, 15. etc.
I want to find those numbers in another excel file and copy that entire row in current sheet. The numbers will be on different rows but I want to copy only those rows which has the number.
Is there any VBA code to do this? The numbers are of around 10 digits or less.

A: Let us assume that you have two files in this situation File-1 and File-2
See screenshot below.  Assume that File-1 has all the information you need

Let us say that File-2 has your numbers ( I have assumed UNIQUE 10 digit numbers)

Now if you have to bring in the row content of say the first row (which would be TOM, 15, M, you should use the VLOOKUP command.
In the cell adjacent to 123456789 enter the following formula
=VLOOKUP(B3,[Book1]Sheet1!$B$3:$E$9,2,0)
If we breakdown this formula
VLOOKUP - This is the lookup function
B3      - The location(cell address) of the data 123456789
[Book1]Sheet1!$B$3:$E$9  - This has two parts.

*

*The [Book1] refers to the name of File-1 in which there is data.

*The Sheet1!$B$3:$E$9 - refers to the Sheet name ( Sheet 1 in this case) and the range in which the data is present (starting from B3 to E9)

2 refers to the column number from the first cell in the range
0 means exact match.
In the end, my File-2 will look like this with the formula.


text:
Q: Tabbed forms - multi line text boxes I have converted my forms to tabs by following the informations as described here: http://www.markrackley.net/2015/12/03/tabify-your-sharepoint-forms/
This works fine however for multi line text boxes (not plain text) the value in the field doesn't show up on the edit form. It shows up on the display form. If I change the multi line text boxes to plain text then the value shows up but I want the field to be rich text so this isn't an option.
Can anyone help?

A: for the love of god DO NOT USE HILLBILLY!!!! its buggy as hell, had a third party put it in and was put all over the place. Client was angry why they could only multi select more than 2 items at a time, the Ribbon area breaks when no item is selected and more than one item is selected. After i looked into it... its a bug in hillbilly tabbing that is still an issue 3 years later and the creator said he isnt going to look into it.
So I changed the code to JqueryUI (https://jqueryui.com/tabs/) which is far more stable and everything works as it should by a reputable company. hillbilly is a big no no in my eyes and your asking for trouble unless you feel like going into the code and re-engineering his code to fix the async issues.
lol when i explain the issues and the client can only focus on the name and said "if we knew they were going to use some 3rd party code with that name we would of never excepted".
EDIT
you need to add all the webparts to the page. In the ribbon click on HTML to look at the code. Now copy all the code and put it in a code editor. seperate each webpart code (between webparts its usually separated by
 tag). It would look somthing like this:

then copy below and add the code above to it:
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

Nunc tincidunt

Proin dolor

Aenean lacinia

            /*webpart 1 code here*/

             /*webpart 2 code here*/

             /*webpart 3 code here*/

with the webpart code inside it:
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

Nunc tincidunt

Proin dolor

Aenean lacinia

             /*webpart 2 code here*/

             /*webpart 3 code here*/

repeat for each webpart. sometimes it doesn't work. That's because you need to load the script stuff and JS stuff beforehand so you can put this:
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

inside a script editor webpart.


text:
Q: Magento Error log record number: 508673659403 I have just installed Magento 1.9.0.1 and i am getting the below error Any Help?
There has been an error processing your request
Exception printing is disabled by default for security reasons.
Error log record number: 508673659403

A: I realized the issue was with my browser cache. I switched to a different browser and it worked. You can also clear your browser cache and use the same browser.


text:
Q: Polynomial multiplication If a function Q(x) only has integer coefficients and has factors : f1(x),f2(x),... fn(x). Can the functions f1(x),f2(x),... and fn(x) necessarily have integer coefficients?
Gaussian integers are fine for functions with complex roots.

A: The literal answer to your question is "of course not".  For example, $x^2-1$ has integer coefficients but we can factorise it as
$$x^2-1=(71x-71)({\textstyle\frac{1}{71}}x+{\textstyle\frac{1}{71}})\ ,$$
and the second factor does not have integer coefficients.  But the point here is that we are just deliberately making things difficult, and we could adjust this by taking $71$ out of the first factor and putting it into the second,
$$x^2-1=(x-1)(x+1)\ ,$$
so that we have factors with integer coefficients.
If a polynomial with integer coefficients is factorised as a product of polynomials with rational coefficients, then the factorisation can always be adjusted in a similar way: this is a corollary of Gauss' Lemma.


text:
Q: Google Earth Network Link with Fusion Heat Map So I have created a heat map in Fusion Tables, obtained a API key and copied the code into the link in Google Earth Network Link add.  I did not get the resulting heat map to populate in Google Earth.  I've set the sharing to Public and Unlisted but neither bears any fruit.  Can anyone tell me what steps I am missing to get the heat map to populate in Google Earth?
Here is my obtained code (XXX'd out my API key)
   <!DOCTYPE html>

<meta name="viewport"></meta>
<title>Copy of Heat Map - Google Fusion Tables</title>


text:
Q: Abort asynchronous function from background proccess I have an asynchronous function that I would like to abort from a process that is running in the background.
The abortion does not need to cancel any promises that are currently pending inside of the asynchronous function.
It just needs to make the function return and prevent any further lines from getting executed.
How could I do this?
The current code does not work because the error is thrown inside setInterval instead of the try block.

setInterval(() => { //background proccess
  abort();
}, 5000);

async function func() {
  try {
    abort = function thr() {
      throw new Error("dsaf");
    };
    await new Promise((r) => setTimeout(r, 10000));
    await new Promise((r) => setTimeout(r, 10000));
    await new Promise((r) => setTimeout(r, 10000));
    await new Promise((r) => setTimeout(r, 10000));
    await new Promise((r) => setTimeout(r, 10000));
    await new Promise((r) => setTimeout(r, 10000));
    await new Promise((r) => setTimeout(r, 10000));
  } catch {
    console.log("caught");
  }
}

func()

Update: Are there other languages that support this type of pattern better or are all languages like this?

A: You're probably looking for
let throwIfAborted = () => {};

setInterval(() => { //background proccess
  throwIfAborted = () => { throw new Error("Abort"); };
}, 5000);

async function func() {
  try {
    throwIfAborted();
    await new Promise((r) => setTimeout(r, 10000));
    throwIfAborted();
    await new Promise((r) => setTimeout(r, 10000));
    throwIfAborted();
    await new Promise((r) => setTimeout(r, 10000));
    throwIfAborted();
    await new Promise((r) => setTimeout(r, 10000));
    throwIfAborted();
    await new Promise((r) => setTimeout(r, 10000));
    throwIfAborted();
    await new Promise((r) => setTimeout(r, 10000));
    throwIfAborted();
    await new Promise((r) => setTimeout(r, 10000));
    throwIfAborted();
  } catch {
    console.log("caught");
  }
}

func()

A: To make life easier, you could create a helper function.
Below I've created a simple abortable function, all you do then is put your async code inside a run, and then call abort when your ready.
eg.

const sleep = ms => new Promise(r => setTimeout(r, ms));

function abortable() {
  let aborted = false;
  return {
    abort: () => aborted = true,
    run: async cb => {
      if (aborted) throw new Error('Aborted');
      return await cb();
    }
  }
}

async function hello(caption, ms) {
  await sleep(ms);
  return `Ran ${caption}`;
}

const {abort, run} = abortable();
setTimeout(() => abort(), 2000);

async function test() {
  try {
    console.log(await run(() => hello('One', 1500)));
    console.log(await run(() => hello('Two', 1500)));
    //this next one should not run, as it's over 2000ms
    console.log(await run(() => hello('Three', 1500)));
  } catch (e) {
    console.log(e.message);
  }
}

test();

Using generators, like in @Dmitriy's answer with CPromise's looks nice, only slight problem is that if the return value from the previous one is required for the next.  A simple solution here though is use some form of state and pass that to each function.
Below is an example using generators, but without any 3rd party lib.

const sleep = ms => new Promise(r => setTimeout(r, ms));

function abortable() {
  let aborted = false;
  return {
    abort: () => aborted = true,
    run: async p => {
      for (const r of p()) {
        if (aborted) throw new Error('aborted');
        console.log(await r);
      }
    }
  }
}

async function hello(state, value, ms) {
  await sleep(ms);
  state.total += value;
  return `Total ${state.total}`;
}

const {abort, run} = abortable();
setTimeout(() => abort(), 2000);

run(function *() {
  const state = {total: 0};
  yield hello(state, 5, 1500);
  yield hello(state, 10, 1500);
  yield hello(state, 15, 1500);
}).catch(e => console.log(e.message));

A: Using the CPromise package, this can be done as follows (Live sandbox):
import { CPromise } from "c-promise2";

const func = CPromise.promisify(function* () {
  try {
    yield new Promise((r) => setTimeout(r, 10000));
    yield new Promise((r) => setTimeout(r, 10000));
    yield new Promise((r) => setTimeout(r, 10000));
    yield new Promise((r) => setTimeout(r, 10000));
    yield new Promise((r) => setTimeout(r, 10000));
    yield new Promise((r) => setTimeout(r, 10000));
    yield new Promise((r) => setTimeout(r, 10000));
  } catch (err) {
    console.log(`caught: ${err}`);
  }
});

const promise = func();

setInterval(() => {
  promise.cancel();
}, 5000);


text:
Q: How to use CMU Sphinx speech recognition with Ruby application? I'm searching for how to use CMU Sphinx with Ruby (Rails) application. I need very simple task - I have an mp3 file and I want get it transcribed into text.
How can I implement this easiest way? I dont' know C/C++ and my task isn't so big to learn C/C++ for it :)
Thanks for help!

A: I've recently created a gem for doing just this:
https://github.com/watsonbox/pocketsphinx-ruby
It uses the Ruby Foreign Function Interface (FFI) to interact directly with libpocketsphinx.

A: CMUSphinx provides several interfaces you can use to leverage speech recognition features. Some of them might be more suitable for you, some less:

*

*Use command-line tools and execute them as an external binaries from Rails application to obtain the required results. The tool to execute is pocketsphinx_continuous. For more information on how to invoke binaries from Rails see the question:
how to execute binary on heroku?

*You can invoke Sphinx4 framework from JRuby using JVM, see for example on how to use Sphinx4 from JRuby: http://cmusphinx.sourceforge.net/wiki/tutorialsphinx4#writing_scripts

*You can implement the pocketsphinx bindings using SWIG. The easy part is that the swig wrappers for Python already exist as a part of the pocketsphinx, you just need to use SWIG to generate Ruby wrappers: https://sourceforge.net/p/cmusphinx/code/11643/tree/trunk/pocketsphinx/swig/

*Finally, you can implement a REST web using Java REST frameworks to convert audio to text using CMUSphinx tools and invoke the sevice from your Ruby code. For more information see information how to use REST from Rails
This way your can make your system really scalable.

A: Maybe look into this Ruby-based speech recognition web service that uses PocketSphinx:
https://github.com/alumae/ruby-pocketsphinx-server


text:
Q: Using substring function within the convert function in SQL Server SQL Server: can I convert a varchar into substring and then convert to datetime to compare with a datetime range in a single SQL query?
I need this in the where clause

A: Technically speaking, no - you can't convert something to a substring because that is not a datatype. You can however convert a varchar to a datetime, by utilizing substring if you need to.
Take the following example
myStringWithDate
------------------------------
'This date, 2015-01-01 08:00:00, is...'

SELECT * FROM myTable
WHERE getDate() <= CAST(SUBSTRING(myStringWithDate, 12, 19) AS DateTime)

In this example, substring will return '2015-01-01 08:00:00' and then cast this to datetime to compare against getDate() (system current DateTime).
I hope I counted the substring correctly. Couldn't verify it, but it should be correct.

A: It can be done. T-Sql allows you to nest the SUBSTRING function within a CAST or CONVERT function.
The best way to compare ranges is with two conditions comparing the beginning and end of the range.
Here is some test data:
Create Table VarCharDateTest --Create Table with dates embedded in a varchar string
(
vID int identity(1,1),
vDate varchar(50)
)
GO

INSERT INTO VarCharDateTest --Insert Test Values
VALUES
('The Date is 04/18/2015, a Saturday'),
('The Date is 04/19/2015, a Sunday'),
('The Date is 04/20/2015, a Monday'),
('The Date is 04/21/2015, a Tuesday')
GO

CREATE TABLE DatetimeTest --Create table with dates stored as datetime
(
dID int identity(1,1),
dDate datetime
)
GO

INSERT INTO DateTimeTest --Insert Test Values
VALUES
('4/12/2015'),
('4/13/2015'),
('4/14/2015'),
('4/15/2015'),
('4/16/2015'),
('4/17/2015'),
('4/18/2015'),
('4/19/2015'),
('4/20/2015'),
('4/21/2015'),
('4/22/2015'),
('4/23/2015')
GO

DECLARE @startDate datetime = '2015-04-18 00:00:00.000'
DECLARE @endDate datetime = '2015-04-21 00:00:00.000'

SELECT
    dID,
    dDate,
    vID,
    vDate,
    cast(Substring(vDate, 12,11) as datetime) as DateConvertedFromVarchar  --explicit conversion to datetime
FROM
    DatetimeTest
INNER JOIN
    VarCharDateTest
    ON dDate = cast(Substring(vDate, 12,11) as datetime)
WHERE
    cast(Substring(vDate, 12,11) as datetime) > @startDate AND
    cast(Substring(vDate, 12,11) as datetime) < @endDate


text:
Q: iPad/iPod: autoRotate resizes view in window Developing an iPad interface, I have a scenario where I have a UIViewController which manages a view that gets placed directly as a subview of the main UIWindow.
Before being placed in the UIWindow, that view gets resized to a non-standard size, let's say, 768x460, and positioned at the bottom of the screen.
When rotating the device, the autoRotate feature of the UIViewController causes the view to be resized so that it fills the entire UIWindow space.
I thought this might be because in the XIB, the view is set to window size, but when I changed it to reflect the desired size, it still expanded it to the window size.
Then I went into the MainWindow XIB and turned off autoresizeSubviews, and it still happens.
This is a very frustrating problem, I am hoping that there is merely something obvious that I am missing out on.
Anyone have any bright ideas?
Code by request:
browseController = [[BrowseController alloc] initWithNibName:@"BrowseController" bundle:nil];

[[browseController view] setFrame:CGRectMake(0, 544, 768, 460)];

[window addSubview:[browseController view]];

A: IF you are in interface builder, click on the size tab when you are editing the view.  Under "autosizing" click on all the red arrows so that they disappear.  You do not want any red arrows there.  Or in code you can do the following:
browseController.autoresizingMask = UIViewAutoresizingNone;

A: What about springs and struts? (aka autoresizingMask) See here.  In code you might need the extra line
[[browseController view] setAutoresizingMask:UIViewAutoresizingNone];

A: Not enough info from your question, but this is usually the problem (so I'm making an educated guess) :
Apple states that only ONE UIView should exist in the UIWindow at root level - if there's more than one, a lot of behaviour is undefined. Often there's an extra one you didn't notice was there / forgot about from weeks ago.
In practice, I've found that when there's "more than one", a lot of these rotation bugs occur, where Apple's code gets confused, and starts randomly re-positioning things.
Standard workaround:

*

*In every app you ever make

*...always have a single, empty, "MyRootViewController" which you add to the UIWindow

*...then add as many views as you want as subviews inside it

(because Apple's strange bugs only affect the UIWindow itself - all subviews work "as expected")

A: I just had this problem, and here's how I fixed it:
Make sure you've defined a view controller for the view that you're attaching to the top level of the window. If you don't, layout will go crazy on you.


text:
Q: Conflict for org.eclipse.ui.window.newEditor Once I relaunch the RCP application I am getting this warning message (Error Log)-
Conflict for 'org.eclipse.ui.window.newEditor':HandlActivation...
as shown in the image-

What can be the reason of the same.

A: are you using e4 or 3.*.
if you are using e4, can easily check conflict using application editor(SHIFT+ ALT + F9) window.


text:
Q: Using sed command,replace line ,but not the matching pattern I know the replace command
sed -i 's/First/Second/' testFile

will replace the string "First" with "Second".
But given an input as shown below,
Infile.txt

First "This line is to be deleted."

I want the output to be like this:
Outfile.txt

First "New string to be added."

i.e. "First" should not be replaced.
How do I achieve this desired output?

A: You can specify the address for the substitution command:
sed -i '/First/s/This line is to be deleted/New string to be added/' testFile

Edit: for a variable pattern string:
sed -i 's/First \(.*\)/First "New string to be added"/' testFile


text:
Q: Datepicker is required in php form with hidden input field I'm creating a php form to post data. One of the elements is a Datepicker JS element. I pass the input from the datepicker to a hidden input field. Now I want this datepicker to be required. If I make the input field required it doesn't seems to work because it's hidden, and it must stay hidden. Anyone know the best way to do this?
The code:

    Datum geselecteerd:
    <input type="hidden" id="datefield" name="date" required/>

A: you can use .submit() in jquery which is called when form is submitted and you can check if date field is filled.
For more info here: https://api.jquery.com/submit/
Also you should check it with php where you process the data the form sent you and if it is not filled you should send user back to fill the form again with a warning that he didnt fill a field
example:
<form id="myform" action="" method="get">
<input type="hidden" id="datefield" name="date" />
<input type="submit" />
</form>


text:
Q: How to send an email on a private telekom smtp? I want send an email automatically, but i get this error message:
"Connection unexpectedly closed: [Errno 104] Connection reset by peer"
I tried a few smtp server methode, but it can't work.
My code is here:
fromaddr = "test@gmail.com"
toaddr = "test2@gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "test"
body = "Test"
msg.attach(MIMEText(body, 'plain'))
#server = smtplib.SMTP('smtp.example.com', 25)
server = smtplib.SMTP_SSL('mail.dt-one.com', 443)
#server.connect("mail.t-online.hu",2525)
server.ehlo()
server.starttls()
server.ehlo()
server.login('myuser','mypassword')
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()


text:
Q: Connecting two computer via socket, in c and on linux I have made a sever in C and can comunicate with it via telnet (telnet localhost 8000), it work as intend on my computer.
I would like to work from an other computer, connected on the same network. I tried puting the public ip and host , found on www.myip.com in place of the localhost but it didn't work.
here is my sever.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>

#define PORT "8000" // the port users will be connecting to

#define BACKLOG 10 // how many pending connections queue will hold

void sigchld_handler(int s)
{
    // waitpid() might overwrite errno, so we save and restore it:
    int saved_errno = errno;

    while (waitpid(-1, NULL, WNOHANG) > 0)
        ;

    errno = saved_errno;
}

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET)
    {
        return &(((struct sockaddr_in *)sa)->sin_addr);
    }

    return &(((struct sockaddr_in6 *)sa)->sin6_addr);
}

int main(void)
{
    int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    struct sigaction sa;
    int yes = 1;
    char s[INET6_ADDRSTRLEN];
    int rv;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0)
    {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for (p = servinfo; p != NULL; p = p->ai_next)
    {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                             p->ai_protocol)) == -1)
        {
            perror("server: socket");
            continue;
        }

        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
                       sizeof(int)) == -1)
        {
            perror("setsockopt");
            exit(1);
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
        {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    freeaddrinfo(servinfo); // all done with this structure
    if (p == NULL) {
        fprintf(stderr, "server: failed to bind\n");
        exit(1);
    }
    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }
    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }
    printf("server: waiting for connections...\n");
    while (1)
    { // main accept() loop
        sin_size = sizeof their_addr;
        new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if (new_fd == -1)
        {
            perror("accept");
            continue;
        }

        inet_ntop(their_addr.ss_family,
                  get_in_addr((struct sockaddr *)&their_addr),
                  s, sizeof s);
        printf("server: got connection from %s\n", s);
        char myBuff[200];
        if (!fork())
        {
            while (1) {
            memset(myBuff, 0, 200);
            close(sockfd); // child doesn't need the listener
            if (send(new_fd, "Hello!\n", 8, 0) == -1)
                perror("send");
            recv(new_fd, myBuff, 200, 0);
            printf("%s", myBuff);
            }
        }
        close(new_fd); // parent doesn't need this
    }
    return 0;
}

A: I think that your problem is not with the code itself, but it's more a networking problem...
First of all, I would check that your server is listening on all addresses by running netstat -ln | grep 8000. If it returns a specific address (for instance, 192.168.0.176:8000) then that's the IP that you should connect to. But as you already connected from localhost, I guess that you'll find something like 0.0.0.0:8000 or *:8000 (I don't remember the exact format now in linux).
If the IP you found is 0.0.0.0 and you want to connect from a computer in the same local network, you shouldn't use the public IP because that's the IP of your router (in fact, you can check that the public IP for both computers will probably be the same because they share the router). Doing it this way is possible but it will most likely require port forwarding so that the router knows to which IP should it send connections attempts for port 8000.
You should execute ifconfig | grep "inet " in your server. That will return you a list of the IP addresses the server is listening on. If you execute the same command in the client, you will find at least one of them that is very similar (for instance, 192.168.0.176 in the server and 192.168.0.178 in the client). Then, you should try to use the IP address you found in the server in the telnet command.
If that doesn't work, most likely the firewall in the server is blocking connections to that port in the server. You should try to open that port and check again.


text:
Q: Visualforce - Show PageBlockSection upon CommandButton Click I have a VF page with a custom Extension controller that creates a task or series of tasks on a button click from the Contact page. Users have the ability to create an initial task then a follow up or another un-related task.  The issue I am running into is when a user creates an initial task and a follow-up and then creates another un-related task, the follow-up task previously created gets cloned.  I want the un-related task to not have a follow-up task until/if the user decides they want one.  Any ideas on how to handle?
Controller:
public with sharing class RDATasks{

    public list<Task> listTask{get;set;}
    public list<Task> listTaskFollow{get;set;}
    public integer n;

    Set<Task>Tasks = new Set<Task>();
    Set<Task>FollowTasks = new Set<Task>();

    private final Contact con;
    public RDATasks(ApexPages.StandardController myController){
        listTask = new List<Task>();
        listTaskFollow = new List<Task>();
        con=(Contact)myController.getRecord();
    }

//  Adds RDA Task to list
    public void RDA()
    {
        listTask.add(new Task(
           WhoId = con.Id,
           Status = 'Completed',
           ActivityDate = system.TODAY(),
           Subject = '',
           Description = '',
           OwnerId = UserInfo.getUserId(),
           WhatId = con.AccountId,
           RDA__c = TRUE,
           FollowUp__c = FALSE)
           );
    }

//  Adds RDA Follow-Up Task to list
    public void RDAfollow()
    {
        n=listTask.size() - 1;
        listTask[n].FollowUp__c = FALSE;
        listTaskFollow.add(new Task(
           WhoId = con.Id,
           Status = 'In Progress',
           ActivityDate = system.TODAY()+7,
           Subject = 'Follow-Up: '+listTask[n].Subject,
           OwnerId = UserInfo.getUserId(),
           WhatId = con.AccountId,
           RDA__c = TRUE,
           FollowUp__c = TRUE)
           );
    }

//  Saves list of RDA Tasks added
    public PageReference saveTask(){
        insert listTask;
        insert listTaskFollow;

        if(!listTaskFollow.isEmpty()){
            Tasks.addAll(listTask);
            FollowTasks.addAll(listTaskFollow);
        if(!Tasks.containsAll(FollowTasks)){
            integer last = listTaskFollow.size();
            listTask.add(listTaskFollow[last]);
        }
        }
        RDAfollow();
            {
            PageReference contactPage = new PageReference('/' + con.Id);
            contactPage.setRedirect(true);
            return contactPage;
            }
    }
}

VF Page:
<apex:page standardController="Contact" tabStyle="Contact" sidebar="false" extensions="RDATasks" action="{!RDA}">

<apex:form >

<apex:sectionHeader title="Revenue Driving Activities"/>
<apex:repeat value="{!listTask}" var="tsk">
    <apex:pageBlock >
        <apex:pageBlockSection title="Main RDA">
            <apex:outputField value="{!Contact.Account.Name}" label="Related To"/>
            <apex:outputField value="{!Contact.Name}" label="Name"/>
            <apex:inputField value="{!tsk.Type_of_RDA__c}" style="width:35%"/>
            <apex:inputField value="{!tsk.Subject}" style="width:45%"/>
            <apex:inputField value="{!tsk.Type_Detail__c}" style="width:35%"/>
            <apex:inputField value="{!tsk.ActivityDate}" style="width:35%"/>
            <apex:inputField value="{!tsk.Status}" />
            <apex:inputField value="{!tsk.Description}" style="width:100%"/>
            <apex:commandButton value="Add Follow Up RDA" action="{!RDAfollow}"/>
        </apex:pageBlockSection>

<apex:repeat value="{!listTaskFollow}" var="tskF">
        <apex:pageBlockSection title="Follow-Up RDA">
            <apex:outputField value="{!Contact.Account.Name}" label="Related To"/>
            <apex:outputField value="{!Contact.Name}" label="Name"/>
            <apex:inputField value="{!tskF.Type_of_RDA__c}" style="width:35%"/>
            <apex:inputField value="{!tskF.Subject}" style="width:45%"/>
            <apex:inputField value="{!tskF.Type_Detail__c}" style="width:35%"/>
            <apex:inputField value="{!tskF.ActivityDate}" style="width:35%"/>
            <apex:inputField value="{!tskF.Status}" />
            <apex:inputField value="{!tskF.Description}" style="width:100%"/>
        </apex:pageBlockSection>
</apex:repeat>

    </apex:pageBlock>
</apex:repeat>

    <apex:commandButton value="Add Another RDA" action="{!RDA}"/>
    <apex:commandButton value="Remove Last RDA" action="{!removeRDA}"/>
    <apex:commandButton value="Save RDAs" action="{!saveTask}"/>
</apex:form>

</apex:page>


text:
Q: How do I destroy an object in python? I have a timer class, that I designed to fire once, and (optimally) delete itself. Is there a way for me to implement that self-deletion?
class timer:
        def __init__(self, duration, function, args):
            self.duration = duration
            self.function = function
            self.args = args
        def start(self):
            self.time = time.time()
            self.validity = True
        def check(self):
            if(int(self.time)+self.duration < time.time() ):
                self.function(self.args)
                self.validity = False
        def __del__(self):
            print("timer destroyed")

A: You can follow the similar approach.
An object.__del__(self) can be called to destroy an instance.
>>> class Test:
...     def __del__(self):
...         print "deleted"
...
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed
Also, From Python official doc reference:

del x doesn't directly call x.del() — the former decrements the
  reference count for x by one, and the latter is only called when x's
  reference count reaches zero

What you would need in your solution is to use something like del object where the object is the instance that you want to remove.

A: Did you try using None? something like this:
timer = None