问:
Functional way to find the Longest Common Substring between two strings in scala
Here is a imperative solution:

```<code>def longestCommonSubstring(a: String, b: String) : String = {
    def loop(m: Map[(Int, Int), Int], bestIndices: List[Int], i: Int, j: Int) : String = {
      if (i > a.length) {
        b.substring(bestIndices(1) - m((bestIndices(0),bestIndices(1))), bestIndices(1))
      } else if (i == 0 || j == 0) {
        loop(m + ((i,j) -> 0), bestIndices, if(j == b.length) i + 1 else i, if(j == b.length) 0 else j + 1)
      } else if (a(i-1) == b(j-1) && math.max(m((bestIndices(0),bestIndices(1))), m((i-1,j-1)) + 1) == (m((i-1,j-1)) + 1)) {
        loop(
          m + ((i,j) -> (m((i-1,j-1)) + 1)),
          List(i, j),
          if(j == b.length) i + 1 else i,
          if(j == b.length) 0 else j + 1
        )
      } else {
        loop(m + ((i,j) -> 0), bestIndices, if(j == b.length) i + 1 else i, if(j == b.length) 0 else j + 1)
      }
    }
    loop(Map[(Int, Int), Int](), List(0, 0), 0, 0)
  }
</code>```

I am looking for a more compact and functional way to find the  Longest Common Substring.

答:
Sidenote: This is my third answer to this question because StackOverflow policy does not allow fundamentally replacing the content of a prior answer. And thanks to feedback from @Kolmar, this new answer is much more performant than my prior answer.

The LCS (Longest Common Substring) problem space has had many hours invested in which to find the optimal solution strategy. To observe the more general computer science problem and the optimal strategy, please review this Wikipedia article. Further down in this Wikipedia article is some pseudocode describing an implementation strategy.

Based on the Wikipedia article pseudocode, I will present several different solutions. The purpose is to allow one to copy/paste the specific solution which is needed without having to do much refactoring:

LCSubstr: Translation into Scala of the Wikipedia article pseudocode which uses an imperative mutable style

LCSubstrFp: Refactoring of LCSubstr into the idiomatic Scala functional immutable style

longestCommonSubstrings: Refactoring of LCSubstrFp to use descriptive names (such as left & right instead of s and t) and to skip storing zero lengths in the Map

longestCommonSubstringsFast: Refactoring of longestCommonSubstrings to deeply optimize for both CPU and memory

longestCommonSubstringsWithIndexes: Refactoring of longestCommonSubstringsFast to enhance the return value by expanding each entry into a tuple of (String, (Int, Int)) which includes both the found substring and the index within each input String at which the substring was found (CAUTION: This creates a combinatorial expansion of the index pairs if the same String appears more than once)

firstLongestCommonSubstring: An efficiency-focused version of longestCommonSubstringsFast which provides an opportunity to terminate early when only caring about the first LCS and would like to ignore the others of the same size.

BONUS: longestCommonSubstringsUltimate: Refactoring of longestCommonSubstringsFast to add internal implementation mutability while externally retaining the function's referential transparency.

The more direct answer to the OP's request would fall be somewhere between LCSubstrFp and longestCommonSubstringsFast. LCSubstrFp is the most direct, but fairly inefficient. Using longestCommonSubstringsFast is substantially more efficient as it ends up using far less CPU and GC. And if internal mutuability contained and constrained within a function's implementation is acceptable, then longestCommonSubstringsUltimate is by far the version with the smallest CPU burden and memory footprint.

LCSubstr

Translation into Scala of the Wikipedia article pseudocode which uses an imperative mutable style.

The intention is to come as close as it is possible with Scala to reproduce a one-to-one implementation. For example, Scala assumes zero-based indexing for String where the pseudocode clearly uses one-based indexing which required several tweaks.

```<code>def LCSubstr(s: String, t: String): scala.collection.mutable.Set[String] =
  if (s.nonEmpty && t.nonEmpty) {
    val l: scala.collection.mutable.Map[(Int, Int), Int] = scala.collection.mutable.Map.empty
    var z: Int = 0
    var ret: scala.collection.mutable.Set[String] = scala.collection.mutable.Set.empty

    (0 until s.length).foreach {
      i =>
        (0 until t.length).foreach {
          j =>
            if (s(i) == t(j)) {
              if ((i == 0) || (j == 0))
                l += ((i, j) -> 1)
              else
                l += ((i, j) -> (l((i - 1, j - 1)) + 1))
              if (l((i, j)) > z) {
                z = l((i, j))
                ret = scala.collection.mutable.Set(s.substring(i - z + 1, i + 1))
              }
              else
                if (l((i, j)) == z)
                  ret += s.substring(i - z + 1, i + 1)
            } else
              l += ((i, j) -> 0)
        }
    }

    ret
  }
  else scala.collection.mutable.Set.empty
</code>```

LCSubstrFp

Refactoring of LCSubstr into the idiomatic Scala functional immutable style.

All imperative and mutation code have been replaced with function and immutable counterparts. The two for loops have been replaced with recursion.

```<code>def LCSubstrFp(s: String, t: String): Set[String] =
  if (s.nonEmpty && t.nonEmpty) {
    @scala.annotation.tailrec
    def recursive(
      i: Int = 0,
      j: Int = 0,
      z: Int = 0,
      l: Map[(Int, Int), Int] = Map.empty,
      ret: Set[String] = Set.empty
    ): Set[String] =
      if (i < s.length) {
        val (newI, newJ) =
          if (j < t.length - 1) (i, j + 1)
          else (i + 1, 0)
        val lij =
          if (s(i) != t(j)) 0
          else
            if ((i == 0) || (j == 0)) 1
            else l((i - 1, j - 1)) + 1
        recursive(
          newI,
          newJ,
          if (lij > z) lij
          else z,
          l + ((i, j) -> lij),
          if (lij > z) Set(s.substring(i - lij + 1, i + 1))
          else
            if ((lij == z) && (z > 0)) ret + s.substring(i - lij + 1, i + 1)
            else ret
        )
      }
      else ret

    recursive()
  }
  else Set.empty
</code>```

longestCommonSubstrings

Refactoring of LCSubstrFp to use descriptive names (such as left & right instead of s and t) and to skip storing zero lengths in the Map.

Besides enhancing readability, this refactoring dispenses with storing zero-length values in lengthByIndexLongerAndIndexShorter substantially reducing the amount of "memory churn". Again in a tweak towards the functional style, the return value has also been enhanced to never return an empty Set by wrapping the Set in an Option. If the value returned is a Some, the contained Set will always contain at least one item.

```<code>def longestCommonSubstrings(left: String, right: String): Option[Set[String]] =
  if (left.nonEmpty && right.nonEmpty) {
    val (shorter, longer) =
      if (left.length < right.length) (left, right)
      else (right, left)

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lengthByIndexLongerAndIndexShorter: Map[(Int, Int), Int] = Map.empty,
      accumulator: List[Int] = Nil
    ): (Int, List[Int]) =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else
            if ((indexShorter == 0) || (indexLonger == 0)) 1
            else lengthByIndexLongerAndIndexShorter.getOrElse((indexLonger - 1, indexShorter - 1), 0) + 1
        val newCurrentLongestLength =
          if (length > currentLongestLength) length
          else currentLongestLength
        val newLengthByIndexLongerAndIndexShorter =
          if (length > 0) lengthByIndexLongerAndIndexShorter + ((indexLonger, indexShorter) -> length)
          else lengthByIndexLongerAndIndexShorter
        val newAccumulator =
          if ((length < currentLongestLength) || (length == 0)) accumulator
          else {
            val entry = indexShorter - length + 1
            if (length > currentLongestLength) List(entry)
            else entry :: accumulator
          }
        if (indexShorter < shorter.length - 1)
          recursive(
            indexLonger,
            indexShorter + 1,
            newCurrentLongestLength,
            newLengthByIndexLongerAndIndexShorter,
            newAccumulator
          )
        else
          recursive(
            indexLonger + 1,
            0,
            newCurrentLongestLength,
            newLengthByIndexLongerAndIndexShorter,
            newAccumulator
          )
      }
      else (currentLongestLength, accumulator)

    val (length, indexShorters) = recursive()
    if (indexShorters.nonEmpty)
      Some(
        indexShorters
          .map {
            indexShorter =>
              shorter.substring(indexShorter, indexShorter + length)
          }
          .toSet
      )
    else None
  }
  else None
</code>```

longestCommonSubstringsFast

Refactoring of longestCommonSubstrings to deeply optimize for both CPU and memory.

Eliminating every ounce of inefficiency while staying functional and immutable, execution speed is enhanced by several times over longestCommonSubstrings. The bulk of the cost reductions were achieved by replacing the Map of the entire matrix with a pair of Lists tracking only the current and prior rows.

To easily see the differences from longestCommonSubstrings, please view this visual diff.

```<code>def longestCommonSubstringsFast(left: String, right: String): Option[Set[String]] =
  if (left.nonEmpty && right.nonEmpty) {
    val (shorter, longer) =
      if (left.length < right.length) (left, right)
      else (right, left)

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lengthsPrior: List[Int] = List.fill(shorter.length)(0),
      lengths: List[Int] = Nil,
      accumulator: List[Int] = Nil
    ): (Int, List[Int]) =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else lengthsPrior.head + 1
        val newCurrentLongestLength =
          if (length > currentLongestLength) length
          else currentLongestLength
        val newAccumulator =
          if ((length < currentLongestLength) || (length == 0)) accumulator
          else {
            val entry = indexShorter - length + 1
            if (length > currentLongestLength) List(entry)
            else entry :: accumulator
          }
        if (indexShorter < shorter.length - 1)
          recursive(
            indexLonger,
            indexShorter + 1,
            newCurrentLongestLength,
            lengthsPrior.tail,
            length :: lengths,
            newAccumulator
          )
        else
          recursive(
            indexLonger + 1,
            0,
            newCurrentLongestLength,
            0 :: lengths.reverse,
            Nil,
            newAccumulator
          )
      }
      else (currentLongestLength, accumulator)

    val (length, indexShorters) = recursive()
    if (indexShorters.nonEmpty)
      Some(
        indexShorters
          .map {
            indexShorter =>
              shorter.substring(indexShorter, indexShorter + length)
          }
          .toSet
      )
    else None
  }
  else None
</code>```

longestCommonSubstringsWithIndexes

Refactoring of longestCommonSubstringsFast to enhance the return value by expanding each entry into a tuple of (String, (Int, Int)) which includes both the found substring and the index within each input String at which the substring was found.

CAUTION: This creates a combinatorial expansion of the index pairs if the same String appears more than once.

Again in a tweak towards the functional style, the return value has also been enhanced to never return an empty List by wrapping the List in an Option. If the value returned is a Some, the contained List will always contain at least one item.

```<code>def longestCommonSubstringsWithIndexes(left: String, right: String): Option[List[(String, (Int, Int))]] =
  if (left.nonEmpty && right.nonEmpty) {
    val isLeftShorter = left.length < right.length
    val (shorter, longer) =
      if (isLeftShorter) (left, right)
      else (right, left)

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lengthsPrior: List[Int] = List.fill(shorter.length)(0),
      lengths: List[Int] = Nil,
      accumulator: List[(Int, Int)] = Nil
    ): (Int, List[(Int, Int)]) =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else lengthsPrior.head + 1
        val newCurrentLongestLength =
          if (length > currentLongestLength) length
          else currentLongestLength
        val newAccumulator =
          if ((length < currentLongestLength) || (length == 0)) accumulator
          else {
            val entry = (indexLonger - length + 1, indexShorter - length + 1)
            if (length > currentLongestLength) List(entry)
            else entry :: accumulator
          }
        if (indexShorter < shorter.length - 1)
          recursive(
            indexLonger,
            indexShorter + 1,
            newCurrentLongestLength,
            lengthsPrior.tail,
            length :: lengths,
            newAccumulator
          )
        else
          recursive(
            indexLonger + 1,
            0,
            newCurrentLongestLength,
            0 :: lengths.reverse,
            Nil,
            newAccumulator
          )
      }
      else (currentLongestLength, accumulator)

    val (length, indexPairs) = recursive()
    if (indexPairs.nonEmpty)
      Some(
        indexPairs
          .reverse
          .map {
            indexPair =>
              (
                longer.substring(indexPair._1, indexPair._1 + length),
                if (isLeftShorter) indexPair.swap else indexPair
              )
          }
      )
    else None
  }
  else None
</code>```

firstLongestCommonSubstring

An efficiency-focused version of longestCommonSubstringsFast which provides an opportunity to terminate early when only caring about the first LCS and would like to ignore the others of the same size.

```<code>def firstLongestCommonSubstring(left: String, right: String): Option[(String, (Int, Int))] =
  if (left.nonEmpty && right.nonEmpty) {
    val isLeftShorter = left.length < right.length
    val (shorter, longer) =
      if (isLeftShorter) (left, right)
      else (right, left)

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lengthsPrior: List[Int] = List.fill(shorter.length)(0),
      lengths: List[Int] = Nil,
      accumulator: Option[(Int, Int)] = None
    ): Option[(Int, (Int, Int))] =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else lengthsPrior.head + 1
        val newAccumulator =
          if (length > currentLongestLength) Some((indexLonger - length + 1, indexShorter - length + 1))
          else accumulator
        if (length < shorter.length) {
          val newCurrentLongestLength =
            if (length > currentLongestLength) length
            else currentLongestLength
          if (indexShorter < shorter.length - 1)
            recursive(
              indexLonger,
              indexShorter + 1,
              newCurrentLongestLength,
              lengthsPrior.tail,
              length :: lengths,
              newAccumulator
            )
          else
            recursive(
              indexLonger + 1,
              0,
              newCurrentLongestLength,
              0 :: lengths.reverse,
              Nil,
              newAccumulator
            )
        }
        else
          recursive(longer.length, 0, length, lengthsPrior, lengths, newAccumulator) //early terminate
      }
      else accumulator.map((currentLongestLength, _))

    recursive().map {
      case (length, indexPair) =>
        (
          longer.substring(indexPair._1, indexPair._1 + length),
          if (isLeftShorter) indexPair.swap else indexPair
        )
    }
  }
  else None
</code>```

BONUS:

longestCommonSubstringsUltimate

Refactoring of longestCommonSubstringsFast to add internal implementation mutability while externally retaining the function's referential transparency.

Further eliminating every ounce of inefficiency while staying functional and referentially transparent (engaging in utilizing mutability within the implementation itself which some consider is not validly functional), execution speed is enhanced by almost three times over longestCommonSubstringsFast. The bulk of the cost reductions were by replacing the pair of Lists with a single Array.

To easily see the differences from longestCommonSubstringsFast, please view this visual diff.

```<code>def longestCommonSubstringsUltimate(left: String, right: String): Option[Set[String]] =
  if (left.nonEmpty && right.nonEmpty) {
    val (shorter, longer) =
      if (left.length < right.length) (left, right)
      else (right, left)
    val lengths: Array[Int] = new Array(shorter.length) //mutable

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lastIterationLength: Int = 0,
      accumulator: List[Int] = Nil
    ): (Int, List[Int]) =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else
            if (indexShorter == 0) 1
            else lastIterationLength + 1
        val newLastIterationLength = lengths(indexShorter)
        lengths(indexShorter) = length //mutation
        val newCurrentLongestLength =
          if (length > currentLongestLength) length
          else currentLongestLength
        val newAccumulator =
          if ((length < currentLongestLength) || (length == 0)) accumulator
          else {
            val entry = indexShorter - length + 1
            if (length > currentLongestLength) List(entry)
            else entry :: accumulator
          }
        if (indexShorter < shorter.length - 1)
          recursive(
            indexLonger,
            indexShorter + 1,
            newCurrentLongestLength,
            newLastIterationLength,
            newAccumulator
          )
        else
          recursive(
            indexLonger + 1,
            0,
            newCurrentLongestLength,
            newLastIterationLength,
            newAccumulator
          )
      }
      else (currentLongestLength, accumulator)

    val (length, indexShorters) = recursive()
    if (indexShorters.nonEmpty)
      Some(
        indexShorters
          .map {
            indexShorter =>
              shorter.substring(indexShorter, indexShorter + length)
          }
          .toSet
      )
    else None
  }
  else None
</code>```

Body:
Here is a imperative solution:

def longestCommonSubstring(a: String, b: String) : String = {
    def loop(m: Map[(Int, Int), Int], bestIndices: List[Int], i: Int, j: Int) : String = {
      if (i > a.length) {
        b.substring(bestIndices(1) - m((bestIndices(0),bestIndices(1))), bestIndices(1))
      } else if (i == 0 || j == 0) {
        loop(m + ((i,j) -> 0), bestIndices, if(j == b.length) i + 1 else i, if(j == b.length) 0 else j + 1)
      } else if (a(i-1) == b(j-1) && math.max(m((bestIndices(0),bestIndices(1))), m((i-1,j-1)) + 1) == (m((i-1,j-1)) + 1)) {
        loop(
          m + ((i,j) -> (m((i-1,j-1)) + 1)),
          List(i, j),
          if(j == b.length) i + 1 else i,
          if(j == b.length) 0 else j + 1
        )
      } else {
        loop(m + ((i,j) -> 0), bestIndices, if(j == b.length) i + 1 else i, if(j == b.length) 0 else j + 1)
      }
    }
    loop(Map[(Int, Int), Int](), List(0, 0), 0, 0)
  }

I am looking for a more compact and functional way to find the  Longest Common Substring.

Body:
Sidenote: This is my third answer to this question because StackOverflow policy does not allow fundamentally replacing the content of a prior answer. And thanks to feedback from @Kolmar, this new answer is much more performant than my prior answer.

The LCS (Longest Common Substring) problem space has had many hours invested in which to find the optimal solution strategy. To observe the more general computer science problem and the optimal strategy, please review this Wikipedia article. Further down in this Wikipedia article is some pseudocode describing an implementation strategy.

Based on the Wikipedia article pseudocode, I will present several different solutions. The purpose is to allow one to copy/paste the specific solution which is needed without having to do much refactoring:

LCSubstr: Translation into Scala of the Wikipedia article pseudocode which uses an imperative mutable style

LCSubstrFp: Refactoring of LCSubstr into the idiomatic Scala functional immutable style

longestCommonSubstrings: Refactoring of LCSubstrFp to use descriptive names (such as left & right instead of s and t) and to skip storing zero lengths in the Map

longestCommonSubstringsFast: Refactoring of longestCommonSubstrings to deeply optimize for both CPU and memory

longestCommonSubstringsWithIndexes: Refactoring of longestCommonSubstringsFast to enhance the return value by expanding each entry into a tuple of (String, (Int, Int)) which includes both the found substring and the index within each input String at which the substring was found (CAUTION: This creates a combinatorial expansion of the index pairs if the same String appears more than once)

firstLongestCommonSubstring: An efficiency-focused version of longestCommonSubstringsFast which provides an opportunity to terminate early when only caring about the first LCS and would like to ignore the others of the same size.

BONUS: longestCommonSubstringsUltimate: Refactoring of longestCommonSubstringsFast to add internal implementation mutability while externally retaining the function's referential transparency.

The more direct answer to the OP's request would fall be somewhere between LCSubstrFp and longestCommonSubstringsFast. LCSubstrFp is the most direct, but fairly inefficient. Using longestCommonSubstringsFast is substantially more efficient as it ends up using far less CPU and GC. And if internal mutuability contained and constrained within a function's implementation is acceptable, then longestCommonSubstringsUltimate is by far the version with the smallest CPU burden and memory footprint.

LCSubstr

Translation into Scala of the Wikipedia article pseudocode which uses an imperative mutable style.

The intention is to come as close as it is possible with Scala to reproduce a one-to-one implementation. For example, Scala assumes zero-based indexing for String where the pseudocode clearly uses one-based indexing which required several tweaks.

def LCSubstr(s: String, t: String): scala.collection.mutable.Set[String] =
  if (s.nonEmpty && t.nonEmpty) {
    val l: scala.collection.mutable.Map[(Int, Int), Int] = scala.collection.mutable.Map.empty
    var z: Int = 0
    var ret: scala.collection.mutable.Set[String] = scala.collection.mutable.Set.empty

    (0 until s.length).foreach {
      i =>
        (0 until t.length).foreach {
          j =>
            if (s(i) == t(j)) {
              if ((i == 0) || (j == 0))
                l += ((i, j) -> 1)
              else
                l += ((i, j) -> (l((i - 1, j - 1)) + 1))
              if (l((i, j)) > z) {
                z = l((i, j))
                ret = scala.collection.mutable.Set(s.substring(i - z + 1, i + 1))
              }
              else
                if (l((i, j)) == z)
                  ret += s.substring(i - z + 1, i + 1)
            } else
              l += ((i, j) -> 0)
        }
    }

    ret
  }
  else scala.collection.mutable.Set.empty

LCSubstrFp

Refactoring of LCSubstr into the idiomatic Scala functional immutable style.

All imperative and mutation code have been replaced with function and immutable counterparts. The two for loops have been replaced with recursion.

def LCSubstrFp(s: String, t: String): Set[String] =
  if (s.nonEmpty && t.nonEmpty) {
    @scala.annotation.tailrec
    def recursive(
      i: Int = 0,
      j: Int = 0,
      z: Int = 0,
      l: Map[(Int, Int), Int] = Map.empty,
      ret: Set[String] = Set.empty
    ): Set[String] =
      if (i < s.length) {
        val (newI, newJ) =
          if (j < t.length - 1) (i, j + 1)
          else (i + 1, 0)
        val lij =
          if (s(i) != t(j)) 0
          else
            if ((i == 0) || (j == 0)) 1
            else l((i - 1, j - 1)) + 1
        recursive(
          newI,
          newJ,
          if (lij > z) lij
          else z,
          l + ((i, j) -> lij),
          if (lij > z) Set(s.substring(i - lij + 1, i + 1))
          else
            if ((lij == z) && (z > 0)) ret + s.substring(i - lij + 1, i + 1)
            else ret
        )
      }
      else ret

    recursive()
  }
  else Set.empty

longestCommonSubstrings

Refactoring of LCSubstrFp to use descriptive names (such as left & right instead of s and t) and to skip storing zero lengths in the Map.

Besides enhancing readability, this refactoring dispenses with storing zero-length values in lengthByIndexLongerAndIndexShorter substantially reducing the amount of "memory churn". Again in a tweak towards the functional style, the return value has also been enhanced to never return an empty Set by wrapping the Set in an Option. If the value returned is a Some, the contained Set will always contain at least one item.

def longestCommonSubstrings(left: String, right: String): Option[Set[String]] =
  if (left.nonEmpty && right.nonEmpty) {
    val (shorter, longer) =
      if (left.length < right.length) (left, right)
      else (right, left)

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lengthByIndexLongerAndIndexShorter: Map[(Int, Int), Int] = Map.empty,
      accumulator: List[Int] = Nil
    ): (Int, List[Int]) =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else
            if ((indexShorter == 0) || (indexLonger == 0)) 1
            else lengthByIndexLongerAndIndexShorter.getOrElse((indexLonger - 1, indexShorter - 1), 0) + 1
        val newCurrentLongestLength =
          if (length > currentLongestLength) length
          else currentLongestLength
        val newLengthByIndexLongerAndIndexShorter =
          if (length > 0) lengthByIndexLongerAndIndexShorter + ((indexLonger, indexShorter) -> length)
          else lengthByIndexLongerAndIndexShorter
        val newAccumulator =
          if ((length < currentLongestLength) || (length == 0)) accumulator
          else {
            val entry = indexShorter - length + 1
            if (length > currentLongestLength) List(entry)
            else entry :: accumulator
          }
        if (indexShorter < shorter.length - 1)
          recursive(
            indexLonger,
            indexShorter + 1,
            newCurrentLongestLength,
            newLengthByIndexLongerAndIndexShorter,
            newAccumulator
          )
        else
          recursive(
            indexLonger + 1,
            0,
            newCurrentLongestLength,
            newLengthByIndexLongerAndIndexShorter,
            newAccumulator
          )
      }
      else (currentLongestLength, accumulator)

    val (length, indexShorters) = recursive()
    if (indexShorters.nonEmpty)
      Some(
        indexShorters
          .map {
            indexShorter =>
              shorter.substring(indexShorter, indexShorter + length)
          }
          .toSet
      )
    else None
  }
  else None

longestCommonSubstringsFast

Refactoring of longestCommonSubstrings to deeply optimize for both CPU and memory.

Eliminating every ounce of inefficiency while staying functional and immutable, execution speed is enhanced by several times over longestCommonSubstrings. The bulk of the cost reductions were achieved by replacing the Map of the entire matrix with a pair of Lists tracking only the current and prior rows.

To easily see the differences from longestCommonSubstrings, please view this visual diff.

def longestCommonSubstringsFast(left: String, right: String): Option[Set[String]] =
  if (left.nonEmpty && right.nonEmpty) {
    val (shorter, longer) =
      if (left.length < right.length) (left, right)
      else (right, left)

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lengthsPrior: List[Int] = List.fill(shorter.length)(0),
      lengths: List[Int] = Nil,
      accumulator: List[Int] = Nil
    ): (Int, List[Int]) =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else lengthsPrior.head + 1
        val newCurrentLongestLength =
          if (length > currentLongestLength) length
          else currentLongestLength
        val newAccumulator =
          if ((length < currentLongestLength) || (length == 0)) accumulator
          else {
            val entry = indexShorter - length + 1
            if (length > currentLongestLength) List(entry)
            else entry :: accumulator
          }
        if (indexShorter < shorter.length - 1)
          recursive(
            indexLonger,
            indexShorter + 1,
            newCurrentLongestLength,
            lengthsPrior.tail,
            length :: lengths,
            newAccumulator
          )
        else
          recursive(
            indexLonger + 1,
            0,
            newCurrentLongestLength,
            0 :: lengths.reverse,
            Nil,
            newAccumulator
          )
      }
      else (currentLongestLength, accumulator)

    val (length, indexShorters) = recursive()
    if (indexShorters.nonEmpty)
      Some(
        indexShorters
          .map {
            indexShorter =>
              shorter.substring(indexShorter, indexShorter + length)
          }
          .toSet
      )
    else None
  }
  else None

longestCommonSubstringsWithIndexes

Refactoring of longestCommonSubstringsFast to enhance the return value by expanding each entry into a tuple of (String, (Int, Int)) which includes both the found substring and the index within each input String at which the substring was found.

CAUTION: This creates a combinatorial expansion of the index pairs if the same String appears more than once.

Again in a tweak towards the functional style, the return value has also been enhanced to never return an empty List by wrapping the List in an Option. If the value returned is a Some, the contained List will always contain at least one item.

def longestCommonSubstringsWithIndexes(left: String, right: String): Option[List[(String, (Int, Int))]] =
  if (left.nonEmpty && right.nonEmpty) {
    val isLeftShorter = left.length < right.length
    val (shorter, longer) =
      if (isLeftShorter) (left, right)
      else (right, left)

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lengthsPrior: List[Int] = List.fill(shorter.length)(0),
      lengths: List[Int] = Nil,
      accumulator: List[(Int, Int)] = Nil
    ): (Int, List[(Int, Int)]) =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else lengthsPrior.head + 1
        val newCurrentLongestLength =
          if (length > currentLongestLength) length
          else currentLongestLength
        val newAccumulator =
          if ((length < currentLongestLength) || (length == 0)) accumulator
          else {
            val entry = (indexLonger - length + 1, indexShorter - length + 1)
            if (length > currentLongestLength) List(entry)
            else entry :: accumulator
          }
        if (indexShorter < shorter.length - 1)
          recursive(
            indexLonger,
            indexShorter + 1,
            newCurrentLongestLength,
            lengthsPrior.tail,
            length :: lengths,
            newAccumulator
          )
        else
          recursive(
            indexLonger + 1,
            0,
            newCurrentLongestLength,
            0 :: lengths.reverse,
            Nil,
            newAccumulator
          )
      }
      else (currentLongestLength, accumulator)

    val (length, indexPairs) = recursive()
    if (indexPairs.nonEmpty)
      Some(
        indexPairs
          .reverse
          .map {
            indexPair =>
              (
                longer.substring(indexPair._1, indexPair._1 + length),
                if (isLeftShorter) indexPair.swap else indexPair
              )
          }
      )
    else None
  }
  else None

firstLongestCommonSubstring

An efficiency-focused version of longestCommonSubstringsFast which provides an opportunity to terminate early when only caring about the first LCS and would like to ignore the others of the same size.

def firstLongestCommonSubstring(left: String, right: String): Option[(String, (Int, Int))] =
  if (left.nonEmpty && right.nonEmpty) {
    val isLeftShorter = left.length < right.length
    val (shorter, longer) =
      if (isLeftShorter) (left, right)
      else (right, left)

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lengthsPrior: List[Int] = List.fill(shorter.length)(0),
      lengths: List[Int] = Nil,
      accumulator: Option[(Int, Int)] = None
    ): Option[(Int, (Int, Int))] =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else lengthsPrior.head + 1
        val newAccumulator =
          if (length > currentLongestLength) Some((indexLonger - length + 1, indexShorter - length + 1))
          else accumulator
        if (length < shorter.length) {
          val newCurrentLongestLength =
            if (length > currentLongestLength) length
            else currentLongestLength
          if (indexShorter < shorter.length - 1)
            recursive(
              indexLonger,
              indexShorter + 1,
              newCurrentLongestLength,
              lengthsPrior.tail,
              length :: lengths,
              newAccumulator
            )
          else
            recursive(
              indexLonger + 1,
              0,
              newCurrentLongestLength,
              0 :: lengths.reverse,
              Nil,
              newAccumulator
            )
        }
        else
          recursive(longer.length, 0, length, lengthsPrior, lengths, newAccumulator) //early terminate
      }
      else accumulator.map((currentLongestLength, _))

    recursive().map {
      case (length, indexPair) =>
        (
          longer.substring(indexPair._1, indexPair._1 + length),
          if (isLeftShorter) indexPair.swap else indexPair
        )
    }
  }
  else None

BONUS:

longestCommonSubstringsUltimate

Refactoring of longestCommonSubstringsFast to add internal implementation mutability while externally retaining the function's referential transparency.

Further eliminating every ounce of inefficiency while staying functional and referentially transparent (engaging in utilizing mutability within the implementation itself which some consider is not validly functional), execution speed is enhanced by almost three times over longestCommonSubstringsFast. The bulk of the cost reductions were by replacing the pair of Lists with a single Array.

To easily see the differences from longestCommonSubstringsFast, please view this visual diff.

def longestCommonSubstringsUltimate(left: String, right: String): Option[Set[String]] =
  if (left.nonEmpty && right.nonEmpty) {
    val (shorter, longer) =
      if (left.length < right.length) (left, right)
      else (right, left)
    val lengths: Array[Int] = new Array(shorter.length) //mutable

    @scala.annotation.tailrec
    def recursive(
      indexLonger: Int = 0,
      indexShorter: Int = 0,
      currentLongestLength: Int = 0,
      lastIterationLength: Int = 0,
      accumulator: List[Int] = Nil
    ): (Int, List[Int]) =
      if (indexLonger < longer.length) {
        val length =
          if (longer(indexLonger) != shorter(indexShorter)) 0
          else
            if (indexShorter == 0) 1
            else lastIterationLength + 1
        val newLastIterationLength = lengths(indexShorter)
        lengths(indexShorter) = length //mutation
        val newCurrentLongestLength =
          if (length > currentLongestLength) length
          else currentLongestLength
        val newAccumulator =
          if ((length < currentLongestLength) || (length == 0)) accumulator
          else {
            val entry = indexShorter - length + 1
            if (length > currentLongestLength) List(entry)
            else entry :: accumulator
          }
        if (indexShorter < shorter.length - 1)
          recursive(
            indexLonger,
            indexShorter + 1,
            newCurrentLongestLength,
            newLastIterationLength,
            newAccumulator
          )
        else
          recursive(
            indexLonger + 1,
            0,
            newCurrentLongestLength,
            newLastIterationLength,
            newAccumulator
          )
      }
      else (currentLongestLength, accumulator)

    val (length, indexShorters) = recursive()
    if (indexShorters.nonEmpty)
      Some(
        indexShorters
          .map {
            indexShorter =>
              shorter.substring(indexShorter, indexShorter + length)
          }
          .toSet
      )
    else None
  }
  else None


来源: stackexchange

问:
How to print a specific item from within a JSON file into python
I want to print a user from a JSON list into Python that I select however I can only print all the users. How do you print a specific user? At the moment I have this which prints all the users out in a ugly format

```<code>import json

with open('Admin_sample.json') as f:
    admin_json = json.load(f)

print(admin_json['staff'])
</code>```

The JSON file looks like this

```<code>{
"staff": [
    {
        "id": "DA7153",
        "name": [
            "Fran\u00c3\u00a7ois",
            "Ullman"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "true"
    },
    {
        "id": "DA7356",
        "name": [
            "Bob",
            "Johnson"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "false"
    },
],
"assets": [
    {
        "asset_name": "ENGAGED SLOTH",
        "asset_type": "File",
        "owner": "DA8333",
        "details": {
            "security": {
                "cia": [
                    "HIGH",
                    "INTERMEDIATE",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "true",
                    "Personal Sensitive": "true",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
        "file_type": "Document",
        "server": {
            "server_name": "ISOLATED UGUISU",
            "ip": [
                10,
                234,
                148,
                52
            ]
        }
    },
    {
        "asset_name": "ISOLATED VIPER",
        "asset_type": "File",
        "owner": "DA8262",
        "details": {
            "security": {
                "cia": [
                    "LOW",
                    "HIGH",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "false",
                    "Personal Sensitive": "false",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
    },
]
</code>```

I just can't work it out. Any help would be appreciated.

Thanks.

答:
Try something like this:</p>

```<code>import json

def findStaffWithId(allStaff, id):
    for staff in allStaff:
        if staff["id"] == id:
            return staff
    return {}  # no staff found

with open('Admin_sample.json') as f:
    admin_json = json.load(f)

print(findStaffWithId(admin_json['staff'], "DA7356"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to print a user from a JSON list into Python that I select however I can only print all the users. How do you print a specific user? At the moment I have this which prints all the users out in a ugly format

import json

with open('Admin_sample.json') as f:
    admin_json = json.load(f)

print(admin_json['staff'])

The JSON file looks like this

{
"staff": [
    {
        "id": "DA7153",
        "name": [
            "Fran\u00c3\u00a7ois",
            "Ullman"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "true"
    },
    {
        "id": "DA7356",
        "name": [
            "Bob",
            "Johnson"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "false"
    },
],
"assets": [
    {
        "asset_name": "ENGAGED SLOTH",
        "asset_type": "File",
        "owner": "DA8333",
        "details": {
            "security": {
                "cia": [
                    "HIGH",
                    "INTERMEDIATE",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "true",
                    "Personal Sensitive": "true",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
        "file_type": "Document",
        "server": {
            "server_name": "ISOLATED UGUISU",
            "ip": [
                10,
                234,
                148,
                52
            ]
        }
    },
    {
        "asset_name": "ISOLATED VIPER",
        "asset_type": "File",
        "owner": "DA8262",
        "details": {
            "security": {
                "cia": [
                    "LOW",
                    "HIGH",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "false",
                    "Personal Sensitive": "false",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
    },
]

I just can't work it out. Any help would be appreciated.

Thanks.

Body:
Try something like this:

import json

def findStaffWithId(allStaff, id):
    for staff in allStaff:
        if staff["id"] == id:
            return staff
    return {}  # no staff found

with open('Admin_sample.json') as f:
    admin_json = json.load(f)

print(findStaffWithId(admin_json['staff'], "DA7356"))


答:
You can list all the users name with

users = [user["name"] for user in admin_json['staff']]

Title: How to print a specific item from within a JSON file into python


问:
Purpose of python antigravity module
I was just digging up some cool modules in python, and this antigravity module seems cool, and full of potentials, but I am not sure if it is what it sounds like.

Is there any use for it other than displaying the comic page on a browser? If there is, please do tell what it can be used for. Is there an example? Note that below in the link, that when the guy asks "But how are you flying?", the python dude answers, "I just typed import antigravity."

I was wondering if there actually is a way to make things fly by just importing antigravity, maybe in Pygame or other cross-platforms modules.

Here is the link...

```<code>import antigravity
def main():
    antigravity.fly()
if __name__=='__main__':
    main()
</code>```

答:
It's an easter egg. Here are some more, have fun!

>>> import __hello__
Hello world!
```
<pre class="lang-none prettyprint-override"><code>>>> import __phello__
Hello world!
</code>```

>>> from __future__ import braces
SyntaxError: not a chance
```
<pre class="lang-none prettyprint-override"><code>>>> hash(float('inf'))
314159
</code>```

>>> hash(-1)
-2
```
<pre class="lang-none prettyprint-override"><code>>>> from __future__ import barry_as_FLUFL
>>> 1 <> 2
True
>>> 1 != 2
  File "<stdin>", line 1
    1 != 2
      ^^
SyntaxError: with Barry as BDFL, use '<>' instead of '!='
</code>```

>>> import types
>>> help(types.CodeType)
Help on class code in module builtins:

class code(object)
 |  # ...
 |
 |  Create a code object.  Not for the faint of heart.
 |
# ...
```
<p>And last but not least, the legendary Zen of Python:</p>
<pre class="lang-none prettyprint-override"><code>>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
</code>```

Title: Purpose of python antigravity module

Body:
I was just digging up some cool modules in python, and this antigravity module seems cool, and full of potentials, but I am not sure if it is what it sounds like.

Is there any use for it other than displaying the comic page on a browser? If there is, please do tell what it can be used for. Is there an example? Note that below in the link, that when the guy asks "But how are you flying?", the python dude answers, "I just typed import antigravity."

I was wondering if there actually is a way to make things fly by just importing antigravity, maybe in Pygame or other cross-platforms modules.

Here is the link...

import antigravity
def main():
    antigravity.fly()
if __name__=='__main__':
    main()

Body:
It's an easter egg. Here are some more, have fun!

>>> import __hello__
Hello world!

>>> import __phello__
Hello world!

>>> from __future__ import braces
SyntaxError: not a chance

>>> hash(float('inf'))
314159

>>> hash(-1)
-2

>>> from __future__ import barry_as_FLUFL
>>> 1 <> 2
True
>>> 1 != 2
  File "<stdin>", line 1
    1 != 2
      ^^
SyntaxError: with Barry as BDFL, use '<>' instead of '!='

>>> import types
>>> help(types.CodeType)
Help on class code in module builtins:

class code(object)
 |  # ...
 |
 |  Create a code object.  Not for the faint of heart.
 |
# ...

And last but not least, the legendary Zen of Python:

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


问:
Node.js + Joi how to display a custom error messages?
It seems pretty straight forward to validate user's input in Node.js RESTapi with Joi.

But the problem is that my app is not written in English.
That means I need to send a custom written messages to the frontend user.

I have googled for this and only found issues.

Maybe could someone give a solution for this?

This is the code I am using to validate with the Joi system:

```<code>    var schema = Joi.object().keys({
      firstName: Joi.string().min(5).max(10).required(),
      lastName: Joi.string().min(5).max(10).required()
      ..
    });

    Joi.validate(req.body, schema, function(err, value) {
      if (err) {
        return catched(err.details);
      }
    });

    function catched(reject) {
      res.json({
        validData: false,
        errors: reject
      });
    }
</code>```

Plus, is there a way to use Joi in client side?

Thanks!

答:
The best solution I found was :

Create a Middleware for JOI validation

Validator.js - You can create your custom error object

```<code>const Joi = require('Joi');

module.exports = schema => (req, res, next) => {
  const result = Joi.validate(req.body, schema);
  if (result.error) {
    return res.status(422).json({
      errorCause: result.error.name,
      missingParams: result.error.details[0].path,
      message: result.error.details[0].message
    });
  }
  next();
};

</code>```

In the routes or controller pass this middleware function

```<code>
const joiValidator = require('../utils/validator'); // Wherever you have declare the validator or middlerware

   const  userSchema = joi.object().keys({
    email : joi.string().email().required(),
    password : joi.string().required()
  });

  routes.routes('/').get(joiValidator(userSchema), (req, res) => {
    res.status(200).send('Person Check');
  });

</code>```

ContentLicense: CC BY-SA 3.0

Body:
It seems pretty straight forward to validate user's input in Node.js RESTapi with Joi.

But the problem is that my app is not written in English.
That means I need to send a custom written messages to the frontend user.

I have googled for this and only found issues.

Maybe could someone give a solution for this?

This is the code I am using to validate with the Joi system:

    var schema = Joi.object().keys({
      firstName: Joi.string().min(5).max(10).required(),
      lastName: Joi.string().min(5).max(10).required()
      ..
    });

    Joi.validate(req.body, schema, function(err, value) {
      if (err) {
        return catched(err.details);
      }
    });

    function catched(reject) {
      res.json({
        validData: false,
        errors: reject
      });
    }

Plus, is there a way to use Joi in client side?

Thanks!

Body:
The best solution I found was :

Create a Middleware for JOI validation

Validator.js - You can create your custom error object

const Joi = require('Joi');

module.exports = schema => (req, res, next) => {
  const result = Joi.validate(req.body, schema);
  if (result.error) {
    return res.status(422).json({
      errorCause: result.error.name,
      missingParams: result.error.details[0].path,
      message: result.error.details[0].message
    });
  }
  next();
};

In the routes or controller pass this middleware function

const joiValidator = require('../utils/validator'); // Wherever you have declare the validator or middlerware

   const  userSchema = joi.object().keys({
    email : joi.string().email().required(),
    password : joi.string().required()
  });

  routes.routes('/').get(joiValidator(userSchema), (req, res) => {
    res.status(200).send('Person Check');
  });


问:
Function in stateless component is not working
In my below code it is giving an error: CreateParticipant.jsx:9 Uncaught ReferenceError: handleInputChangeName is not defined

I could not understand what is the problem. I have already defined the function, then also it is giving such an error.

Can someone please help me in finding out the problem.

```<code>import React, { useState, useEffect } from 'react';
import { Redirect } from 'react-router-dom';

const CreateParticipant = () => {

  const [name, setname] = useState([])
  const [email, setemail] = useState([])

  handleInputChange = (event) => {
    if(event.target.name === "name"){
      setname(event.target.value)
    }
    else if(event.target.name === "email"){
      setemail(event.target.value)
    }
  }

  async function createPostRequest(event) {
    // console.log('this.state', this.state);
    const statepost = { name, email }
    await fetch('/api/v1/participants', {
      method: 'post',
      body: JSON.stringify(statepost),
      headers: { 'Content-Type': 'application/json' },
    }).then((response) => {
      alert('Post created successfully');
      location.href = '/';
    });
  }

  useEffect(() => {
    createPostRequest()
  }, []);

  return (
    <div>
      <h3>New Post</h3>
      <div>
        <label>name: </label>
        <input
          type='text'
          name='name'
          value={name}
          onChange={this.handleInputChange}
        />
      </div>
      <div>
        <label>email: </label>
        <input
          type='text'
          name='email'
          value={email}
          onChange={this.handleInputChange}
        />
      </div>
      {/* <div>
          <label>created_at: </label>
          <input
            type='text'
            name='created_at'
            value={created_at}
            onChange={this.handleInputChange}
            />
        </div> */}
      <button onClick={this.createPostRequest}>Create</button>
    </div>
  );
}

export default CreateParticipant;
</code>```

答:
Unlike in a class component where functionName = () => {} is valid, a function component is just that - a function. You need either var, let or const:

```<code>const handleInputChangeName = (event) => {
  if(event.target.name === "name"){
    setname(event.target.value)
  }
  else if(event.target.name === "email"){
    setemail(event.target.value)
  }
}
</code>```

Additionally, the this. is not needed since the functions are in the scope of the same function, e.g.:

```<code>onChange={handleInputChange}
// ...
onClick={createPostRequest}
</code>```

Body:
In my below code it is giving an error: CreateParticipant.jsx:9 Uncaught ReferenceError: handleInputChangeName is not defined

I could not understand what is the problem. I have already defined the function, then also it is giving such an error.

Can someone please help me in finding out the problem.

import React, { useState, useEffect } from 'react';
import { Redirect } from 'react-router-dom';

const CreateParticipant = () => {

  const [name, setname] = useState([])
  const [email, setemail] = useState([])

  handleInputChange = (event) => {
    if(event.target.name === "name"){
      setname(event.target.value)
    }
    else if(event.target.name === "email"){
      setemail(event.target.value)
    }
  }

  async function createPostRequest(event) {
    // console.log('this.state', this.state);
    const statepost = { name, email }
    await fetch('/api/v1/participants', {
      method: 'post',
      body: JSON.stringify(statepost),
      headers: { 'Content-Type': 'application/json' },
    }).then((response) => {
      alert('Post created successfully');
      location.href = '/';
    });
  }

  useEffect(() => {
    createPostRequest()
  }, []);

  return (

New Post

        name:
        <input
          type='text'
          name='name'
          value={name}
          onChange={this.handleInputChange}
        />

        email:
        <input
          type='text'
          name='email'
          value={email}
          onChange={this.handleInputChange}
        />

      {/*

          created_at:
          <input
            type='text'
            name='created_at'
            value={created_at}
            onChange={this.handleInputChange}
            />

 */}
      <button onClick={this.createPostRequest}>Create</button>

  );
}

export default CreateParticipant;

Body:
Unlike in a class component where functionName = () => {} is valid, a function component is just that - a function. You need either var, let or const:

const handleInputChangeName = (event) => {
  if(event.target.name === "name"){
    setname(event.target.value)
  }
  else if(event.target.name === "email"){
    setemail(event.target.value)
  }
}

Additionally, the this. is not needed since the functions are in the scope of the same function, e.g.:

onChange={handleInputChange}
// ...
onClick={createPostRequest}


问:
How to highlight SQL keywords using a regular expression?
I would like to highlight SQL keywords that occur within a string in a syntax highlighter. Here are the rules I would like to have:

Match the keywords SELECT and FROM (others will be added, but we'll start here). Must be all-caps

Must be contained in a string -- either starting with ' or "

The first word in that string (ignoring whitespace preceding it) should be one of the keywords.

This of course is not comprehensive (can ignore escapes within a string), but I'd like to start here.

Here are a few examples:

SELECT * FROM main -- will not match (not in a string)

"SELECT name FROM main" -- will match

"

      SELECT name FROM main" -- will match

"""Here is a SQL statement:

SELECT * FROM main""" -- no, string does not start with a keyword (SELECT...).

The only way I thought to do it in a single regex would be with a negative lookbehind...but then it would not be fixed width, as we don't know when the string starts. Something like:

(?<=["']\s*(SELECT)\s*)(SELECT|FROM)

But this of course won't work:

Would something like this be possible to do in a single regex?

答:
You could use capturing groups:

```<code>(.*["']\s*\K)(?(1)(SELECT|FROM).*(SELECT|FROM)|)
</code>```

In this case $2 would refer to the first keyword and $3 would refer to the second keyword.  This also only works if there are only two keywords and only one string on a line, which seems to be true in all of your examples, but if those restrictions don't work for you, let me know.

Body:
You could use capturing groups:

(.*["']\s*\K)(?(1)(SELECT|FROM).*(SELECT|FROM)|)

In this case $2 would refer to the first keyword and $3 would refer to the second keyword.  This also only works if there are only two keywords and only one string on a line, which seems to be true in all of your examples, but if those restrictions don't work for you, let me know.


问:
collapsing duplicate rows in data.table in R
I am working on a large data.table, where I am taking lead/lag values. This is an reduced example of my data:

```<code>> data.table(from = c(2012, 2013, 2014, 2012, 2013, 2013, 2013, 2014, 2012, 2013, 2014),
+            item = c("A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"),
+            loc = c(NA, NA, NA, NA, NA, "other", "others", NA, "NY", "NY", "M"))
    from item    loc
 1: 2012    A   <NA>
 2: 2013    A   <NA>
 3: 2014    A   <NA>
 4: 2012    B   <NA>
 5: 2013    B   <NA>
 6: 2013    B  other
 7: 2013    B others
 8: 2014    C   <NA>
 9: 2012    C     NY
10: 2013    C     NY
11: 2014    C      M
</code>```

Item B has multiple enteries for the same year & item combination, because the loc is different. For every from & item I want them to appear only once. I would like to collapse these cases and have "multiple" in the loc column. How can this be done with data.table in R?

desired output:

```<code>    from item    loc
 1: 2012    A   <NA>
 2: 2013    A   <NA>
 3: 2014    A   <NA>
 4: 2012    B   <NA>
 5: 2013    B   multiple
 8: 2014    C   <NA>
 9: 2012    C     NY
10: 2013    C     NY
11: 2014    C      M
</code>```

答:
You could do:</p>

```<code>aggregate(loc ~ from + item, df, function(x)ifelse(length(x) > 1, "multiple", x), na.action = NULL)
  from item      loc
1 2012    A     <NA>
2 2013    A     <NA>
3 2014    A     <NA>
4 2012    B     <NA>
5 2013    B multiple
6 2012    C       NY
7 2013    C       NY
8 2014    C multiple
</code>```

Body:
I am working on a large data.table, where I am taking lead/lag values. This is an reduced example of my data:

> data.table(from = c(2012, 2013, 2014, 2012, 2013, 2013, 2013, 2014, 2012, 2013, 2014),
+            item = c("A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"),
+            loc = c(NA, NA, NA, NA, NA, "other", "others", NA, "NY", "NY", "M"))
    from item    loc
 1: 2012    A   <NA>
 2: 2013    A   <NA>
 3: 2014    A   <NA>
 4: 2012    B   <NA>
 5: 2013    B   <NA>
 6: 2013    B  other
 7: 2013    B others
 8: 2014    C   <NA>
 9: 2012    C     NY
10: 2013    C     NY
11: 2014    C      M

Item B has multiple enteries for the same year & item combination, because the loc is different. For every from & item I want them to appear only once. I would like to collapse these cases and have "multiple" in the loc column. How can this be done with data.table in R?

desired output:

    from item    loc
 1: 2012    A   <NA>
 2: 2013    A   <NA>
 3: 2014    A   <NA>
 4: 2012    B   <NA>
 5: 2013    B   multiple
 8: 2014    C   <NA>
 9: 2012    C     NY
10: 2013    C     NY
11: 2014    C      M

Body:
You could do:

aggregate(loc ~ from + item, df, function(x)ifelse(length(x) > 1, "multiple", x), na.action = NULL)
  from item      loc
1 2012    A     <NA>
2 2013    A     <NA>
3 2014    A     <NA>
4 2012    B     <NA>
5 2013    B multiple
6 2012    C       NY
7 2013    C       NY
8 2014    C multiple


答:
Modules are always run in strict mode where implicit globals are forbidden.

You need to explicitly declare the variable (with const (or let or var)).

```<code>const handleInputChangeName = (event) => {
</code>```

Title: Function in stateless component is not working

Body:
Modules are always run in strict mode where implicit globals are forbidden.

You need to explicitly declare the variable (with const (or let or var)).

const handleInputChangeName = (event) => {


问:
how to repeat a function with some arguments on some process with pool.starmap
I used multiprocessing in python for repeating a function 1000 times with one number as input on some cores and I used the code:

```<code>def GradientProccess(m):
    x=random.seed(os.getpid()*m)
    print(random.seed(os.getpid()*m))
      .
      .
      .
    return()

if __name__ == '__main__':
    __spec__ = "ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>)"

    with Pool(processes=8) as pool:

        result=pool.map(GradientProccess,range(1000))
</code>```

But now I am going to use multiprocessing for repeating the function with 2 lists as the input of the function. I want to use starmap but how can I repeat it 1000 times? I wrote this code but it is not correct:

```<code> def GradientProccess(m,list1,list2):
        x=random.seed(os.getpid()*m)
        print(random.seed(os.getpid()*m))
          .
          .
          .
        return()

    if __name__ == '__main__':
        __spec__ = "ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>)"
        list1=[4,3]
        list2=[5,7]
        with Pool(processes=8) as pool:

            result=pool.starmap(GradientProccess,[list1,list2],range(1000))
</code>```

How can I use starmap for repeat a function with 2 fixed lists as arguments?
Is there any other way to do this?

答:
Since the function consumes both lists entirely (and not a combination of elements from each list), you don't need to use starmap.  Instead, you can create a partial function and use it with map as follows.

```<code>def gradiant_process(m, l1, l2):
    ...

with Pool(processes=8) as pool:
    ...
    import functools
    partial_gp = functools.partial(gradient_process, l1=list1, l2=list2)
    result = pool.map(partial_gp, range(1000))
</code>```

Body:
I used multiprocessing in python for repeating a function 1000 times with one number as input on some cores and I used the code:

def GradientProccess(m):
    x=random.seed(os.getpid()*m)
    print(random.seed(os.getpid()*m))
      .
      .
      .
    return()

if __name__ == '__main__':
    __spec__ = "ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>)"

    with Pool(processes=8) as pool:

        result=pool.map(GradientProccess,range(1000))

But now I am going to use multiprocessing for repeating the function with 2 lists as the input of the function. I want to use starmap but how can I repeat it 1000 times? I wrote this code but it is not correct:

 def GradientProccess(m,list1,list2):
        x=random.seed(os.getpid()*m)
        print(random.seed(os.getpid()*m))
          .
          .
          .
        return()

    if __name__ == '__main__':
        __spec__ = "ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>)"
        list1=[4,3]
        list2=[5,7]
        with Pool(processes=8) as pool:

            result=pool.starmap(GradientProccess,[list1,list2],range(1000))

How can I use starmap for repeat a function with 2 fixed lists as arguments?
Is there any other way to do this?

Body:
Since the function consumes both lists entirely (and not a combination of elements from each list), you don't need to use starmap.  Instead, you can create a partial function and use it with map as follows.

def gradiant_process(m, l1, l2):
    ...

with Pool(processes=8) as pool:
    ...
    import functools
    partial_gp = functools.partial(gradient_process, l1=list1, l2=list2)
    result = pool.map(partial_gp, range(1000))


问:
PixiJS: How to use its ResizePlugin
At https://pixijs.download/dev/docs/PIXI.Application.html#queueResize, the PixiJS API documents a queueResize() function, but when I try to use it in my browser application I get the following error:

```<code>TypeError: app.queueResize is not a function
</code>```

Here's a typical example:

let pixi_container = document.getElementById("pixi_container");

app = new PIXI.Application(
    {
        backgroundColor: 0xAAAAAA,
        resizeTo: pixi_container
    }
);

pixi_container.appendChild(app.view);

app.queueResize();  // <-- error here
```

I'm using the latest PixiJS release (as of today).

Is there something I need to do before calling the queueResize() function?

答:
Method is undefined because it comes in plugin ( https://pixijs.download/dev/docs/packages_app_src_ResizePlugin.js.html#line36 ) - and probably you didnt registered this plugin yet.

You need to register ResizePlugin and then this method should work. See for example: https://medium.com/@bigtimebuddy/new-pixijs-v5-plugins-75a7d86afb6

Title: PixiJS: How to use its ResizePlugin

Body:
At https://pixijs.download/dev/docs/PIXI.Application.html#queueResize, the PixiJS API documents a queueResize() function, but when I try to use it in my browser application I get the following error:

TypeError: app.queueResize is not a function

Here's a typical example:

let pixi_container = document.getElementById("pixi_container");

app = new PIXI.Application(
    {
        backgroundColor: 0xAAAAAA,
        resizeTo: pixi_container
    }
);

pixi_container.appendChild(app.view);

app.queueResize();  // <-- error here

I'm using the latest PixiJS release (as of today).

Is there something I need to do before calling the queueResize() function?


问:
Battleship game: place ships randomly in java
I am writing the code of the game. How can I do this board? </p>

```<code>It should be like this example.

  0 1 2 3 4 5 6 7 8 9
0 . . . . . . . . . .
1 . . o . . . . . . .
2 . . . . . . . o . .
3 . . . . . . . o . .
4 . . . o o . . o . .
5 . . . . . . . o . o
6 . . . . . . . . . o
7 . o o o . . . . . o
8 . . . . . . . . . o
9 . . . . . . . . . o
</code>```

答:
Your loop is iterating only 5 times and it'll place only one 'o' in each iteration.
One of the solutions could be, have a 10x10 nested loop, inside that loop make another loop of variable size, that will control the size of the ship. Finally, add one more condition to check if there's already a ship around or not. </p>

Body:
I am writing the code of the game. How can I do this board?

It should be like this example.

  0 1 2 3 4 5 6 7 8 9
0 . . . . . . . . . .
1 . . o . . . . . . .
2 . . . . . . . o . .
3 . . . . . . . o . .
4 . . . o o . . o . .
5 . . . . . . . o . o
6 . . . . . . . . . o
7 . o o o . . . . . o
8 . . . . . . . . . o
9 . . . . . . . . . o


问:
Linq - how to write group by query to get quantity of each product
Hello every one I have a data as follows

```<code>Item    Qty Type
1       2   Purchase
1       3   Sales
1       8   Return

2       5   Purchase
2       4   Sales
2       5   Return
</code>```

Now I have a requirement of getting quantity of each item by Subtracting Sales and Return with Purchase
And my final output would be

```<code>item    Qty
1      -9
2      -4
</code>```

Note : To get quantity: Qty => (Purchase Qty - SalesQty - Return Qty) eg: (2-3-8)

So how can I write this query on LINQ or in SQL

答:
SQL Query:

```<code>SELECT Item, SUM(CASE Type WHEN 'Purchase' THEN Qty ELSE -Qty END) AS Qty
FROM Table
GROUP BY Item
</code>```

LINQ:

```<code>Items
.GroupBy(p => p.Item)
.Select(p => new
{
     Item = p.Key,
     Qty = p.Sum(x => x.Type == "Purchase" ? x.Qty : -x.Qty)
});
</code>```

Body:
Hello every one I have a data as follows

Item    Qty Type
1       2   Purchase
1       3   Sales
1       8   Return

2       5   Purchase
2       4   Sales
2       5   Return

Now I have a requirement of getting quantity of each item by Subtracting Sales and Return with Purchase
And my final output would be

item    Qty
1      -9
2      -4

Note : To get quantity: Qty => (Purchase Qty - SalesQty - Return Qty) eg: (2-3-8)

So how can I write this query on LINQ or in SQL

Body:
SQL Query:

SELECT Item, SUM(CASE Type WHEN 'Purchase' THEN Qty ELSE -Qty END) AS Qty
FROM Table
GROUP BY Item

LINQ:

Items
.GroupBy(p => p.Item)
.Select(p => new
{
     Item = p.Key,
     Qty = p.Sum(x => x.Type == "Purchase" ? x.Qty : -x.Qty)
});


问:
Why does the time function and print() execute before the label is created in the Tkinter window
```<code>def createLabel():
    l = label(text='Label Created')
    l.grid(row=10, column=3)
    time.sleep(5)
    print('Label Created')

b = Button(text='Click to create a label', command=createLabel)
</code>```

Output:
After 5 seconds
printed: Label Created
Then the label appears

**
How to make the label appear on the window first then print() the "Label Created message"

Please help me with this..
**

答:
Just use after(ms, func, *args). Here is an example of your case.

```<code>from tkinter import *
import tkinter as tk

def createLabel():
    l = Label(text='Label Created')
    l.pack(side=BOTTOM)
    b.after(5000, print, 'Label created')

root = tk.Tk()
b = Button(root,text='Click to create a label', command=createLabel)
b.pack(side=TOP)
root.mainloop()
</code>```

Body:
def createLabel():
    l = label(text='Label Created')
    l.grid(row=10, column=3)
    time.sleep(5)
    print('Label Created')

b = Button(text='Click to create a label', command=createLabel)

Output:
After 5 seconds
printed: Label Created
Then the label appears

**
How to make the label appear on the window first then print() the "Label Created message"

Please help me with this..
**

Body:
Just use after(ms, func, *args). Here is an example of your case.

from tkinter import *
import tkinter as tk

def createLabel():
    l = Label(text='Label Created')
    l.pack(side=BOTTOM)
    b.after(5000, print, 'Label created')

root = tk.Tk()
b = Button(root,text='Click to create a label', command=createLabel)
b.pack(side=TOP)
root.mainloop()


问:
Radiobuttonlist event not always firing
I have a radiobuttonlist with a selectedindexchanged event that updates a search function.  One of the items is specified in the aspx, and the others are appended databound items.  No matter what I set as the default, that item will not fire the event.  All other items will fire the event.  Also, it seems that after the "dead" item is selected, the event won't fire at all.

How can I track down the error and correct?  Here is current code.

EDIT: Sorry if the short version was misleading.  I wasn't sure what to include.  Here is the whole page.

All aspx:

```<code>     <%@ Page Language="C#" MasterPageFile="~/MSDS/MSDS.master" EnableEventValidation="false"
    AutoEventWireup="true" CodeFile="SearchMSDS.aspx.cs" Inherits="MSDS_ByDept" Title="NCLWeb - Search MSDS" %>

<%@ Register Assembly="SqlWhereBuilder" Namespace="UNLV.IAP.WebControls" TagPrefix="cc1" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PageContent" runat="Server">
    <h2>
        <asp:Label ID="lblTitle" runat="server">Search Active MSDS</asp:Label></h2>
    <table class="style1">
        <tr>
            <td style="width: 435px" valign="top">
                <asp:Panel runat="server" ID="pnlSearch" DefaultButton="btnSearch">
                    <asp:TextBox ID="txtSimpleSearch" runat="server" Width="262px"></asp:TextBox>
                    <asp:Button ID="btnSearch" runat="server" Text="Search" Width="96px" OnClick="btnSearch_Click" />
                    <br />
                    <asp:LinkButton ID="btnAdvSearch" runat="server" OnClick="btnAdvSearch_Click" Font-Size="Small">Show Advanced Search</asp:LinkButton>
                </asp:Panel>
                <asp:Panel ID="pnlAdvSearch" runat="server" Width="635px" DefaultButton="btnRunAdvSearch">
                    <asp:Button ID="btnRunAdvSearch" runat="server" OnClick="btnRunAdvSearch_Click" Text="Advanced Search" />
                    <cc1:SqlWhereBuilder ID="SqlWhereBuilder1" runat="server" ClientCodeLocation="../JavaScripts/SqlWhereBuilder.js"
                        FieldsFile="../ConfigFiles/SearchMSDS.config" OperatorListsFile="../ConfigFiles/SearchMSDS.config"
                        ValueEntryFile="../ConfigFiles/SearchMSDS.config">
                    </cc1:SqlWhereBuilder>
                    <br />
                    <br />
                </asp:Panel>
                <cc2:CollapsiblePanelExtender ID="pnlAdvSearch_CollapsiblePanelExtender" runat="server"
                    CollapseControlID="btnAdvSearch" Collapsed="True" Enabled="True" ExpandControlID="btnAdvSearch"
                    TargetControlID="pnlAdvSearch">
                </cc2:CollapsiblePanelExtender>
            </td>
            <td valign="top">
                <asp:Panel ID="pnlStatus" runat="server">
                    <asp:RadioButtonList ID="rblStatus" runat="server" AppendDataBoundItems="True"
                        AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="DisplayValue"
                        DataValueField="Value" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
                        RepeatDirection="Horizontal" CellPadding="3" CellSpacing="3"
                        CausesValidation="True" Visible="True">
                        <asp:ListItem Selected="True">All</asp:ListItem>
                    </asp:RadioButtonList>
                </asp:Panel>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                    SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
                    <SelectParameters>
                        <asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
                    </SelectParameters>
                </asp:SqlDataSource>
                <asp:UpdatePanel runat="server" ID="upd2">
                    <ContentTemplate>
                        <asp:Button ID="btnExport" runat="server" Text="Export Results"
                            OnClick="btnExport_Click1" UseSubmitBehavior="False" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </td>
        </tr>
    </table>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100" DynamicLayout="False">
                <ProgressTemplate>
                    <img src="../images/loading.gif" alt="Loading..." style="text-align: center" />
                    <asp:Label ID="lblProgress" runat="server"></asp:Label></ProgressTemplate>
            </asp:UpdateProgress>
            <asp:GridView ID="gridResults" runat="server" DataSourceID="sqlMSDS" OnRowDataBound="GridView1_RowDataBound"
                AllowPaging="True" PageSize="25" AllowSorting="True" OnSelectedIndexChanged="gridResults_SelectedIndexChanged"
                AutoGenerateColumns="False" EmptyDataText="No matching MSDS Sheets." OnSorted="gridResults_Sorted">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" Visible="false"
                        ReadOnly="True" SortExpression="ID" />
                    <asp:BoundField DataField="ChemicalTitle" HeaderText="ChemicalTitle" SortExpression="ChemicalTitle" />
                    <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
                    <asp:BoundField DataField="UsageDept" HeaderText="UsageDept" SortExpression="UsageDept" />
                    <asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
                    <asp:BoundField DataField="Health" HeaderText="Health" visible="false" SortExpression="Health" />
                    <asp:BoundField DataField="Fire" HeaderText="Fire"  visible="false" SortExpression="Fire" />
                    <asp:BoundField DataField="Reactivity" HeaderText="Reactivity"  visible="false" SortExpression="Reactivity" />
                    <asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated" SortExpression="DateUpdated" />
                </Columns>
                <SelectedRowStyle BackColor="Yellow" />
            </asp:GridView>
            <asp:SqlDataSource ID="sqlMSDS" OnSelected="sqlMSDS_OnSelected" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                SelectCommand="SELECT [ID]
                                      ,[ChemicalTitle]
                                      ,[Manufacturer]
                                      ,[UsageDept]
                                      ,[Notes]
                                      ,[Health]
                                      ,[Fire]
                                      ,[Reactivity]
                                      ,[DateUpdated]
                                      FROM [msds_Sheets]" OnSelecting="sqlMSDS_Selecting"></asp:SqlDataSource>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="btnRunAdvSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="rblStatus" EventName="SelectedIndexChanged" />
            <asp:AsyncPostBackTrigger ControlID="btnExport" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>
    <br />
</asp:Content>
</code>```

And code-behind:

```<code>    List<String> safeWords = new List<String>();

protected void Page_Load(object sender, EventArgs e)
{
    pnlStatus.Visible = User.IsInRole("msds_Admin");

    gridResults.DataKeyNames = new String[] { "id" };

    txtSimpleSearch.Focus();

    if (!IsPostBack)
    {
        safeWords.Add("delete");
        safeWords.Add("insert");
        safeWords.Add("update");
        safeWords.Add("set");
        safeWords.Add("exec");
        safeWords.Add("N'");

        sqlMSDS.SelectCommand += " Where status = 0 ";

        Session["Sql"] = sqlMSDS.SelectCommand;

        try
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand.Remove(sqlMSDS.SelectCommand.IndexOf("Where"));
        }
        catch (Exception)
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand;
        }
    }
}

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ((Label)UpdateProgress1.FindControl("lblProgress")).Text = "Searching...";

            if (btnSearch.Visible)
            {
                btnSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
            else
            {
                btnRunAdvSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    if (sqlMSDS.SelectCommand.Contains("Where"))
                    {
                        sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                    }
                    else
                    {
                        sqlMSDS.SelectCommand += " Where Status = " + RadioButtonList1.SelectedValue;
                    }
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
        }
</code>```

答:
Does this RadioButtonList specified as AsyncPostBackTrigger for another UpdatePanel? If so, check following link: CheckedChanged event not firing on a radio button within UpdatePanel

I have reproduce that behaviour and fix this with the following script:

```<code> $(function () {
        $("input[type='radio']:first", $("#<%= RadioButtonList1.ClientID %>")).attr("checked", true);
    });
</code>```

if you can't use the jQuery try this javascript:

```<code> window.onload = function () {
        window.document.getElementById("<%= RadioButtonList1.ClientID %>_0").checked = true;
    };

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "RadioButtonListDefaultValue", String.Format("window.document.getElementById('{0}_0').checked = true;", RadioButtonList1.ClientID), true);
        }
    }
</code>```

Title: Radiobuttonlist event not always firing

Body:
I have a radiobuttonlist with a selectedindexchanged event that updates a search function.  One of the items is specified in the aspx, and the others are appended databound items.  No matter what I set as the default, that item will not fire the event.  All other items will fire the event.  Also, it seems that after the "dead" item is selected, the event won't fire at all.

How can I track down the error and correct?  Here is current code.

EDIT: Sorry if the short version was misleading.  I wasn't sure what to include.  Here is the whole page.

All aspx:

     <%@ Page Language="C#" MasterPageFile="~/MSDS/MSDS.master" EnableEventValidation="false"
    AutoEventWireup="true" CodeFile="SearchMSDS.aspx.cs" Inherits="MSDS_ByDept" Title="NCLWeb - Search MSDS" %>

<%@ Register Assembly="SqlWhereBuilder" Namespace="UNLV.IAP.WebControls" TagPrefix="cc1" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PageContent" runat="Server">

        <asp:Label ID="lblTitle" runat="server">Search Active MSDS</asp:Label>

                <asp:Panel runat="server" ID="pnlSearch" DefaultButton="btnSearch">
                    <asp:TextBox ID="txtSimpleSearch" runat="server" Width="262px"></asp:TextBox>
                    <asp:Button ID="btnSearch" runat="server" Text="Search" Width="96px" OnClick="btnSearch_Click" />

                    <asp:LinkButton ID="btnAdvSearch" runat="server" OnClick="btnAdvSearch_Click" Font-Size="Small">Show Advanced Search</asp:LinkButton>
                </asp:Panel>
                <asp:Panel ID="pnlAdvSearch" runat="server" Width="635px" DefaultButton="btnRunAdvSearch">
                    <asp:Button ID="btnRunAdvSearch" runat="server" OnClick="btnRunAdvSearch_Click" Text="Advanced Search" />
                    <cc1:SqlWhereBuilder ID="SqlWhereBuilder1" runat="server" ClientCodeLocation="../JavaScripts/SqlWhereBuilder.js"
                        FieldsFile="../ConfigFiles/SearchMSDS.config" OperatorListsFile="../ConfigFiles/SearchMSDS.config"
                        ValueEntryFile="../ConfigFiles/SearchMSDS.config">
                    </cc1:SqlWhereBuilder>

                </asp:Panel>
                <cc2:CollapsiblePanelExtender ID="pnlAdvSearch_CollapsiblePanelExtender" runat="server"
                    CollapseControlID="btnAdvSearch" Collapsed="True" Enabled="True" ExpandControlID="btnAdvSearch"
                    TargetControlID="pnlAdvSearch">
                </cc2:CollapsiblePanelExtender>

                <asp:Panel ID="pnlStatus" runat="server">
                    <asp:RadioButtonList ID="rblStatus" runat="server" AppendDataBoundItems="True"
                        AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="DisplayValue"
                        DataValueField="Value" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
                        RepeatDirection="Horizontal" CellPadding="3" CellSpacing="3"
                        CausesValidation="True" Visible="True">
                        <asp:ListItem Selected="True">All</asp:ListItem>
                    </asp:RadioButtonList>
                </asp:Panel>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                    SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
                    <SelectParameters>
                        <asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
                    </SelectParameters>
                </asp:SqlDataSource>
                <asp:UpdatePanel runat="server" ID="upd2">
                    <ContentTemplate>
                        <asp:Button ID="btnExport" runat="server" Text="Export Results"
                            OnClick="btnExport_Click1" UseSubmitBehavior="False" />
                    </ContentTemplate>
                </asp:UpdatePanel>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100" DynamicLayout="False">
                <ProgressTemplate>

                    <asp:Label ID="lblProgress" runat="server"></asp:Label></ProgressTemplate>
            </asp:UpdateProgress>
            <asp:GridView ID="gridResults" runat="server" DataSourceID="sqlMSDS" OnRowDataBound="GridView1_RowDataBound"
                AllowPaging="True" PageSize="25" AllowSorting="True" OnSelectedIndexChanged="gridResults_SelectedIndexChanged"
                AutoGenerateColumns="False" EmptyDataText="No matching MSDS Sheets." OnSorted="gridResults_Sorted">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" Visible="false"
                        ReadOnly="True" SortExpression="ID" />
                    <asp:BoundField DataField="ChemicalTitle" HeaderText="ChemicalTitle" SortExpression="ChemicalTitle" />
                    <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
                    <asp:BoundField DataField="UsageDept" HeaderText="UsageDept" SortExpression="UsageDept" />
                    <asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
                    <asp:BoundField DataField="Health" HeaderText="Health" visible="false" SortExpression="Health" />
                    <asp:BoundField DataField="Fire" HeaderText="Fire"  visible="false" SortExpression="Fire" />
                    <asp:BoundField DataField="Reactivity" HeaderText="Reactivity"  visible="false" SortExpression="Reactivity" />
                    <asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated" SortExpression="DateUpdated" />
                </Columns>
                <SelectedRowStyle BackColor="Yellow" />
            </asp:GridView>
            <asp:SqlDataSource ID="sqlMSDS" OnSelected="sqlMSDS_OnSelected" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                SelectCommand="SELECT [ID]
                                      ,[ChemicalTitle]
                                      ,[Manufacturer]
                                      ,[UsageDept]
                                      ,[Notes]
                                      ,[Health]
                                      ,[Fire]
                                      ,[Reactivity]
                                      ,[DateUpdated]
                                      FROM [msds_Sheets]" OnSelecting="sqlMSDS_Selecting"></asp:SqlDataSource>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="btnRunAdvSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="rblStatus" EventName="SelectedIndexChanged" />
            <asp:AsyncPostBackTrigger ControlID="btnExport" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>

</asp:Content>

And code-behind:

    List<String> safeWords = new List<String>();

protected void Page_Load(object sender, EventArgs e)
{
    pnlStatus.Visible = User.IsInRole("msds_Admin");

    gridResults.DataKeyNames = new String[] { "id" };

    txtSimpleSearch.Focus();

    if (!IsPostBack)
    {
        safeWords.Add("delete");
        safeWords.Add("insert");
        safeWords.Add("update");
        safeWords.Add("set");
        safeWords.Add("exec");
        safeWords.Add("N'");

        sqlMSDS.SelectCommand += " Where status = 0 ";

        Session["Sql"] = sqlMSDS.SelectCommand;

        try
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand.Remove(sqlMSDS.SelectCommand.IndexOf("Where"));
        }
        catch (Exception)
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand;
        }
    }
}

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ((Label)UpdateProgress1.FindControl("lblProgress")).Text = "Searching...";

            if (btnSearch.Visible)
            {
                btnSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
            else
            {
                btnRunAdvSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    if (sqlMSDS.SelectCommand.Contains("Where"))
                    {
                        sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                    }
                    else
                    {
                        sqlMSDS.SelectCommand += " Where Status = " + RadioButtonList1.SelectedValue;
                    }
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
        }

Body:
Does this RadioButtonList specified as AsyncPostBackTrigger for another UpdatePanel? If so, check following link: CheckedChanged event not firing on a radio button within UpdatePanel

I have reproduce that behaviour and fix this with the following script:

 $(function () {
        $("input[type='radio']:first", $("#<%= RadioButtonList1.ClientID %>")).attr("checked", true);
    });

if you can't use the jQuery try this javascript:

 window.onload = function () {
        window.document.getElementById("<%= RadioButtonList1.ClientID %>_0").checked = true;
    };

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "RadioButtonListDefaultValue", String.Format("window.document.getElementById('{0}_0').checked = true;", RadioButtonList1.ClientID), true);
        }
    }


问:
How to keep vectors in a dictionary in tensorflow?
It seems that tf.lookup.experimental.DenseHashTable cannot hold vectors and I could not find examples of how to use it.

答:
Below you can find a simple implementation of dictionary of vectors in Tensorflow. It is also an example of usage of tf.lookup.experimental.DenseHashTable and tf.TensorArray.

As said, vectors cannot be kept in tf.lookup.experimental.DenseHashTable, and therefore tf.TensorArray is used to keep the actual vectors.

Of course, this is a simple example, and it does not include deletion of entries in the dictionary - an operation that will require some management of the free cells of the array. Also, you should read in the respective API pages of tf.lookup.experimental.DenseHashTable and tf.TensorArray how to tune them for your needs.

import tensorflow as tf

class DictionaryOfVectors:

  def __init__(self, dtype):
    empty_key = tf.constant('')
    deleted_key = tf.constant('deleted')

    self.ht = tf.lookup.experimental.DenseHashTable(key_dtype=tf.string,
                                                    value_dtype=tf.int32,
                                                    default_value=-1,
                                                    empty_key=empty_key,
                                                    deleted_key=deleted_key)
    self.ta = tf.TensorArray(dtype, size=0, dynamic_size=True, clear_after_read=False)
    self.inserts_counter = 0

  @tf.function
  def insertOrAssign(self, key, vec):
    # Insert the vector to the TensorArray. The write() method returns a new
    # TensorArray object with flow that ensures the write occurs. It should be
    # used for subsequent operations.
    with tf.init_scope():
      self.ta = self.ta.write(self.inserts_counter, vec)

      # Insert the same counter value to the hash table
      self.ht.insert_or_assign(key, self.inserts_counter)
      self.inserts_counter += 1

  @tf.function
  def lookup(self, key):
    with tf.init_scope():
      index = self.ht.lookup(key)
      return self.ta.read(index)

dictionary_of_vectors = DictionaryOfVectors(dtype=tf.float32)
dictionary_of_vectors.insertOrAssign('first', [1,2,3,4,5])
print(dictionary_of_vectors.lookup('first'))
```

The example is a bit more sophisticated, as the insert and lookup methods are decorated with  @tf.function. Because the methods change variables defined outside of them, the tf.init_scope() is used. You might ask what is changed in the lookup() method as it actually only reads from the hash table and the array. The reason is that in graph mode, the index that is returned from the lookup() call is a Tensor, and in the TensorArray implementation there is a line containing if index < 0: which fails with:

OperatorNotAllowedInGraphError: using a tf.Tensor as a Python bool is not allowed.

When we use the tf.init_scope(), as explained in its API documentation, "code inside an init_scope block runs with eager execution enabled even when tracing a tf.function". So in that case that index is not a Tensor but as scalar.

Body:
Below you can find a simple implementation of dictionary of vectors in Tensorflow. It is also an example of usage of tf.lookup.experimental.DenseHashTable and tf.TensorArray.

As said, vectors cannot be kept in tf.lookup.experimental.DenseHashTable, and therefore tf.TensorArray is used to keep the actual vectors.

Of course, this is a simple example, and it does not include deletion of entries in the dictionary - an operation that will require some management of the free cells of the array. Also, you should read in the respective API pages of tf.lookup.experimental.DenseHashTable and tf.TensorArray how to tune them for your needs.

import tensorflow as tf

class DictionaryOfVectors:

  def __init__(self, dtype):
    empty_key = tf.constant('')
    deleted_key = tf.constant('deleted')

    self.ht = tf.lookup.experimental.DenseHashTable(key_dtype=tf.string,
                                                    value_dtype=tf.int32,
                                                    default_value=-1,
                                                    empty_key=empty_key,
                                                    deleted_key=deleted_key)
    self.ta = tf.TensorArray(dtype, size=0, dynamic_size=True, clear_after_read=False)
    self.inserts_counter = 0

  @tf.function
  def insertOrAssign(self, key, vec):
    # Insert the vector to the TensorArray. The write() method returns a new
    # TensorArray object with flow that ensures the write occurs. It should be
    # used for subsequent operations.
    with tf.init_scope():
      self.ta = self.ta.write(self.inserts_counter, vec)

      # Insert the same counter value to the hash table
      self.ht.insert_or_assign(key, self.inserts_counter)
      self.inserts_counter += 1

  @tf.function
  def lookup(self, key):
    with tf.init_scope():
      index = self.ht.lookup(key)
      return self.ta.read(index)

dictionary_of_vectors = DictionaryOfVectors(dtype=tf.float32)
dictionary_of_vectors.insertOrAssign('first', [1,2,3,4,5])
print(dictionary_of_vectors.lookup('first'))

The example is a bit more sophisticated, as the insert and lookup methods are decorated with  @tf.function. Because the methods change variables defined outside of them, the tf.init_scope() is used. You might ask what is changed in the lookup() method as it actually only reads from the hash table and the array. The reason is that in graph mode, the index that is returned from the lookup() call is a Tensor, and in the TensorArray implementation there is a line containing if index < 0: which fails with:

OperatorNotAllowedInGraphError: using a tf.Tensor as a Python bool is not allowed.

When we use the tf.init_scope(), as explained in its API documentation, "code inside an init_scope block runs with eager execution enabled even when tracing a tf.function". So in that case that index is not a Tensor but as scalar.