问:
akka-http no stack trace or details on error
I got a structure which can basically be summarized as:

outside user makes a rest request to akka-http server

akka-http makes a request(query?) to a (some)data source using asynchttpclient

akka-http transforms the result from asynchttpclient and serves it back to user

At some point I am getting an error from akka which tells me almost nothing. This error happens right after the asynchttpclient returns me some results. (I can infact at this point print the results on the log, they are there parsed from json etc.. but akka had already errored out)

Even in debug logging level I got no decipherable error message from akka or a stacktrace.

only message I got is:

```<code>2017-03-24 17:22:55 INFO  CompanyRepository:111 - search company with name:"somecompanyname"
2017-03-24 17:22:55 INFO  CompanyRepository:73 - [QUERY TIME]: 527ms
[ERROR] [03/24/2017 17:22:55.951] [company-api-system-akka.actor.default-dispatcher-3] [akka.actor.ActorSystemImpl(company-api-system)] Error during processing of request: 'requirement failed'. Completing with 500 Internal Server Error response.
</code>```

This error message is the only thing I get. Relevant parts of my config:

```<code>akka {
  loglevel = "DEBUG"
  # edit --  tested with sl4jlogger with no change
  #loggers = ["akka.event.slf4j.Slf4jLogger"]
  #logging-filter = "akka.event.slf4j.Slf4jLoggingFilter"

  parsing {
    max-content-length = 800m
    max-chunk-size             = 100m
  }
  server {
    server-header = akka-http/${akka.http.version}
    idle-timeout = 120 s
    request-timeout = 120 s
    bind-timeout = 10s
    max-connections = 1024
    pipelining-limit = 32

    verbose-error-messages = on
  }

  client {
    user-agent-header = akka-http/${akka.http.version}
  }

  host-connection-pool {
    max-connections = 4
  }
}

akka.http.routing {
  verbose-error-messages = on
}
</code>```

Anyone knows if I can make akka to spit out more details about what/where the error is occurring?

Edit: <s>I realized I do NOT get this same error on resultsets which are smaller in size.</s> <- ignore

Edit 2:

Added akka.loglevel = DEBUG, spits out a lot more noise but still not detail about the actual error.

Converted asynchttpclient to akka quickly to rule out AHC

I already had a wrapper around my query to time it, added some logging there trying to pinpoint when exactly the error is happening.

```<code>def queryTimer[ R <: Future[ Any ] ]( block: => R ): R = {
  val t0 = System.currentTimeMillis()
  val result = block
  result.onComplete { maybeResult =>
    val t1 = System.currentTimeMillis()
    logger.info( "[QUERY TIME]: " + ( t1 - t0 ) + "ms" )

    maybeResult match {
      case Success(some) =>
        logger.info( "successful feature:")
        logger.info( FormattedString.prettyPrint(some))
      case Failure(someFailure) =>
        logger.info( "failed feature:")
        logger.debug( FormattedString.prettyPrint(someFailure))
    }
  }
  result
}
</code>```

resulting log:

```<code>2017-03-28 13:19:10 INFO  CompanyRepository:111 - search company with name:"some company"
[DEBUG] [03/28/2017 13:19:10.497] [company-api-system-akka.actor.default-dispatcher-2] [EventStream(akka://xca-api-actor-system)] logger log1-Logging$DefaultLogger started
[DEBUG] [03/28/2017 13:19:10.497] [company-api-system-akka.actor.default-dispatcher-2] [EventStream(akka://xca-api-actor-system)] Default Loggers started
[DEBUG] [03/28/2017 13:19:10.613] [company-api-system-akka.actor.default-dispatcher-2] [AkkaSSLConfig(akka://xca-api-actor-system)] Initializing AkkaSSLConfig extension...
[DEBUG] [03/28/2017 13:19:10.613] [company-api-system-akka.actor.default-dispatcher-2] [AkkaSSLConfig(akka://xca-api-actor-system)] buildHostnameVerifier: created hostname verifier: com.typesafe.sslconfig.ssl.DefaultHostnameVerifier@779e2339
[DEBUG] [03/28/2017 13:19:10.633] [xca-api-actor-system-akka.actor.default-dispatcher-3] [akka://xca-api-actor-system/user/pool-master/PoolInterfaceActor-0] (Re-)starting host connection pool to localhost:27474
[DEBUG] [03/28/2017 13:19:10.727] [xca-api-actor-system-akka.actor.default-dispatcher-3] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Resolving localhost before connecting
[DEBUG] [03/28/2017 13:19:10.740] [xca-api-actor-system-akka.actor.default-dispatcher-4] [akka://xca-api-actor-system/system/IO-DNS] Resolution request for localhost from Actor[akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0#-815754478]
[DEBUG] [03/28/2017 13:19:10.749] [xca-api-actor-system-akka.actor.default-dispatcher-4] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Attempting connection to [localhost/127.0.0.1:27474]
[DEBUG] [03/28/2017 13:19:10.751] [xca-api-actor-system-akka.actor.default-dispatcher-4] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Connection established to [localhost:27474]
2017-03-28 13:19:10 INFO  CompanyRepository:73 - [QUERY TIME]: 376ms
2017-03-28 13:19:10 INFO  CompanyRepository:77 - successful feature:
[ERROR] [03/28/2017 13:19:10.896] [company-api-system-akka.actor.default-dispatcher-7] [akka.actor.ActorSystemImpl(company-api-system)] Error during processing of request: 'requirement failed'. Completing with 500 Internal Server Error response.
2017-03-28 13:19:10 INFO  CompanyRepository:78 - SearchResult(List(
( prettyprint output here!!! lots and lots of legit result, json parsed succcesfully into a bunch of case classes)
</code>```

as you can see my logging format and akkas' are different, the ERROR is coming from akka with do details, while everything looks like working.

Edit 3: logs with sleep in between calls

new query timer function with sleeps

```<code>def queryTimer[ R <: Future[ Any ] ]( block: => R ): R = {
  val t0 = System.currentTimeMillis()
  val result = block
  result.onComplete { maybeResult =>
    val t1 = System.currentTimeMillis()
    logger.info( "[QUERY TIME]: " + ( t1 - t0 ) + "ms" )

    maybeResult match {
      case Success(some) =>
        Thread.sleep(500)
        logger.info( "successful feature:")
        Thread.sleep(500)
        logger.info( FormattedString.prettyPrint(some))
        Thread.sleep(500)
        logger.info("we are there!")
      case Failure(someFailure) =>
        logger.info( "failed feature:")
        logger.debug( FormattedString.prettyPrint(someFailure))
    }
  }
  result
}
</code>```

logs with sleeps

```<code>[DEBUG] [03/30/2017 11:11:58.629] [xca-api-actor-system-akka.actor.default-dispatcher-7] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Attempting connection to [localhost/127.0.0.1:27474]
[DEBUG] [03/30/2017 11:11:58.631] [xca-api-actor-system-akka.actor.default-dispatcher-7] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Connection established to [localhost:27474]
11:11:59.442 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:11:59.496 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:00.250 [ForkJoinPool-2-worker-15] INFO  c.s.s.r.neo4j.CompanyRepository - [QUERY TIME]: 1880ms
[ERROR] [03/30/2017 11:12:00.265] [company-api-system-akka.actor.default-dispatcher-3] [akka.actor.ActorSystemImpl(company-api-system)] Error during processing of request: 'requirement failed'. Completing with 500 Internal Server Error response.
11:12:00.543 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:00.597 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:00.752 [ForkJoinPool-2-worker-15] INFO  c.s.s.r.neo4j.CompanyRepository - successful feature:
11:12:01.645 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:01.697 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:01.750 [ForkJoinPool-2-worker-15] INFO  c.s.s.r.neo4j.CompanyRepository - SearchResult(List( "lots of legit result here"
11:12:02.281 [ForkJoinPool-2-worker-15] INFO  c.s.s.r.neo4j.CompanyRepository - we are there!
</code>```

Edit 4 and solution!

Apparently the default exception handler does not print a stack trace! overriding the exception handler with a very basic catch all:

```<code>implicit def myExceptionHandler: ExceptionHandler =
  ExceptionHandler {
    case e: Exception => {
      logger.info("---------------- exception log start")
      logger.error(e.getMessage, e)
      logger.error("cause" , e.getCause)
      logger.error("cause" , e.getStackTraceString )
      logger.info( FormattedString.prettyPrint(e))
      logger.info("---------------- exception log end")
      Directives.complete("server made a boo boo")
      }
  }
</code>```

results in a stack trace that befuddles the sh*t out of me!!

```<code>11:42:04.634 [company-api-system-akka.actor.default-dispatcher-2] INFO  c.stepweb.scarifgate.CompanyApiApp$ - ---------------- exception log start
11:42:04.640 [company-api-system-akka.actor.default-dispatcher-2] ERROR c.stepweb.scarifgate.CompanyApiApp$ - requirement failed
java.lang.IllegalArgumentException: requirement failed
    at scala.Predef$.require(Predef.scala:212) ~[scala-library-2.11.8.jar:na]
    at spray.json.BasicFormats$StringJsonFormat$.write(BasicFormats.scala:121) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.BasicFormats$StringJsonFormat$.write(BasicFormats.scala:119) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.ProductFormats$class.productElement2Field(ProductFormats.scala:46) ~[spray-json_2.11-1.3.2.jar:na]
    at com.stepweb.scarifgate.services.CompanyService.productElement2Field(CompanyService.scala:14) ~[classes/:na]
    at spray.json.ProductFormatsInstances$$anon$3.write(ProductFormatsInstances.scala:73) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.ProductFormatsInstances$$anon$3.write(ProductFormatsInstances.scala:68) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.PimpedAny.toJson(package.scala:39) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.CollectionFormats$$anon$1$$anonfun$write$1.apply(CollectionFormats.scala:26) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.CollectionFormats$$anon$1$$anonfun$write$1.apply(CollectionFormats.scala:26) ~[spray-json_2.11-1.3.2.jar:na]
    at scala.collection.immutable.List.map(List.scala:273) ~[scala-library-2.11.8.jar:na]
    at spray.json.CollectionFormats$$anon$1.write(CollectionFormats.scala:26) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.CollectionFormats$$anon$1.write(CollectionFormats.scala:25) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.ProductFormats$class.productElement2Field(ProductFormats.scala:46) ~[spray-json_2.11-1.3.2.jar:na]
    at com.stepweb.scarifgate.services.CompanyService.productElement2Field(CompanyService.scala:14) ~[classes/:na]
    at spray.json.ProductFormatsInstances$$anon$1.write(ProductFormatsInstances.scala:30) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.ProductFormatsInstances$$anon$1.write(ProductFormatsInstances.scala:26) ~[spray-json_2.11-1.3.2.jar:na]
    at akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport$$anonfun$sprayJsonMarshaller$1.apply(SprayJsonSupport.scala:62) ~[akka-http-spray-json_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport$$anonfun$sprayJsonMarshaller$1.apply(SprayJsonSupport.scala:62) ~[akka-http-spray-json_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anonfun$compose$1$$anonfun$apply$15.apply(Marshaller.scala:73) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anonfun$compose$1$$anonfun$apply$15.apply(Marshaller.scala:73) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.GenericMarshallers$$anonfun$optionMarshaller$1$$anonfun$apply$1.apply(GenericMarshallers.scala:19) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.GenericMarshallers$$anonfun$optionMarshaller$1$$anonfun$apply$1.apply(GenericMarshallers.scala:18) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.PredefinedToResponseMarshallers$$anonfun$fromStatusCodeAndHeadersAndValue$1$$anonfun$apply$5.apply(PredefinedToResponseMarshallers.scala:58) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.PredefinedToResponseMarshallers$$anonfun$fromStatusCodeAndHeadersAndValue$1$$anonfun$apply$5.apply(PredefinedToResponseMarshallers.scala:57) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anonfun$compose$1$$anonfun$apply$15.apply(Marshaller.scala:73) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anonfun$compose$1$$anonfun$apply$15.apply(Marshaller.scala:73) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.ToResponseMarshallable$$anonfun$1$$anonfun$apply$1.apply(ToResponseMarshallable.scala:29) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.ToResponseMarshallable$$anonfun$1$$anonfun$apply$1.apply(ToResponseMarshallable.scala:29) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.GenericMarshallers$$anonfun$futureMarshaller$1$$anonfun$apply$3$$anonfun$apply$4.apply(GenericMarshallers.scala:33) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.GenericMarshallers$$anonfun$futureMarshaller$1$$anonfun$apply$3$$anonfun$apply$4.apply(GenericMarshallers.scala:33) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.util.FastFuture$.akka$http$scaladsl$util$FastFuture$$strictTransform$1(FastFuture.scala:41) ~[akka-http-core_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.util.FastFuture$$anonfun$transformWith$extension1$1.apply(FastFuture.scala:51) [akka-http-core_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.util.FastFuture$$anonfun$transformWith$extension1$1.apply(FastFuture.scala:50) [akka-http-core_2.11-10.0.0.jar:10.0.0]
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32) [scala-library-2.11.8.jar:na]
    at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply$mcV$sp(BatchingExecutor.scala:91) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply(BatchingExecutor.scala:91) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply(BatchingExecutor.scala:91) [akka-actor_2.11-2.4.16.jar:na]
    at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:72) [scala-library-2.11.8.jar:na]
    at akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:90) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:39) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:415) [akka-actor_2.11-2.4.16.jar:na]
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) [scala-library-2.11.8.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) [scala-library-2.11.8.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [scala-library-2.11.8.jar:na]
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [scala-library-2.11.8.jar:na]
11:42:04.640 [company-api-system-akka.actor.default-dispatcher-2] ERROR c.stepweb.scarifgate.CompanyApiApp$ - cause
11:42:04.641 [company-api-system-akka.actor.default-dispatcher-2] ERROR c.stepweb.scarifgate.CompanyApiApp$ - cause
11:42:04.644 [company-api-system-akka.actor.default-dispatcher-2] INFO  c.stepweb.scarifgate.CompanyApiApp$ - java.lang.IllegalArgumentException: requirement failed
11:42:04.644 [company-api-system-akka.actor.default-dispatcher-2] INFO  c.stepweb.scarifgate.CompanyApiApp$ - ---------------- exception log end
</code>```

so... the exception is caused here in spray.json.BasicFormats

```<code>implicit object StringJsonFormat extends JsonFormat[String] {
  def write(x: String) = {
    require(x ne null)    // <-----------------------------------
    JsString(x)
  }
  def read(value: JsValue) = value match {
    case JsString(x) => x
    case x => deserializationError("Expected String as JsString, but got " + x)
  }
}
</code>```

which sort of means one of the strings in this thousands of lines of response is null. Special thanks goes to the laziness of using that "require" without a message. Debugging which string is empty where will be a nightmare but I still think akka should fail in a better way.

答:
akka-http no stack trace or details on error

Well, default akka-http ExceptionHandler doesn't print stack trace and prints only error message or its class name if the message is empty but you can provide custom exception handler that will print anything you want (i.e. stack trace in your example).

Some examples of how to make a custom exception handler are provided at GitHub ExceptionHandlerExamplesSpec.spec

The simplest way in your case seems to be to define your own custom implicit exception handler

  import akka.http.scaladsl.model._
  import akka.http.scaladsl.server._
  import StatusCodes._
  import Directives._

  implicit def myExceptionHandler: ExceptionHandler =
    ExceptionHandler {
      case NonFatal(e) =>
          logger.error(s"Exception $e at\n${e.getStackTraceString}")
          complete(HttpResponse(InternalServerError, entity = "Internal Server Error"))
        }
    }
```

Body:
I got a structure which can basically be summarized as:

outside user makes a rest request to akka-http server

akka-http makes a request(query?) to a (some)data source using asynchttpclient

akka-http transforms the result from asynchttpclient and serves it back to user

At some point I am getting an error from akka which tells me almost nothing. This error happens right after the asynchttpclient returns me some results. (I can infact at this point print the results on the log, they are there parsed from json etc.. but akka had already errored out)

Even in debug logging level I got no decipherable error message from akka or a stacktrace.

only message I got is:

2017-03-24 17:22:55 INFO  CompanyRepository:111 - search company with name:"somecompanyname"
2017-03-24 17:22:55 INFO  CompanyRepository:73 - [QUERY TIME]: 527ms
[ERROR] [03/24/2017 17:22:55.951] [company-api-system-akka.actor.default-dispatcher-3] [akka.actor.ActorSystemImpl(company-api-system)] Error during processing of request: 'requirement failed'. Completing with 500 Internal Server Error response.

This error message is the only thing I get. Relevant parts of my config:

akka {
  loglevel = "DEBUG"
  # edit --  tested with sl4jlogger with no change
  #loggers = ["akka.event.slf4j.Slf4jLogger"]
  #logging-filter = "akka.event.slf4j.Slf4jLoggingFilter"

  parsing {
    max-content-length = 800m
    max-chunk-size             = 100m
  }
  server {
    server-header = akka-http/${akka.http.version}
    idle-timeout = 120 s
    request-timeout = 120 s
    bind-timeout = 10s
    max-connections = 1024
    pipelining-limit = 32

    verbose-error-messages = on
  }

  client {
    user-agent-header = akka-http/${akka.http.version}
  }

  host-connection-pool {
    max-connections = 4
  }
}

akka.http.routing {
  verbose-error-messages = on
}

Anyone knows if I can make akka to spit out more details about what/where the error is occurring?

Edit: <s>I realized I do NOT get this same error on resultsets which are smaller in size.</s> <- ignore

Edit 2:

Added akka.loglevel = DEBUG, spits out a lot more noise but still not detail about the actual error.

Converted asynchttpclient to akka quickly to rule out AHC

I already had a wrapper around my query to time it, added some logging there trying to pinpoint when exactly the error is happening.

def queryTimer[ R <: Future[ Any ] ]( block: => R ): R = {
  val t0 = System.currentTimeMillis()
  val result = block
  result.onComplete { maybeResult =>
    val t1 = System.currentTimeMillis()
    logger.info( "[QUERY TIME]: " + ( t1 - t0 ) + "ms" )

    maybeResult match {
      case Success(some) =>
        logger.info( "successful feature:")
        logger.info( FormattedString.prettyPrint(some))
      case Failure(someFailure) =>
        logger.info( "failed feature:")
        logger.debug( FormattedString.prettyPrint(someFailure))
    }
  }
  result
}

resulting log:

2017-03-28 13:19:10 INFO  CompanyRepository:111 - search company with name:"some company"
[DEBUG] [03/28/2017 13:19:10.497] [company-api-system-akka.actor.default-dispatcher-2] [EventStream(akka://xca-api-actor-system)] logger log1-Logging$DefaultLogger started
[DEBUG] [03/28/2017 13:19:10.497] [company-api-system-akka.actor.default-dispatcher-2] [EventStream(akka://xca-api-actor-system)] Default Loggers started
[DEBUG] [03/28/2017 13:19:10.613] [company-api-system-akka.actor.default-dispatcher-2] [AkkaSSLConfig(akka://xca-api-actor-system)] Initializing AkkaSSLConfig extension...
[DEBUG] [03/28/2017 13:19:10.613] [company-api-system-akka.actor.default-dispatcher-2] [AkkaSSLConfig(akka://xca-api-actor-system)] buildHostnameVerifier: created hostname verifier: com.typesafe.sslconfig.ssl.DefaultHostnameVerifier@779e2339
[DEBUG] [03/28/2017 13:19:10.633] [xca-api-actor-system-akka.actor.default-dispatcher-3] [akka://xca-api-actor-system/user/pool-master/PoolInterfaceActor-0] (Re-)starting host connection pool to localhost:27474
[DEBUG] [03/28/2017 13:19:10.727] [xca-api-actor-system-akka.actor.default-dispatcher-3] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Resolving localhost before connecting
[DEBUG] [03/28/2017 13:19:10.740] [xca-api-actor-system-akka.actor.default-dispatcher-4] [akka://xca-api-actor-system/system/IO-DNS] Resolution request for localhost from Actor[akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0#-815754478]
[DEBUG] [03/28/2017 13:19:10.749] [xca-api-actor-system-akka.actor.default-dispatcher-4] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Attempting connection to [localhost/127.0.0.1:27474]
[DEBUG] [03/28/2017 13:19:10.751] [xca-api-actor-system-akka.actor.default-dispatcher-4] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Connection established to [localhost:27474]
2017-03-28 13:19:10 INFO  CompanyRepository:73 - [QUERY TIME]: 376ms
2017-03-28 13:19:10 INFO  CompanyRepository:77 - successful feature:
[ERROR] [03/28/2017 13:19:10.896] [company-api-system-akka.actor.default-dispatcher-7] [akka.actor.ActorSystemImpl(company-api-system)] Error during processing of request: 'requirement failed'. Completing with 500 Internal Server Error response.
2017-03-28 13:19:10 INFO  CompanyRepository:78 - SearchResult(List(
( prettyprint output here!!! lots and lots of legit result, json parsed succcesfully into a bunch of case classes)

as you can see my logging format and akkas' are different, the ERROR is coming from akka with do details, while everything looks like working.

Edit 3: logs with sleep in between calls

new query timer function with sleeps

def queryTimer[ R <: Future[ Any ] ]( block: => R ): R = {
  val t0 = System.currentTimeMillis()
  val result = block
  result.onComplete { maybeResult =>
    val t1 = System.currentTimeMillis()
    logger.info( "[QUERY TIME]: " + ( t1 - t0 ) + "ms" )

    maybeResult match {
      case Success(some) =>
        Thread.sleep(500)
        logger.info( "successful feature:")
        Thread.sleep(500)
        logger.info( FormattedString.prettyPrint(some))
        Thread.sleep(500)
        logger.info("we are there!")
      case Failure(someFailure) =>
        logger.info( "failed feature:")
        logger.debug( FormattedString.prettyPrint(someFailure))
    }
  }
  result
}

logs with sleeps

[DEBUG] [03/30/2017 11:11:58.629] [xca-api-actor-system-akka.actor.default-dispatcher-7] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Attempting connection to [localhost/127.0.0.1:27474]
[DEBUG] [03/30/2017 11:11:58.631] [xca-api-actor-system-akka.actor.default-dispatcher-7] [akka://xca-api-actor-system/system/IO-TCP/selectors/$a/0] Connection established to [localhost:27474]
11:11:59.442 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:11:59.496 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:00.250 [ForkJoinPool-2-worker-15] INFO  c.s.s.r.neo4j.CompanyRepository - [QUERY TIME]: 1880ms
[ERROR] [03/30/2017 11:12:00.265] [company-api-system-akka.actor.default-dispatcher-3] [akka.actor.ActorSystemImpl(company-api-system)] Error during processing of request: 'requirement failed'. Completing with 500 Internal Server Error response.
11:12:00.543 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:00.597 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:00.752 [ForkJoinPool-2-worker-15] INFO  c.s.s.r.neo4j.CompanyRepository - successful feature:
11:12:01.645 [pool-2-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:01.697 [pool-1-thread-1] DEBUG o.a.netty.channel.DefaultChannelPool - Closed 0 connections out of 0 in 0 ms
11:12:01.750 [ForkJoinPool-2-worker-15] INFO  c.s.s.r.neo4j.CompanyRepository - SearchResult(List( "lots of legit result here"
11:12:02.281 [ForkJoinPool-2-worker-15] INFO  c.s.s.r.neo4j.CompanyRepository - we are there!

Edit 4 and solution!

Apparently the default exception handler does not print a stack trace! overriding the exception handler with a very basic catch all:

implicit def myExceptionHandler: ExceptionHandler =
  ExceptionHandler {
    case e: Exception => {
      logger.info("---------------- exception log start")
      logger.error(e.getMessage, e)
      logger.error("cause" , e.getCause)
      logger.error("cause" , e.getStackTraceString )
      logger.info( FormattedString.prettyPrint(e))
      logger.info("---------------- exception log end")
      Directives.complete("server made a boo boo")
      }
  }

results in a stack trace that befuddles the sh*t out of me!!

11:42:04.634 [company-api-system-akka.actor.default-dispatcher-2] INFO  c.stepweb.scarifgate.CompanyApiApp$ - ---------------- exception log start
11:42:04.640 [company-api-system-akka.actor.default-dispatcher-2] ERROR c.stepweb.scarifgate.CompanyApiApp$ - requirement failed
java.lang.IllegalArgumentException: requirement failed
    at scala.Predef$.require(Predef.scala:212) ~[scala-library-2.11.8.jar:na]
    at spray.json.BasicFormats$StringJsonFormat$.write(BasicFormats.scala:121) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.BasicFormats$StringJsonFormat$.write(BasicFormats.scala:119) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.ProductFormats$class.productElement2Field(ProductFormats.scala:46) ~[spray-json_2.11-1.3.2.jar:na]
    at com.stepweb.scarifgate.services.CompanyService.productElement2Field(CompanyService.scala:14) ~[classes/:na]
    at spray.json.ProductFormatsInstances$$anon$3.write(ProductFormatsInstances.scala:73) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.ProductFormatsInstances$$anon$3.write(ProductFormatsInstances.scala:68) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.PimpedAny.toJson(package.scala:39) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.CollectionFormats$$anon$1$$anonfun$write$1.apply(CollectionFormats.scala:26) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.CollectionFormats$$anon$1$$anonfun$write$1.apply(CollectionFormats.scala:26) ~[spray-json_2.11-1.3.2.jar:na]
    at scala.collection.immutable.List.map(List.scala:273) ~[scala-library-2.11.8.jar:na]
    at spray.json.CollectionFormats$$anon$1.write(CollectionFormats.scala:26) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.CollectionFormats$$anon$1.write(CollectionFormats.scala:25) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.ProductFormats$class.productElement2Field(ProductFormats.scala:46) ~[spray-json_2.11-1.3.2.jar:na]
    at com.stepweb.scarifgate.services.CompanyService.productElement2Field(CompanyService.scala:14) ~[classes/:na]
    at spray.json.ProductFormatsInstances$$anon$1.write(ProductFormatsInstances.scala:30) ~[spray-json_2.11-1.3.2.jar:na]
    at spray.json.ProductFormatsInstances$$anon$1.write(ProductFormatsInstances.scala:26) ~[spray-json_2.11-1.3.2.jar:na]
    at akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport$$anonfun$sprayJsonMarshaller$1.apply(SprayJsonSupport.scala:62) ~[akka-http-spray-json_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport$$anonfun$sprayJsonMarshaller$1.apply(SprayJsonSupport.scala:62) ~[akka-http-spray-json_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anonfun$compose$1$$anonfun$apply$15.apply(Marshaller.scala:73) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anonfun$compose$1$$anonfun$apply$15.apply(Marshaller.scala:73) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.GenericMarshallers$$anonfun$optionMarshaller$1$$anonfun$apply$1.apply(GenericMarshallers.scala:19) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.GenericMarshallers$$anonfun$optionMarshaller$1$$anonfun$apply$1.apply(GenericMarshallers.scala:18) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.PredefinedToResponseMarshallers$$anonfun$fromStatusCodeAndHeadersAndValue$1$$anonfun$apply$5.apply(PredefinedToResponseMarshallers.scala:58) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.PredefinedToResponseMarshallers$$anonfun$fromStatusCodeAndHeadersAndValue$1$$anonfun$apply$5.apply(PredefinedToResponseMarshallers.scala:57) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anonfun$compose$1$$anonfun$apply$15.apply(Marshaller.scala:73) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anonfun$compose$1$$anonfun$apply$15.apply(Marshaller.scala:73) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.ToResponseMarshallable$$anonfun$1$$anonfun$apply$1.apply(ToResponseMarshallable.scala:29) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.ToResponseMarshallable$$anonfun$1$$anonfun$apply$1.apply(ToResponseMarshallable.scala:29) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.Marshaller$$anon$1.apply(Marshaller.scala:92) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.GenericMarshallers$$anonfun$futureMarshaller$1$$anonfun$apply$3$$anonfun$apply$4.apply(GenericMarshallers.scala:33) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.marshalling.GenericMarshallers$$anonfun$futureMarshaller$1$$anonfun$apply$3$$anonfun$apply$4.apply(GenericMarshallers.scala:33) ~[akka-http_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.util.FastFuture$.akka$http$scaladsl$util$FastFuture$$strictTransform$1(FastFuture.scala:41) ~[akka-http-core_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.util.FastFuture$$anonfun$transformWith$extension1$1.apply(FastFuture.scala:51) [akka-http-core_2.11-10.0.0.jar:10.0.0]
    at akka.http.scaladsl.util.FastFuture$$anonfun$transformWith$extension1$1.apply(FastFuture.scala:50) [akka-http-core_2.11-10.0.0.jar:10.0.0]
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32) [scala-library-2.11.8.jar:na]
    at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply$mcV$sp(BatchingExecutor.scala:91) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply(BatchingExecutor.scala:91) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply(BatchingExecutor.scala:91) [akka-actor_2.11-2.4.16.jar:na]
    at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:72) [scala-library-2.11.8.jar:na]
    at akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:90) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:39) [akka-actor_2.11-2.4.16.jar:na]
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:415) [akka-actor_2.11-2.4.16.jar:na]
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) [scala-library-2.11.8.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) [scala-library-2.11.8.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [scala-library-2.11.8.jar:na]
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [scala-library-2.11.8.jar:na]
11:42:04.640 [company-api-system-akka.actor.default-dispatcher-2] ERROR c.stepweb.scarifgate.CompanyApiApp$ - cause
11:42:04.641 [company-api-system-akka.actor.default-dispatcher-2] ERROR c.stepweb.scarifgate.CompanyApiApp$ - cause
11:42:04.644 [company-api-system-akka.actor.default-dispatcher-2] INFO  c.stepweb.scarifgate.CompanyApiApp$ - java.lang.IllegalArgumentException: requirement failed
11:42:04.644 [company-api-system-akka.actor.default-dispatcher-2] INFO  c.stepweb.scarifgate.CompanyApiApp$ - ---------------- exception log end

so... the exception is caused here in spray.json.BasicFormats

implicit object StringJsonFormat extends JsonFormat[String] {
  def write(x: String) = {
    require(x ne null)    // <-----------------------------------
    JsString(x)
  }
  def read(value: JsValue) = value match {
    case JsString(x) => x
    case x => deserializationError("Expected String as JsString, but got " + x)
  }
}

which sort of means one of the strings in this thousands of lines of response is null. Special thanks goes to the laziness of using that "require" without a message. Debugging which string is empty where will be a nightmare but I still think akka should fail in a better way.


来源: stackexchange

问:
For a given line in a file, can I find out which commit last changed/created it? Thanks
For a given line (or any given unit of text) in a file, can I find out which commit last changed/created it?

This will help me to identify who last changed/created it, based on the commit.

Visual Studio 2015 for C# seems to have such feature. I guess it uses git to do that. Also some commentator said that "I have a bit more trust in git showing correct commit\merge author than in Tom remembering what he did."

Thanks.

答:
git blame -L

```<code># Here -L100,+10 means "only look at the lines 100 to 100+11":
git blame -L100,+10 -- git-web--browse.sh
</code>```

-L <start>,<end>

    -L :<funcname>

Annotate only the given line range.

  May be specified multiple times. Overlapping ranges are allowed.

<start> and <end> are optional. -L <start> or -L <start>, spans from <start> to end of file.

-L ,<end> spans from start of file to <end>.

ContentLicense: CC BY-SA 3.0

Body:
git blame -L

# Here -L100,+10 means "only look at the lines 100 to 100+11":
git blame -L100,+10 -- git-web--browse.sh

-L <start>,<end>

    -L :<funcname>

Annotate only the given line range.

  May be specified multiple times. Overlapping ranges are allowed.

<start> and <end> are optional. -L <start> or -L <start>, spans from <start> to end of file.

-L ,<end> spans from start of file to <end>.


问:
Setting Up Intel TBB with Nuwen
I've recently become interested in learning more about parallel computing, concurrency, etc. My main language is C++, so obviously I decided to use that in my personal studies.

After some research (read: looking things up on Google), I decided that using Intel's TBB library would be the most ideal.

The one thing that's got me stuck so far, though, is setting it up to use on my computer. I have looked on the Internet for some sort of tutorial on setting TBB up with MinGW (in my case, specifically Nuwen) and haven't really found anything.

So, here's my question: how would I set up TBB to use with a Nuwen distro?

答:
TBB doesn't provides binaries for mingw in a Windows package. So you should build it from source code. You need compiler and GNU make;

Download source code(.zip) from https://github.com/01org/tbb/releases

Unpack somethere (not sure, but in common: beware of spaces in the dir path)

Open your console with compiler's environment, go to $archive_root/src and call gmake tbb tbbmalloc compiler=gcc. Also you could try to add stdver=c++11 in the build command if your complier supports this mode.

You will find a library build in the $archive_root/build/windows_... directory

Title: Setting Up Intel TBB with Nuwen


问:
setting hidden form field values with jquery
I'm using js.cookie.js to set cookie values after reading URL parameters. Next I want to populate a number of hidden fields with the cookie values. Reading the URL values and setting the cookie is working, but setting the values in the hidden fields is not working.

Here's the script:

```
</div>
</div>
</p>

<p>And here is are the hidden fields within the form with the id="contact-form"</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Visitor ID: -->
  <input id="00N4100000NglQ2" maxlength="255" name="00N4100000NglQ2" size="20" type="hidden" value="" />

  <!-- Medium: -->
  <input id="00N4100000NgleO" maxlength="255" name="00N4100000NgleO" size="20" type="hidden" value="" />
  <!-- Source: -->

  <input id="00N4100000NglpC" maxlength="255" name="00N4100000NglpC" size="20" type="hidden" value="" />
  <!-- Campaign: -->
  <input id="00N4100000NglyY" maxlength="255" name="00N4100000NglyY" size="20" type="hidden" value="" />

  <!-- Content: -->
  <input id="00N4100000NgmBh" maxlength="255" name="00N4100000NgmBh" size="20" type="hidden" value="" />

  <!-- Term: -->
  <input id="00N4100000NgmIs" maxlength="255" name="00N4100000NgmIs" size="20" type="hidden" value="" />

  <!-- Count of Sessions: -->
  <input id="00N4100000NgmQw" maxlength="255" name="00N4100000NgmQw" size="20" type="hidden" value="" />

  <!-- Count of Pageviews: -->
  <input id="00N4100000NgmZ5" maxlength="255" name="00N4100000NgmZ5" size="20" type="hidden" value="" /> </code>```

I'm wondering if it's a problem with the hidden field names,"00N4100000NgmZ5" for example, which are custom field names from salesforce.com

Thanks for your help.

答:
It appears you're missing the closing bracket in each of your selectors. I'd say that's the reason it's unable to insert the value into the input field.

Also, make sure that those values are collected and stored before you're inserting them into the input field.

Body:
I'm using js.cookie.js to set cookie values after reading URL parameters. Next I want to populate a number of hidden fields with the cookie values. Reading the URL values and setting the cookie is working, but setting the values in the hidden fields is not working.

Here's the script:

And here is are the hidden fields within the form with the id="contact-form"

  <input id="00N4100000NglQ2" maxlength="255" name="00N4100000NglQ2" size="20" type="hidden" value="" />

  <input id="00N4100000NgleO" maxlength="255" name="00N4100000NgleO" size="20" type="hidden" value="" />

  <input id="00N4100000NglpC" maxlength="255" name="00N4100000NglpC" size="20" type="hidden" value="" />

  <input id="00N4100000NglyY" maxlength="255" name="00N4100000NglyY" size="20" type="hidden" value="" />

  <input id="00N4100000NgmBh" maxlength="255" name="00N4100000NgmBh" size="20" type="hidden" value="" />

  <input id="00N4100000NgmIs" maxlength="255" name="00N4100000NgmIs" size="20" type="hidden" value="" />

  <input id="00N4100000NgmQw" maxlength="255" name="00N4100000NgmQw" size="20" type="hidden" value="" />

  <input id="00N4100000NgmZ5" maxlength="255" name="00N4100000NgmZ5" size="20" type="hidden" value="" />

I'm wondering if it's a problem with the hidden field names,"00N4100000NgmZ5" for example, which are custom field names from salesforce.com

Thanks for your help.


问:
Posting a reply to a tweet using Zapier
I was wondering if there is a way to post a reply to a specific tweet using Zapier?  By the looks of it, the only way would be to use webhooks and post the json, but it just would be so much simpler if I could the built in twitter functionality of Zapier.</p>

答: This isn't possible because it goes against Twitter's policies: https://zapier.com/help/twitter/#using-zapier-as-a-twitter-auto-responder</p>

Title: Posting a reply to a tweet using Zapier


问:
Allow newer SQL syntax to fallback gracefully on older versions?
I'm supporting an ageing ASP.net system that has to run on numerous customers' older installations of SQL Server (back to 2005).

Is there any way to use features of later versions of SQL Server without running into Incorrect syntax near.... errors?

The current feature I'd like to use is AT DATE TIME on Azure SQL 12 e.g. select CONVERT(datetime, SYSDATETIMEOFFSET() AT TIME ZONE 'GMT Standard Time') to implement a custom GETDATE() function, but earlier Sql versions refuse to compile it.

Is the only option running exec() on a sql string, or is there a more graceful solution?

```<code>--do a version check, and then run the appropriate sql string?
if (CHARINDEX('Azure', @@VERSION,0) > 0)
    exec('select CONVERT(datetime, SYSDATETIMEOFFSET() AT TIME ZONE ''GMT Standard Time'')')
else
    select getDate()
</code>```

答:
Your choices are as follows:

Dynamic Sql, which is what you are doing.

Have the client program/app check the version first, then adjust its queries/requests (which is really just pushing the dynamic part to the client).

Use stored procedures written specifically for the version of SQL Server they reside in.

Of these, #3 is the preferred solution.

Body:
I'm supporting an ageing ASP.net system that has to run on numerous customers' older installations of SQL Server (back to 2005).

Is there any way to use features of later versions of SQL Server without running into Incorrect syntax near.... errors?

The current feature I'd like to use is AT DATE TIME on Azure SQL 12 e.g. select CONVERT(datetime, SYSDATETIMEOFFSET() AT TIME ZONE 'GMT Standard Time') to implement a custom GETDATE() function, but earlier Sql versions refuse to compile it.

Is the only option running exec() on a sql string, or is there a more graceful solution?

--do a version check, and then run the appropriate sql string?
if (CHARINDEX('Azure', @@VERSION,0) > 0)
    exec('select CONVERT(datetime, SYSDATETIMEOFFSET() AT TIME ZONE ''GMT Standard Time'')')
else
    select getDate()


问:
Building Apache Spark 2.1.0 from source fails
Am trying to build Apache Spark 2.1.0 source, but get these errors below that baffle me...

Hadoop 2.8.0 was installed and is working
Scala 2.12.1 was installed in advance of executing the Spark install (Which seems to auto install Scala 2.11.8 ?!?)

My build line is:

```<code>build/mvn -Pyarn -Phadoop-2.7 -Dhadoop.version=2.7.0 -DskipTests clean package
</code>```

Does anybody know why I get:

```<code>user@server:/usr/local/share/spark/spark-2.1.0$ sudo /usr/local/share/spark/spark-2.1.0/build/mvn -Pyarn -Phadoop-2.7 -Dhadoop.version=2.7.0 -DskipTests clean package
[sudo] password for user:
exec: curl --progress-bar -L https://downloads.typesafe.com/zinc/0.3.9/zinc-0.3.9.tgz
######################################################################## 100.0%
exec: curl --progress-bar -L https://downloads.typesafe.com/scala/2.11.8/scala-2.11.8.tgz
######################################################################## 100.0%
exec: curl --progress-bar -L https://www.apache.org/dyn/closer.lua?action=download&filename=/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz
######################################################################## 100.0%
Using `mvn` from path: /usr/local/share/spark/spark-2.1.0/build/apache-maven-3.3.9/bin/mvn
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512M; support was removed in 8.0
[INFO] Scanning for projects...
Downloading: https://repo1.maven.org/maven2/org/apache/apache/14/apache-14.pom
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for org.apache.spark:spark-parent_2.11:2.1.0: Could not transfer artifact org.apache:apache:pom:14 from/to central (https://repo1.maven.org/maven2): repo1.maven.org: Name or service not known and 'parent.relativePath' points at wrong local POM @ line 22, column 11
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project org.apache.spark:spark-parent_2.11:2.1.0 (/usr/local/share/spark/spark-2.1.0/pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for org.apache.spark:spark-parent_2.11:2.1.0: Could not transfer artifact org.apache:apache:pom:14 from/to central (https://repo1.maven.org/maven2): repo1.maven.org: Name or service not known and 'parent.relativePath' points at wrong local POM @ line 22, column 11: Unknown host repo1.maven.org: Name or service not known -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
</code>```

I tested downloading manually (To see if that was causing the errors), which downloads without issues:

```<code>https://repo1.maven.org/maven2/org/apache/apache/14/apache-14.pom
</code>```

I also tested accessing the URL below, which also shows content:

```<code>https://repo1.maven.org/maven2
</code>```

Hope somebody smart knows how to solve this...

答:
I found out what the issue was:

I had to configure our proxy settings in the SETTINGS.XML in the directory:

```<code>/usr/local/share/spark/spark-2.1.0/build/apache-maven-3.3.9/conf
</code>```

After editing the file, the build went without any issues :)

Hope this helps someone else running into the same issue...

EDIT: Just to be extra clear, having a working proxy configuration in bash only is NOT SUFFICIENT for the Maven Build to succeed. I was able to download all files from bash manually, but Maven needed the proxy configuration in the SETTINGS.XML file present as well...

Body:
Am trying to build Apache Spark 2.1.0 source, but get these errors below that baffle me...

Hadoop 2.8.0 was installed and is working
Scala 2.12.1 was installed in advance of executing the Spark install (Which seems to auto install Scala 2.11.8 ?!?)

My build line is:

build/mvn -Pyarn -Phadoop-2.7 -Dhadoop.version=2.7.0 -DskipTests clean package

Does anybody know why I get:

user@server:/usr/local/share/spark/spark-2.1.0$ sudo /usr/local/share/spark/spark-2.1.0/build/mvn -Pyarn -Phadoop-2.7 -Dhadoop.version=2.7.0 -DskipTests clean package
[sudo] password for user:
exec: curl --progress-bar -L https://downloads.typesafe.com/zinc/0.3.9/zinc-0.3.9.tgz
######################################################################## 100.0%
exec: curl --progress-bar -L https://downloads.typesafe.com/scala/2.11.8/scala-2.11.8.tgz
######################################################################## 100.0%
exec: curl --progress-bar -L https://www.apache.org/dyn/closer.lua?action=download&filename=/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz
######################################################################## 100.0%
Using `mvn` from path: /usr/local/share/spark/spark-2.1.0/build/apache-maven-3.3.9/bin/mvn
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512M; support was removed in 8.0
[INFO] Scanning for projects...
Downloading: https://repo1.maven.org/maven2/org/apache/apache/14/apache-14.pom
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for org.apache.spark:spark-parent_2.11:2.1.0: Could not transfer artifact org.apache:apache:pom:14 from/to central (https://repo1.maven.org/maven2): repo1.maven.org: Name or service not known and 'parent.relativePath' points at wrong local POM @ line 22, column 11
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project org.apache.spark:spark-parent_2.11:2.1.0 (/usr/local/share/spark/spark-2.1.0/pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for org.apache.spark:spark-parent_2.11:2.1.0: Could not transfer artifact org.apache:apache:pom:14 from/to central (https://repo1.maven.org/maven2): repo1.maven.org: Name or service not known and 'parent.relativePath' points at wrong local POM @ line 22, column 11: Unknown host repo1.maven.org: Name or service not known -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException

I tested downloading manually (To see if that was causing the errors), which downloads without issues:

https://repo1.maven.org/maven2/org/apache/apache/14/apache-14.pom

I also tested accessing the URL below, which also shows content:

https://repo1.maven.org/maven2

Hope somebody smart knows how to solve this...

Body:
I found out what the issue was:

I had to configure our proxy settings in the SETTINGS.XML in the directory:

/usr/local/share/spark/spark-2.1.0/build/apache-maven-3.3.9/conf

After editing the file, the build went without any issues :)

Hope this helps someone else running into the same issue...

EDIT: Just to be extra clear, having a working proxy configuration in bash only is NOT SUFFICIENT for the Maven Build to succeed. I was able to download all files from bash manually, but Maven needed the proxy configuration in the SETTINGS.XML file present as well...


问:
Cancel running job scheduled with Hangfire.io
I schedule job using hangfire.io library and I can observe it being processed in built in dashboard. However, my system has requirement that the job can be cancelled from the dashboard.

There is an option to delete running job, but this only changes the state of the job in database and does not stop running job.

I see in documentation there is option to pass IJobCancellationToken however as I understand it it is used to correctly stop the job when whole server is shutting down.

Is there a way to achieve programmatic cancellation of already running task?

Should I write my own component that would periodically pull database and check whether current server instance is running job that has been cancelled? For instance maintain dictionary jobId -> CancellationTokenSource and then signal cancellation using appropriate tokensource.

答:
This works if you delete the job from the dashboard

static public void DoWork(IJobCancellationToken cancellationToken)
{
    Debug.WriteLine("Starting Work...");
    for (int i = 0; i < 10; i++)
    {
        Debug.WriteLine("Ping");

        try
        {
            cancellationToken.ThrowIfCancellationRequested();

        }
        catch (Exception ex)
        {
            Debug.WriteLine("ThrowIfCancellationRequested");
            break;
        }
        //Debug.WriteProgressBar(i);
        Thread.Sleep(5000);
    }

    Debug.WriteLine("Finished.");
}
```

ContentLicense: CC BY-SA 4.0


问:
Does lldb have a comm command like gdb?
In GDB, we can do

```<code>comm 1
p x
end
</code>```

This prints x whenever the breakpoint 1 is hit. Can lldb do the same thing?

答:
Yes.  See:

(lldb) help breakpoint command add

Title: Does lldb have a comm command like gdb?

Body:
In GDB, we can do

comm 1
p x
end

This prints x whenever the breakpoint 1 is hit. Can lldb do the same thing?


问:
Railstutorial.org: Authentication only works in the same device as created
I have followed the railstutorial.org in creating my own authentication system but it looks like there's an error.

The sign_in only works when the user has been created in the same device.

e.g:

1) I deploy the app to heroku

2) I create the user on my MAC

3) I try to sign in on my iPhone

4) Failure.

Link : http://railstutorial.org/chapters/sign-in-sign-out#top

The same happens if you replace "my MAC" for iPhone of for any other computer.

Could it be because of sessions?

What could be causing this?

答: I know this doesn't solve the problem directly but why not try a prebuilt authentication system like devise. People have put a lot of effort into solving many of the issues that you might come across and it seems crazy to re-create the wheel in terms of login.</p>

ContentLicense: CC BY-SA 2.5


问:
Aggregarte with condtions of two df
I am looking for solution that allow me to have the mean of some values in data frame by date depending on two criteria in an other data frame

Criteria DF

```<code>  > dput(Criteria)
structure(list(Name = c("ff", "fd", "fe", "fr", "fz", "fa", "kl",
"ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl", "ml",
"az", "er"), Date = c(1992, 1992, 1992, 1992, 1992, 1992, 1992,
 1992, 1992, 1992, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1993,
 1993, 1993), Value = c("FALSE", "TRUE", "FALSE", "FALSE", "FALSE",
 "FALSE", "TRUE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE",
 "TRUE", "FALSE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE",
 "TRUE")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
 -20L), .Names = c("Name", "Date", "Value"))
</code>```

Return DF

```<code>> dput(Return)
structure(list(`Names ` = c("ff", "fd", "fe", "fr", "fz", "fa",
"kl", "ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl",
"ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl", "ml",
"az", "er"), Date = structure(c(8065, 8065, 8065, 8065, 8065,
8065, 8065, 8065, 8065, 8065, 8186, 8186, 8186, 8186, 8186, 8186,
8186, 8186, 8186, 8186, 8490, 8490, 8490, 8490, 8490, 8490, 8490,
8431, 8431, 8431), class = "Date"), Value = c(0.2, 0.43, NA,
0.52, -0.002, NA, 0.001, NA, 0.22, 0.32, 0, 0.001, 0.032, 0.9123,
1, 0.32, 0.43, 0.0312, 0.0312, 0.43, 0.53, 0.84, 0.001, -0.0123,
0.43, 0.134, 0.74, 0.0312, 0.9324, 0.06)), row.names = c(NA,
-30L), .Names = c("Names ", "Date", "Value"), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

I tried to calculate the mean Value of Return DF per date , but this mean value should be calculated just for companies have the condition TRUE in Criteria DF in that Year

my solution was

```<code> for (val in Return$Value) {
 if (year(Return$Date)%in% year(Criteria$Date) & Criteria$Value == TRUE)
 result = aggregate(Return$Value, by=list(Return$Date), mean, na.rm= TRUE)
 }
 print result
</code>```

But I failed using the aggregate function .

答:
You can try this:

```<code>x <- Criteria[Criteria$Value==TRUE,]
ag <- aggregate(Value~Names+Date, Return, mean, na.rm = TRUE)
y <- data.frame(Name=ag$Names,
       Date=format(as.Date(ag$Date, format="%d/%m/%Y"),"%Y"), Date1=ag$Date, Mean=ag$Value)

merge(x, y, by = c("Name", "Date"))[,c("Name", "Date1", "Mean")]
</code>```

So you first do aggregation based on full data (i.e., variable ag) and then filter out the result based on the Name and Year in other data frame (by doing merge).

```<code> # Name      Date1   Mean
# 1   az 1992-05-31 0.0312
# 2   az 1992-01-31 0.2200
# 3   er 1993-01-31 0.0600
# 4   fd 1992-01-31 0.4300
# 5   fd 1992-05-31 0.0010
# 6   fe 1993-03-31 0.0010
# 7   kl 1992-01-31 0.0010
# 8   kl 1992-05-31 0.4300
# 9   kl 1993-03-31 0.7400
</code>```

Title: Aggregarte with condtions of two df

Body:
I am looking for solution that allow me to have the mean of some values in data frame by date depending on two criteria in an other data frame

Criteria DF

  > dput(Criteria)
structure(list(Name = c("ff", "fd", "fe", "fr", "fz", "fa", "kl",
"ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl", "ml",
"az", "er"), Date = c(1992, 1992, 1992, 1992, 1992, 1992, 1992,
 1992, 1992, 1992, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1993,
 1993, 1993), Value = c("FALSE", "TRUE", "FALSE", "FALSE", "FALSE",
 "FALSE", "TRUE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE",
 "TRUE", "FALSE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE",
 "TRUE")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
 -20L), .Names = c("Name", "Date", "Value"))

Return DF

> dput(Return)
structure(list(`Names ` = c("ff", "fd", "fe", "fr", "fz", "fa",
"kl", "ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl",
"ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl", "ml",
"az", "er"), Date = structure(c(8065, 8065, 8065, 8065, 8065,
8065, 8065, 8065, 8065, 8065, 8186, 8186, 8186, 8186, 8186, 8186,
8186, 8186, 8186, 8186, 8490, 8490, 8490, 8490, 8490, 8490, 8490,
8431, 8431, 8431), class = "Date"), Value = c(0.2, 0.43, NA,
0.52, -0.002, NA, 0.001, NA, 0.22, 0.32, 0, 0.001, 0.032, 0.9123,
1, 0.32, 0.43, 0.0312, 0.0312, 0.43, 0.53, 0.84, 0.001, -0.0123,
0.43, 0.134, 0.74, 0.0312, 0.9324, 0.06)), row.names = c(NA,
-30L), .Names = c("Names ", "Date", "Value"), class = c("tbl_df",
"tbl", "data.frame"))

I tried to calculate the mean Value of Return DF per date , but this mean value should be calculated just for companies have the condition TRUE in Criteria DF in that Year

my solution was

 for (val in Return$Value) {
 if (year(Return$Date)%in% year(Criteria$Date) & Criteria$Value == TRUE)
 result = aggregate(Return$Value, by=list(Return$Date), mean, na.rm= TRUE)
 }
 print result

But I failed using the aggregate function .

Body:
You can try this:

x <- Criteria[Criteria$Value==TRUE,]
ag <- aggregate(Value~Names+Date, Return, mean, na.rm = TRUE)
y <- data.frame(Name=ag$Names,
       Date=format(as.Date(ag$Date, format="%d/%m/%Y"),"%Y"), Date1=ag$Date, Mean=ag$Value)

merge(x, y, by = c("Name", "Date"))[,c("Name", "Date1", "Mean")]

So you first do aggregation based on full data (i.e., variable ag) and then filter out the result based on the Name and Year in other data frame (by doing merge).

 # Name      Date1   Mean
# 1   az 1992-05-31 0.0312
# 2   az 1992-01-31 0.2200
# 3   er 1993-01-31 0.0600
# 4   fd 1992-01-31 0.4300
# 5   fd 1992-05-31 0.0010
# 6   fe 1993-03-31 0.0010
# 7   kl 1992-01-31 0.0010
# 8   kl 1992-05-31 0.4300
# 9   kl 1993-03-31 0.7400


问:
Finding the highest COUNT in a GROUP BY query
Hello I am new in postgresql . Here is my code for grouping the options and counting them . I want a way though to get only the option with the max count . Is there any way ?</p>

```<code>SELECT s.option, COUNT(*)
FROM "Set" as s, "Lecture" as l, "Process" as p, "donation" as d
WHERE d.code = p.code and l.type = p.type and l.option = s.option
GROUP BY s.option
</code>```

答:
Simply give the child a name (for instance count), ORDER BY that name, and LIMIT to 1:

```<code>SELECT s.option, COUNT(*) <b>AS count</b> -- give the child a name
FROM "Set" as s, "Lecture" as l, "Process" as p, "donation" as d
WHERE d.code = p.code and l.type = p.type and l.option = s.option
GROUP BY s.option
<b>ORDER BY count DESC</b> -- order by that child in descending order
<b>LIMIT 1</b> -- and limit the output to one row</code>```

If you want the highest, you should add DESC to the ORDER BY. In case you want the lowest; either do not specify or add ASC.

Body:
Hello I am new in postgresql . Here is my code for grouping the options and counting them . I want a way though to get only the option with the max count . Is there any way ?

SELECT s.option, COUNT(*)
FROM "Set" as s, "Lecture" as l, "Process" as p, "donation" as d
WHERE d.code = p.code and l.type = p.type and l.option = s.option
GROUP BY s.option

Body:
Simply give the child a name (for instance count), ORDER BY that name, and LIMIT to 1:

SELECT s.option, COUNT(*) AS count -- give the child a name
FROM "Set" as s, "Lecture" as l, "Process" as p, "donation" as d
WHERE d.code = p.code and l.type = p.type and l.option = s.option
GROUP BY s.option
ORDER BY count DESC -- order by that child in descending order
LIMIT 1 -- and limit the output to one row

If you want the highest, you should add DESC to the ORDER BY. In case you want the lowest; either do not specify or add ASC.


问:
How to map matching property values into same object?
I'm mapping matching Objects into one where the ID property values match.
So far the reduce and map works fine for the ID and Fet properties.

But now I want to map the Name property to each new mapped object. I did try the following but this creates a new Object separate to the others with the Name values.

How can I map matching property values to an object?

https://jsfiddle.net/brianVarley/zs8xadht/

This is what I tried in order to get the Name mapping:

```<code>const arr = [{ ID:12, Fet: "Donuts", Name: "DD" } , { ID: 12, Fet: "Cake", Name: "DD" }, { ID: 13, Fet: "Lemon", Name: "CC"}] ;
const grouped = arr.reduce((a,v) => {
    if( !(v.ID in a) ) a[v.ID] = [];
  a.Name = v.Name
  a[v.ID].push(v.Fet);
    return a;
},{});

var newArrayOfReducedObjects = Object.keys(grouped).map(key => {
    return { ID: key, Name: key, Fet: grouped[key] };
});

console.log(newArrayOfReducedObjects);
</code>```

答:
I think you should use generic group by function which you can use with various keys for an array of objects.

```<code>var customGroupBy = function(xs, key) {
    return xs.reduce(function(rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
};
</code>```

Then you can call this function for any key:

```<code>customGroupBy (arr,"ID")
customGroupBy (arr,"Name")
</code>```

The last call above will result in (JSONified)

```<code>"{"DD":[{"ID":12,"Fet":"Donuts","Name":"DD"},{"ID":12,"Fet":"Cake","Name":"DD"}],"CC":[{"ID":13,"Fet":"Lemon","Name":"CC"}]}"
</code>```

Body:
I'm mapping matching Objects into one where the ID property values match.
So far the reduce and map works fine for the ID and Fet properties.

But now I want to map the Name property to each new mapped object. I did try the following but this creates a new Object separate to the others with the Name values.

How can I map matching property values to an object?

https://jsfiddle.net/brianVarley/zs8xadht/

This is what I tried in order to get the Name mapping:

const arr = [{ ID:12, Fet: "Donuts", Name: "DD" } , { ID: 12, Fet: "Cake", Name: "DD" }, { ID: 13, Fet: "Lemon", Name: "CC"}] ;
const grouped = arr.reduce((a,v) => {
    if( !(v.ID in a) ) a[v.ID] = [];
  a.Name = v.Name
  a[v.ID].push(v.Fet);
    return a;
},{});

var newArrayOfReducedObjects = Object.keys(grouped).map(key => {
    return { ID: key, Name: key, Fet: grouped[key] };
});

console.log(newArrayOfReducedObjects);

Body:
I think you should use generic group by function which you can use with various keys for an array of objects.

var customGroupBy = function(xs, key) {
    return xs.reduce(function(rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
};

Then you can call this function for any key:

customGroupBy (arr,"ID")
customGroupBy (arr,"Name")

The last call above will result in (JSONified)

"{"DD":[{"ID":12,"Fet":"Donuts","Name":"DD"},{"ID":12,"Fet":"Cake","Name":"DD"}],"CC":[{"ID":13,"Fet":"Lemon","Name":"CC"}]}"


问:
How to replace white space between 2 strings using sed
How I can replace a single white space for underscore just between 2 strings like the example below, using sed:

```<code>xxx ccc vvv bbb        333  444  555
   ^   ^   ^   ^^^^^^^^   ^^   ^^   <--- spaces visualized for easier counting
</code>```

Desired output:

```<code>xxx_ccc_vvv_bbb        333  444  555
</code>```

答:
That's easy, you just do a global (g) replace (s) of single whitespace characters (\s) surrounded by word boundaries (\b) with underscores (_):

```<code>sed 's/\b\s\b/_/g'
</code>```

Your example could be run like this:

```<code>echo "xxx ccc vvv bbb        333  444  555" | sed 's/\b\s\b/_/g'
</code>```

which produces the output you want:

```<code>xxx_ccc_vvv_bbb        333  444  555
</code>```

Body:
How I can replace a single white space for underscore just between 2 strings like the example below, using sed:

xxx ccc vvv bbb        333  444  555
   ^   ^   ^   ^^^^^^^^   ^^   ^^   <--- spaces visualized for easier counting

Desired output:

xxx_ccc_vvv_bbb        333  444  555

Body:
That's easy, you just do a global (g) replace (s) of single whitespace characters (\s) surrounded by word boundaries (\b) with underscores (_):

sed 's/\b\s\b/_/g'

Your example could be run like this:

echo "xxx ccc vvv bbb        333  444  555" | sed 's/\b\s\b/_/g'

which produces the output you want:

xxx_ccc_vvv_bbb        333  444  555


问:
URL automatically apending to page URL
I'm trying to use a getElementsByTagName to swap out some text in the body section of my website and replace it with a hyperlink.  The problem is instead of giving me the link I'm specifying instead I get https://www.example.com/section1/"https://www.example.com/section2".

Here's my code:

```<code><script>
window.onload = function() {
    var string = document.getElementsByTagName('body')[0].innerHTML;
    var replacedString = string.replace(/msAb/gi,"<a href = "https://www.example.com/sectiontitle&quot'>hyperlinktext</a>");
    document.getElementsByTagName('body')[0].innerHTML = replacedString;
}
</script>
</code>```

I'd appreciate your suggestions.

Thanks!

答:
Link element href values are normally supplied as quoted strings in HTML source. But in practice, and without suggesting you do so, the quotes can be omitted. So the HTML parser is going to remove quotes from around the href value if it sees them there. The HTML parser also replaces character entities like " with the character the entity represents - in this case double quote marks.

The order in which the parser attempts to remove quote marks around the href attribute and replace character entities determines the result. You have amply demonstrated removing actual quote marks comes first. The href value, which ended up having quotation marks in it, after character entity replacement, is seen as a relative reference and produces the relative link you posted.

So take out the character entities from the string. Either escape the quotes in JavaScript with backslash, or use double quotes inside a single quoted string.

Title: URL automatically apending to page URL

Body:
I'm trying to use a getElementsByTagName to swap out some text in the body section of my website and replace it with a hyperlink.  The problem is instead of giving me the link I'm specifying instead I get https://www.example.com/section1/"https://www.example.com/section2".

Here's my code:

I'd appreciate your suggestions.

Thanks!

Body:
Link element href values are normally supplied as quoted strings in HTML source. But in practice, and without suggesting you do so, the quotes can be omitted. So the HTML parser is going to remove quotes from around the href value if it sees them there. The HTML parser also replaces character entities like &quot; with the character the entity represents - in this case double quote marks.

The order in which the parser attempts to remove quote marks around the href attribute and replace character entities determines the result. You have amply demonstrated removing actual quote marks comes first. The href value, which ended up having quotation marks in it, after character entity replacement, is seen as a relative reference and produces the relative link you posted.

So take out the character entities from the string. Either escape the quotes in JavaScript with backslash, or use double quotes inside a single quoted string.


问:
class not found after composer dump-autoload
I have a problem with compser autoload.
 If execute command "composer dump-autoload" then emerges error Class not found because autoload_static.php changed.

I have following structure of project:

app

-- public

------ index.php

-- src

------ WordToImage.php

-- vendor

------ composer

------------ (any composer files)

------------ autoload_static.php

-- composer.json

index.php

```<code> require_once __DIR__ . '/../vendor/autoload.php';
 use wti\src\WordToImage;

 $loader = new WordToImage();
 $loader->saveImages();
</code>```

composer.json

```<code>{
    "autoload": {
        "psr-4": {
            "wti\\" : "src/"
        }
    }
}
</code>```

autoload_static.php

```<code><?php

// autoload_static.php @generated by Composer

namespace Composer\Autoload;

class ComposerStaticInit416f5acb57c46a86bf05d897e056b40d
{
    public static $prefixLengthsPsr4 = array (
        'w' =>
        array (
            'wti\\' => 4,
        ),
    );

    public static $prefixDirsPsr4 = array (
        'wti\\' =>
        array (
            0 => __DIR__ . '/../..' . '/src/WordToImage.php',
        ),
    );

    public static $classMap = array (
        'wti\\src\\WordToImage' => __DIR__ . '/../..' . '/src/WordToImage.php',
    );

    public static function getInitializer(ClassLoader $loader)
    {
        return \Closure::bind(function () use ($loader) {
            $loader->prefixLengthsPsr4 = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$prefixLengthsPsr4;
            $loader->prefixDirsPsr4 = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$prefixDirsPsr4;
            $loader->classMap = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$classMap;

        }, null, ClassLoader::class);
    }
}
</code>```

When I execute command "composer dump-autoload" then autoload_static.php is changed

```<code><?php

// autoload_static.php @generated by Composer

namespace Composer\Autoload;

class ComposerStaticInit416f5acb57c46a86bf05d897e056b40d
{
    public static $prefixLengthsPsr4 = array (
        'w' =>
        array (
            'wti\\' => 4,
        ),
    );

    public static $prefixDirsPsr4 = array (
        'wti\\' =>
        array (
            0 => __DIR__ . '/../..' . '/src',
        ),
    );

    public static function getInitializer(ClassLoader $loader)
    {
        return \Closure::bind(function () use ($loader) {
            $loader->prefixLengthsPsr4 = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$prefixLengthsPsr4;
            $loader->prefixDirsPsr4 = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$prefixDirsPsr4;

        }, null, ClassLoader::class);
    }
}
</code>```

And when I starting the project, an error emerges (Class not found). Please tell me why this strings:

```<code>0 => __DIR__ . '/../..' . '/src/WordToImage.php'
'wti\\src\\WordToImage' => __DIR__ . '/../..' . '/src/WordToImage.php',
</code>```

are delete

答:
Two things:
1. The psr-4 autoloader definition takes an array of directories as the value for the namespace:

```<code>{
    "autoload": {
        "psr-4": {
            "wti\\": ["src/"]
        }
    }
}
</code>```

As @ndufreche already mentioned: Try use wti\WordToImage;

Body:
I have a problem with compser autoload.
 If execute command "composer dump-autoload" then emerges error Class not found because autoload_static.php changed.

I have following structure of project:

app

-- public

------ index.php

-- src

------ WordToImage.php

-- vendor

------ composer

------------ (any composer files)

------------ autoload_static.php

-- composer.json

index.php

 require_once __DIR__ . '/../vendor/autoload.php';
 use wti\src\WordToImage;

 $loader = new WordToImage();
 $loader->saveImages();

composer.json

{
    "autoload": {
        "psr-4": {
            "wti\\" : "src/"
        }
    }
}

autoload_static.php

<?php

// autoload_static.php @generated by Composer

namespace Composer\Autoload;

class ComposerStaticInit416f5acb57c46a86bf05d897e056b40d
{
    public static $prefixLengthsPsr4 = array (
        'w' =>
        array (
            'wti\\' => 4,
        ),
    );

    public static $prefixDirsPsr4 = array (
        'wti\\' =>
        array (
            0 => __DIR__ . '/../..' . '/src/WordToImage.php',
        ),
    );

    public static $classMap = array (
        'wti\\src\\WordToImage' => __DIR__ . '/../..' . '/src/WordToImage.php',
    );

    public static function getInitializer(ClassLoader $loader)
    {
        return \Closure::bind(function () use ($loader) {
            $loader->prefixLengthsPsr4 = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$prefixLengthsPsr4;
            $loader->prefixDirsPsr4 = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$prefixDirsPsr4;
            $loader->classMap = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$classMap;

        }, null, ClassLoader::class);
    }
}

When I execute command "composer dump-autoload" then autoload_static.php is changed

<?php

// autoload_static.php @generated by Composer

namespace Composer\Autoload;

class ComposerStaticInit416f5acb57c46a86bf05d897e056b40d
{
    public static $prefixLengthsPsr4 = array (
        'w' =>
        array (
            'wti\\' => 4,
        ),
    );

    public static $prefixDirsPsr4 = array (
        'wti\\' =>
        array (
            0 => __DIR__ . '/../..' . '/src',
        ),
    );

    public static function getInitializer(ClassLoader $loader)
    {
        return \Closure::bind(function () use ($loader) {
            $loader->prefixLengthsPsr4 = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$prefixLengthsPsr4;
            $loader->prefixDirsPsr4 = ComposerStaticInit416f5acb57c46a86bf05d897e056b40d::$prefixDirsPsr4;

        }, null, ClassLoader::class);
    }
}

And when I starting the project, an error emerges (Class not found). Please tell me why this strings:

0 => __DIR__ . '/../..' . '/src/WordToImage.php'
'wti\\src\\WordToImage' => __DIR__ . '/../..' . '/src/WordToImage.php',

are delete

Body:
Two things:
1. The psr-4 autoloader definition takes an array of directories as the value for the namespace:

{
    "autoload": {
        "psr-4": {
            "wti\\": ["src/"]
        }
    }
}

As @ndufreche already mentioned: Try use wti\WordToImage;


问:
Sum of two numbers with function in haskell
I am beginner who wants to learn Haskell! I want to make a function, which has two parameters for input and one for output! The task of the function is to sum two numbers and to return the result! This is my code but it gives a error

```<code>mygcd :: (a , b) -> c
mygcd c = a + b

main = do
a <- readLn
b <-readLn
print $ mygcd (a , b)
</code>```

I will be thankful if you can help me!

答:
I think you may be confusing type variables which are used in type annotations, and the actual values being passed to the function.

In your definition of mygcd:

```<code>mygcd c = a + b
</code>```

Unless a and b are defined elsewhere, this will be an error. In other words, these a, b, and c are different than the a, b, and c mentioned in the type annotation for the function. The ones in the type annotation refer only to types of variables.

If it is confusing, you can leave off the type annotation and let the compiler determine it for you.

For instance, if you want a function to add two numbers, it's as simple as this:

```<code>addTwoNumbers a b = a + b
</code>```

If you load this into GHCi, and check the type with :t addTwoNumbers, you'll see that the inferred type is addTwoNumbers :: Num a => a -> a -> a.

If you would prefer the function add the contents of a tuple, you can change the definition to

```<code>addTuple (a, b) = a + b
</code>```

Now the inferred type will be addTuple :: Num a => (a, a) -> a

```<code>mygcd :: Num a => (a, a) -> a
mygcd (a, b) = a + b

main = do
  a <- readLn
  b <- readLn
  print $ mygcd (a, b)
</code>```

Body:
I am beginner who wants to learn Haskell! I want to make a function, which has two parameters for input and one for output! The task of the function is to sum two numbers and to return the result! This is my code but it gives a error

mygcd :: (a , b) -> c
mygcd c = a + b

main = do
a <- readLn
b <-readLn
print $ mygcd (a , b)

I will be thankful if you can help me!

Body:
I think you may be confusing type variables which are used in type annotations, and the actual values being passed to the function.

In your definition of mygcd:

mygcd c = a + b

Unless a and b are defined elsewhere, this will be an error. In other words, these a, b, and c are different than the a, b, and c mentioned in the type annotation for the function. The ones in the type annotation refer only to types of variables.

If it is confusing, you can leave off the type annotation and let the compiler determine it for you.

For instance, if you want a function to add two numbers, it's as simple as this:

addTwoNumbers a b = a + b

If you load this into GHCi, and check the type with :t addTwoNumbers, you'll see that the inferred type is addTwoNumbers :: Num a => a -> a -> a.

If you would prefer the function add the contents of a tuple, you can change the definition to

addTuple (a, b) = a + b

Now the inferred type will be addTuple :: Num a => (a, a) -> a

mygcd :: Num a => (a, a) -> a
mygcd (a, b) = a + b

main = do
  a <- readLn
  b <- readLn
  print $ mygcd (a, b)


问:
Segregate Odd and Even elements in an Array in Java
Given an array of integers in java.

```<code>int arr[] = {12, 34, 45, 9, 8, 90, 3};
</code>```

Output should be :
12 34 8 90 45 9 3

There is one catch here. I know how to segregate the even and odd elements but in one of the interviews, I have asked to write a code that will not only do this segregation but also maintain the order in such a way that an even element should follow insertion order with respect to other even elements in array and same for odd elements.

Normal even odd segregation will result [12 34 90 8 9 45 3] but I want the final output as  [12 34 8 90 45 9 3].

For normal even odd segregation I followed this approach:

```<code>class TestOutput {
static void segregateEvenOdd(int input[]) {
    int left = 0, right = input.length - 1;
    while (left < right) {
        while (input[left] % 2 == 0 && left < right)
            left++;
        while (input[right] % 2 == 1 && left < right)
            right--;
        if (left < right) {
            int temp = input[left];
            input[left] = input[right];
            input[right] = temp;
            left++;
            right--;
        }
    }
}
public static void main(String[] args) {
    int input[] = { 12, 34, 45, 9, 8, 90, 3 };
    segregateEvenOdd(input);
    for (int i = 0; i < input.length; i++)
        System.out.print(input[i] + " ");
}
</code>```

}

答:
```<code>/**
 * Created by maciej.brzozowski.83@gmail.com on 2017-03-30.
 * stackOverflow_43127404
 */
public class ArraySort {

    public ArraySort() {
    }

    public int[] sort(int[] array){
        int[] result = new int[array.length];
        int resultIndex=0; //

        for (int i = 0; i <array.length ; i++) {
            if (array[i]%2==0){
                result[resultIndex]= array[i];
                resultIndex++;
            }
        }

        for (int i = 0; i <array.length ; i++) {
            if (array[i]%2==1){
                result[resultIndex]= array[i];
                resultIndex++;
            }
        }

        return result;
    }

}
</code>```

It should do what you need. Code needs two passes throuht array so it needs O(2n) for execute. Under is test for this algorithm in Spock Framework (groovy)

```<code>import org.junit.Assert
import spock.lang.Specification

/**
 * Created by maciej.brzozowski.83@gmail.com on 2017-03-30.
 * stackOverflow_43127404
 */
class arraySortSpectTest extends Specification {

   def "ShouldSortArrayInSpecificOrderPolishFlagSortOddEven"() {
      given:
      int[] testArray = [12,34,45,9,8,90,3];
      int[] expectedArray = [12,34,8,90,45,9,3];
      ArraySort polishFlagSort = new ArraySort();

      when:
      int[] actualResult = polishFlagSort.sort(testArray);

      then:

      Assert.assertArrayEquals(expectedArray, actualResult);
   }
}
</code>```

Body:
Given an array of integers in java.

int arr[] = {12, 34, 45, 9, 8, 90, 3};

Output should be :
12 34 8 90 45 9 3

There is one catch here. I know how to segregate the even and odd elements but in one of the interviews, I have asked to write a code that will not only do this segregation but also maintain the order in such a way that an even element should follow insertion order with respect to other even elements in array and same for odd elements.

Normal even odd segregation will result [12 34 90 8 9 45 3] but I want the final output as  [12 34 8 90 45 9 3].

For normal even odd segregation I followed this approach:

class TestOutput {
static void segregateEvenOdd(int input[]) {
    int left = 0, right = input.length - 1;
    while (left < right) {
        while (input[left] % 2 == 0 && left < right)
            left++;
        while (input[right] % 2 == 1 && left < right)
            right--;
        if (left < right) {
            int temp = input[left];
            input[left] = input[right];
            input[right] = temp;
            left++;
            right--;
        }
    }
}
public static void main(String[] args) {
    int input[] = { 12, 34, 45, 9, 8, 90, 3 };
    segregateEvenOdd(input);
    for (int i = 0; i < input.length; i++)
        System.out.print(input[i] + " ");
}

}

Body:
/**
 * Created by maciej.brzozowski.83@gmail.com on 2017-03-30.
 * stackOverflow_43127404
 */
public class ArraySort {

    public ArraySort() {
    }

    public int[] sort(int[] array){
        int[] result = new int[array.length];
        int resultIndex=0; //

        for (int i = 0; i <array.length ; i++) {
            if (array[i]%2==0){
                result[resultIndex]= array[i];
                resultIndex++;
            }
        }

        for (int i = 0; i <array.length ; i++) {
            if (array[i]%2==1){
                result[resultIndex]= array[i];
                resultIndex++;
            }
        }

        return result;
    }

}

It should do what you need. Code needs two passes throuht array so it needs O(2n) for execute. Under is test for this algorithm in Spock Framework (groovy)

import org.junit.Assert
import spock.lang.Specification

/**
 * Created by maciej.brzozowski.83@gmail.com on 2017-03-30.
 * stackOverflow_43127404
 */
class arraySortSpectTest extends Specification {

   def "ShouldSortArrayInSpecificOrderPolishFlagSortOddEven"() {
      given:
      int[] testArray = [12,34,45,9,8,90,3];
      int[] expectedArray = [12,34,8,90,45,9,3];
      ArraySort polishFlagSort = new ArraySort();

      when:
      int[] actualResult = polishFlagSort.sort(testArray);

      then:

      Assert.assertArrayEquals(expectedArray, actualResult);
   }
}


问:
Is it possible to get current mouse cursor size in Javascript/jQuery?
I am using a custom cursor (SVG file) which is activated when hovering a button. I want this cursor to have the same size with default cursor on all platforms.

I wonder if it is possible to get default cursor size and set size of custom cursor accordingly.

A similar question was asked here almost 8 years ago. I was hoping it would be possible with new technologies.

答:
Unfortunately, there is no property to adjust cursor size with jquery. However since you are using a custom image you might find this useful:

http://www.ajaxblender.com/howto-create-custom-image-cursors.html.

This will show you how to create a custom cursor without a .cur file and add some css to adjust the size.


问:
Focus removed even after event returns false (cancelled event)
I have implemented hotkeys using jquery.hotkeys

```<code>  $("textarea").bind("keydown", "tab", function() {
    alert("tab");
    return false;
  });
</code>```

But I noticed that after the function returns, the focus is not in the textbox anymore. Its not in the next control too. I could do this.focus(), but I wonder why after returning false, the focus will be gone? also I am curious where did the focus go to

http://jsfiddle.net/Tu6vF/1/

答:
It's not the return, it's the alert() that loses focus (that's also the answer for the "where did it go?" part...the alert window it created).

Here's your code without the alerts, never losing focus (at least, not because of your binds, clicking outside, etc works normally).

Body:
I have implemented hotkeys using jquery.hotkeys

  $("textarea").bind("keydown", "tab", function() {
    alert("tab");
    return false;
  });

But I noticed that after the function returns, the focus is not in the textbox anymore. Its not in the next control too. I could do this.focus(), but I wonder why after returning false, the focus will be gone? also I am curious where did the focus go to

http://jsfiddle.net/Tu6vF/1/


问:
Oracle WCC ServiceHandler not running
I'm creating a component to add some AJAX style functionality for Oracle WCC 11G

The Front-End Works successfully and is leveraging Bex Huff's Oracle UCM Jquery Plugin.

I've created a ServiceHandler for DocService PREPARE_BASKET prepareTopicEdits().  However it never fires.

Content Basket defines PREPARE_BASKET like so:

```<code><tr>
    <td>PREPARE_BASKET</td>
    <td>DocService
        17
        REDIRECT_TEMPLATE
        null
        null<br>
        null</td>
    <td>3:prepareTopicEdits:::null
        3:checkBasketLimit::0:null
        3:prepareRedirect:IdcService=SHOW_BASKET:0:null</td>
</tr>
</code>```

So I Wired up my ServiceHandlder Like so:

```<code>  <tr>
     <td>DocService</td><td>com.foo.ecm.ajaxValidator.ContentBasketHandler</td><td>10</td>
  </tr>
  <tr>
     <td>PREPARE_BASKET</td><td>com.foo.ecm.ajaxValidator.ContentBasketHandler</td><td>10</td>
  </tr>
</code>```

The Table is listed in the merge rules in the componentName.hda file

ContentBasketHandler extends ServiceHandler in the  com.foo.ecm.ajaxValidator package.

prepareTopicEdits is defined in the class like so:

```<code>public void prepareTopicEdits() throws DataException, ServiceException
{
  Report.trace(TRACE_SECTION, "in prepareTopicEdits()", null);

  //rest of method

  //pass the call up the chain
  m_service.doCodeEx("prepareTopicEdits", this);
}
</code>```

When I run look at the System Audit Log (with verbose Logging) my message never appears.

So why doesn't my ServiceHandler method fire, and how can I get it to run properly?

答:
Turns out the problem was in Priority.

prepareTopicEdits doesn't call other methods.
I had to lower the search order to 5 from 10 for it to be picked up and ran first.

Title: Oracle WCC ServiceHandler not running

Body:
I'm creating a component to add some AJAX style functionality for Oracle WCC 11G

The Front-End Works successfully and is leveraging Bex Huff's Oracle UCM Jquery Plugin.

I've created a ServiceHandler for DocService PREPARE_BASKET prepareTopicEdits().  However it never fires.

Content Basket defines PREPARE_BASKET like so:

    PREPARE_BASKET
    DocService
        17
        REDIRECT_TEMPLATE
        null
        null

        null
    3:prepareTopicEdits:::null
        3:checkBasketLimit::0:null
        3:prepareRedirect:IdcService=SHOW_BASKET:0:null

So I Wired up my ServiceHandlder Like so:

     DocService	com.foo.ecm.ajaxValidator.ContentBasketHandler	10

     PREPARE_BASKET	com.foo.ecm.ajaxValidator.ContentBasketHandler	10

The Table is listed in the merge rules in the componentName.hda file

ContentBasketHandler extends ServiceHandler in the  com.foo.ecm.ajaxValidator package.

prepareTopicEdits is defined in the class like so:

public void prepareTopicEdits() throws DataException, ServiceException
{
  Report.trace(TRACE_SECTION, "in prepareTopicEdits()", null);

  //rest of method

  //pass the call up the chain
  m_service.doCodeEx("prepareTopicEdits", this);
}

When I run look at the System Audit Log (with verbose Logging) my message never appears.

So why doesn't my ServiceHandler method fire, and how can I get it to run properly?


问:
Remove duplicates as well as original row
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

```<code>ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove
</code>```

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

答:
In a list

```<code>SELECT MIN(ItemNUMBER), from_DATE, to_DATE, fancy_code
FROM yourTable
GROUP BY ID, from_DATE, to_DATE, fancy_code
HAVING COUNT(*) = 1
</code>```

If need DELETE

```<code>DELETE FROM yourTable
WHERE ItemNUMBER  NOT IN (
    SELECT MIN(ItemNUMBER) as ItemNUMBER
    FROM yourTable
    GROUP BY ID, from_DATE, to_DATE, fancy_code
    HAVING COUNT(*) = 1
   )
</code>```

Body:
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

Body:
In a list

SELECT MIN(ItemNUMBER), from_DATE, to_DATE, fancy_code
FROM yourTable
GROUP BY ID, from_DATE, to_DATE, fancy_code
HAVING COUNT(*) = 1

If need DELETE

DELETE FROM yourTable
WHERE ItemNUMBER  NOT IN (
    SELECT MIN(ItemNUMBER) as ItemNUMBER
    FROM yourTable
    GROUP BY ID, from_DATE, to_DATE, fancy_code
    HAVING COUNT(*) = 1
   )


问:
How to make Firebase rest api call from android when database security is set
How to authenticate against the Firebase rest api from Android when I have this
database rule:

```<code>"TOY_STORE": {
  ".read": "auth != null",
  ".write": "auth != null"
},
</code>```

If I set the ".read": "true" I can access a nod using this code

```<code> com.loopj.android.http.AsyncHttpClient client = new AsyncHttpClient();
    client.get("https://xxx-project.firebaseio.com/TOY_STORE/.json?print=pretty&shallow=true?auth=HnhLyXRxUsadhj237eYiQ53",  new JsonHttpResponseHandler() {

// respons..
}
</code>```

But when having ".read": "auth != null" it gíve permission denied.

Im signed in to Firebase usning Google credentials and the auth=HnhLyXRxUsadhj237eYiQ53 is my Firebase ID. I can read and write to database making regularly ValueEventListener and updateChildren calls.

I have also tried the Web API Key for auth but not working.

I want to run this code because of the Firebase REST API shallow-data

答:
The documentation for authenticating with the REST API can be found here.  You need to pass an auth parameter in the query string with the value of the user's authentication token.

It's a really bad idea to put your database secret key into your app, which can be easily reverse engineered by anyone.  But if you want to use the REST API from a server you control, you can find your database secret key in Project Settings -> Service Accounts -> Database Secrets.

Body:
How to authenticate against the Firebase rest api from Android when I have this
database rule:

"TOY_STORE": {
  ".read": "auth != null",
  ".write": "auth != null"
},

If I set the ".read": "true" I can access a nod using this code

 com.loopj.android.http.AsyncHttpClient client = new AsyncHttpClient();
    client.get("https://xxx-project.firebaseio.com/TOY_STORE/.json?print=pretty&shallow=true?auth=HnhLyXRxUsadhj237eYiQ53",  new JsonHttpResponseHandler() {

// respons..
}

But when having ".read": "auth != null" it gíve permission denied.

Im signed in to Firebase usning Google credentials and the auth=HnhLyXRxUsadhj237eYiQ53 is my Firebase ID. I can read and write to database making regularly ValueEventListener and updateChildren calls.

I have also tried the Web API Key for auth but not working.

I want to run this code because of the Firebase REST API shallow-data