问:
Ruby iterate a function with its own output without mutating original input
The goal:Trying to optimize solution for the alphametics problem on exercism.

My approach: Rather than brute force trying every possible combination for all letters at once, I would like to try letters corresponding to the ones units first.  If a guess satisfies the ones units, use that guess as a starting point for trying the tens units.  And so on for as many places as the problem requires.

Rationale: Reduce the number of iterations overall by not wasting time with subsets of numbers that won't work for a subset of letters.

Here is my code that solves the puzzles but is very slow (puzzles with 8 letters take around 5-6 seconds and 10 letters MUCH longer).

```<code>class Alphametics
  class << self
    def solve(input)
      @input = input
      guess(@input)
    end

    def guess(input)
      letters_to_keys(input)
      left_most_digit_of_sum_max(input, @candidates)
      left_most_digit_is_not_0(first_letters(input), @candidates)
      generate_guess(@candidates)
    end

    def letters_to_keys(input) # create hash of letters and their possible values
      @candidates = {}
      letters(input).each {|ltr| @candidates[ltr] = (0..9).to_a}
      @candidates
    end

    def letters(input) # creates an array of unique letters from summands and sum
      (summands(input) + [sum(input)]).join.chars.uniq
    end

    def summands(input) #takes the input and separates summands from sum, removing the "+" character, returns array of "words" as strings
      input.split(" == ")[0].split(" + ")
    end

    def sum(input) # takes the input and separates sum from summands, returning a string of only letters
      input.split(" == ")[1]
    end

    def left_most_digit_of_sum_max(input, candidates) # the first digit of the sum has its value considerably constrained by the number summands when the sum has more digits than any of the individual summands
      if summands(input).all? {|word| word.length < sum(input).length}
        candidates[sum(input)[0]] = (0..summands(input).length-1).to_a
      end
    end

    def left_most_digit_is_not_0(letters, candidates) # the first digit of any number cannot be zero
      letters.each {|ltr| candidates[ltr] -= [0]}
    end

    def first_letters(input) # create an array of the first letter of each word -- for determining which letters cannot be zero
      a = []
      summands(input).each { |word| a << word[0]}
      a << sum(input)[0]
      a
    end

    def generate_guess(candidates)
      answer = {}
      potential_values = candidates.values
      letters = candidates.keys
      guess_index(potential_values).each do |i|
        dividend = i
        guess = []
        (0..potential_values.length-1).each do |ndx|
          divisor = potential_values[ndx].length
          if guess.include?(potential_values[ndx][dividend % divisor])
            next i
          else
            guess << potential_values[ndx][dividend % divisor]
            dividend = dividend / divisor
          end
        end
        if guess.length == potential_values.length && check_summation(letters, guess)
          answer = solution(guess, letters)
          return answer
        end
      end
      return answer
    end

    def guess_index(potential_values)
      index_length = 1
      potential_values.each { |vals| index_length*=vals.length }
      (0..index_length-1).to_a
    end

    def check_summation(letters, guess) # check that guess satisfies the summation
      nums = int_sub_for_letter(@input, letters, guess)
      summands(nums).collect{|x| x.to_i}.reduce(:+) == sum(nums).to_i
    end

    def int_sub_for_letter(input, letters, guess) # substitute numbers for letters in string
      string = input
      (0..guess.length-1).each do |i|
        string = string.gsub(letters[i], guess[i].to_s)
      end
      return string
    end

    def solution(guess, letters) # generate solution hash without mutating candidates hash
      letters.zip(guess).to_h
    end

  end
end
t1 = Time.now
p Alphametics.solve("SEND + MORE == MONEY")
t2 = Time.now
p t2-t1
</code>```

I am trying to make this more efficient by reducing the number of iterations required.  I have done this by performing the calculation for each place (column if summation written vertically) sequentially.  Thus letters in the ones place that repeat elsewhere will have fewer potential values, leading to fewer permutations of guesses overall and thus fewer checks that the sum works out.

In essence the problem I'm running up against is this:
Given a hash of "places" with strings from the puzzle's terms as values, how do I iterate one set of values over each "place", expanding the set as needed to accommodate new letters in the next "place"?
To illustrate, for the puzzle "SEND + MORE == MONEY" you have

```<code>h = {
      0 => ['D', 'E', 'Y'],
      1 => ['ND', 'RE', 'EY'],
      2 => ['END', 'ORE', 'NEY',
      3 => ['SEND', 'MORE', 'ONEY'],
      4 => ['MONEY']
    }
</code>```

And after constraining the possible values for each letter based on position and number of summands, you get:

```<code>candidate_values = {
      M => [1],
      S => [1,2,3,4,5,6,7,8,9],
      E => [0,1,2,3,4,5,6,7,8,9],
      N => [0,1,2,3,4,5,6,7,8,9],
      D => [0,1,2,3,4,5,6,7,8,9],
      O => [0,1,2,3,4,5,6,7,8,9],
      R => [0,1,2,3,4,5,6,7,8,9],
      Y => [0,1,2,3,4,5,6,7,8,9]
    }
</code>```

I know how to generate all the possible guesses for each place, but what I want to do is generate all the guesses for the ones place, iterate over that set of guesses and check if the guess satisfies the addition for the ones place.  If it does, I want to take that guess, use it to generate a set of possible guesses for the tens place and iterate over those guesses in the same way.  But if NO solution is found for the tens place, it should go back to the iterations of the ones guesses.

FWIW, these are the methods I've been trying to use to set up the iteration:

```<code>def check_guess(guess, candidates, current_segments, current_letters, exp)
  nums_to_chk = current_segments
  current_letters.each do |ltr|
    nums_to_chk = int_sub_for_letter(nums_to_chk, current_letters, ltr, guess)
  end
  nums_to_chk.collect {|i| i.reverse.to_i}[0..-2].reduce(:+).to_s[-(exp+1)..-1] == nums_to_chk[-1].reverse
end
def take_a_guess(guesses, candidates, segments, current_segments, current_letters, exp)
  guesses.each do |guess|
    if check_guess(guess, candidates, current_segments, current_letters, exp)
      partial_solution = current_letters.zip(guess.each_slice(1).to_a).to_h
      exp+=1
      next_segments = segments[exp]
      new_letters = letters_to_chk(next_segments) - current_letters
      new_letters.each{|ltr| partial_solution[ltr] = candidates[ltr]}
      next_letters = partial_solution.keys
      next_values = get_potential_values(partial_solution, next_letters)
      next_guesses = generate_guesses(next_values)
      take_a_guess(next_guesses, partial_solution, segments, next_segments, next_letters, exp)

    end
  end
end
</code>```

答:
This is not really an answer, but an extended comment. I would simply like to offer some suggestions for approaching the problem. (I would use recursion, btw.) I've spent an inordinate amount of time on this but what I have to offer is not very satisfactory, wandering all over the place, and incomplete. I've written quite a few more words and equations, and some incomplete code, but have stripped all of that out.

I have come to hate this problem. It's the type of problem where one can figure out a general approach to solving it in just a few minutes, but there are so many special cases and twists and turns that working up code to solve it is very time consuming and about as fun as having a root canal done.

The problem

The link gives an example of the question being addressed. We are given strings or arrays of capital letters that can be viewed as follows.

```<code>  S E N D
  M O R E +
-----------
M O N E Y
</code>```

The idea is to assign a digit to each letter so that the resulting addition is correct. Here that is:

```<code>{ "S"=>9, "E"=>5, "N"=>6, "D"=>7, "M"=>1, "O"=>0, "R"=>8, "Y"=>2 }
</code>```

which gives us the following.

```<code>  9 5 6 7
  1 0 8 5 +
-----------
1 0 6 5 2
</code>```

Observations

For convenience, I will express this problem as follows.

```<code>arr = [["*", "S", "E", "N", "D"],
       ["*", "M", "O", "R", "E"],
       ["M", "O", "N", "E", "Y"]]
</code>```

We can assume that "M" must equal 1, as one would not write 0 in that position. Our beginning hash of known values is therefore

```<code>known = { "*"=>0, "M"=>1 }
</code>```

It is more convenient to work with the following array.

```<code>arr.transpose.reverse
  #=> [["D", "E", "Y"],
  #    ["N", "R", "E"],
  #    ["E", "O", "N"],
  #    ["S", "M", "O"],
  #    ["*", "*", "M"]]
</code>```

The first row represents the column in the 1's place, the second row, the column in the 10's place, and so on. Our search will progress row-by-row until we have valid assignments for all rows.

The third row (for example) represents two equations:

```<code>v("E") + v("O") + c = v("N")
v("E") + v("O") + c = v("N") + 10
</code>```

where v gives the value of each letter (a digit 0-9) and c is the amount carried from the previous column (0 or 1). The two equations correspond, respectively, to 0 and 1 being carried forward to the column to the left (with the next most significant digits).

The idea is to sequentially assign the digits 0-9 to "D", then for each assign digits 0-9 to "E", then compute the associated value of "Y", v("Y"). If v("Y") < 10, the carryover to the next column is 0; else v("Y") is replace with v("Y") % 10 and the carryover to the next column is 1.

Suppose "D" were assigned 6. Then the hash for the current location in the search tree would be

```<code>known = { "*"=>0, "M"=>1, "D"=>6 }
</code>```

If "E" were assigned 7, the hash would become

```<code>known = { "*"=>0, "M"=>1, "D"=>6, "E"=>7 }
</code>```

The value of "Y" would then computed to be

```<code>v("Y") = 6 + 7 + 0 #> 13
</code>```

(Note the carryover for the 1's column is zero.) Since v("Y") > 9, v("Y") = v("Y") % 10 #=> 3, 1 is carried over to the next column and known becomes

```<code>known = { "*"=>0, "M"=>1, "D"=>6, "E"=>7, "Y"=> 3 }
</code>```

When the 10's column is processed the equations are

```<code>v("N") + v("R") + 1 = v("E")
v("N") + v("R") + 1 = v("E") + 10
</code>```

but as v("E") is currently known, these equations reduce to

```<code>v("N") + v("R") = 2   (carryover 0)
v("N") + v("R") = 12  (carryover 1)
</code>```

We may now assign different digits to v("R") (say), and solve for v("N").

In the 3rd row we need only solve for v("R"). If that is between 1 and 9, we continue to the next line; else we abandon that part of the search tree and go back to the 10's column. The algorithm terminates with a solution when the calculation for the first column (the last row of the above array) is successful; else it is concluded that there is no solution.

Suppose a column has letters x, y and z, and c (0 or 1) has been carried from the previous column and v is a function that maps each of these letters to a digit.

Cases to consider

Here are various cases to be considered.

x == y == z

This requires v(x) = 9 and c #=> 1.

x == y, z != x, v(z) known

The equation here is either

```<code>2*v(x) + c = v(z)
</code>```

or

```<code>2*v(x) + c = v(z) + 10
</code>```

If v(z) is known, we can solve for v(x) like so.

```<code>v(x) = (v(z) - c)/2
</code>```

or

```<code>v(x) = (v(z) - c + 10)/2
</code>```

Suppose v(z) #=> 5 and c #=> 1. The two expressions above evaluate to v(x) #=> 2 and v(x) #=> 7. We would need to explore both of these possibilities. If c #=> 0, v(x) takes on a fractional value in both cases, so we would conclude that at this branch of our search tree v(z) cannot equal 5.

x == y, z != x, v(x) known

Here we would solve

```<code>v(z) = 2*v(z) + c
</code>```

or

```<code>v(z) = 2*v(z) + c - 10
</code>```

Notice that 0 <= v(z) <= 4 and 5 <= v(z) <= 9 for the two expressions respectively, regardless of whether c equals 0 or 1. Therefore, there is but one solution. Suppose v(z) #=> 6. Then the expressions evaluate v(z) #=> 14 + c and v(z) #=>4 + c. Therefore, we need only evaluate the first expression. Ifv(x) < 10we setv(x)to that value and carry0to the next column; otherwise we setv(x)to that number less10and carry1` to the next column.

Suppose capital and lowercase letters represent letters with known and unknown values, respectively.  equals the amount carried from the previous column (or or 1).

Solve for one unknown value

```<code>x + Y +  = Z      #=> x = Z - Y -        if Z > Y  (carry 0)
x + Y +  = Z + 10 #=> x = Z + 10 - Y -   if Z <= Y (carry 1)
</code>```

The calculations for the unknown value occupying the other two possible positions is similar.

Solve for two unknown values

Suppose there are two unknown values represented by two letters.

```<code>x + y +  = Z
</code>```

For x to be a positive digit, y <= Z - , which gives a range of values for y to consider, except when Z = 0 and  = 1, where there is no solution. The other case is

```<code>x + y +  = Z + 10
</code>```

For x to be a positive digit, 0 <= y <= [Z -  + 10, 9].min = 9, meaning that y can be assigned any digit.

Again, the calculations are similar when when the known value occupies one of the two other possible positions.

Solve for three unknown values

If all three values are unknown we may sequentially assign the digit 0-9 to the letter in the first row, reducing the problem to one having two unknown values, which I just discussed.

Special cases

```<code>x + x +  = Z
x + x +  = Z + 10
</code>```

If Z -  is odd or -1 there is no integral solution (for x) to these equations. If that amount is non-negative and even,

```<code>x = (Z - )/2
x = (Z - )/2 + 5
</code>```

0 <= x <= 9 for both of these numbers, so both assignments must be explored in the search tree.

If x + Y +  = x or X + y +  = y there is no integral solution. However,

```<code>x + Y +  = x + 10 #=> Y #=> 10 -
X + y +  = y + 10 #=> X #=> 10 -
</code>```

If the known value (Y or Z) equal 10 - , the unknown value (x or y) can equal any digit.

The final case is where there are three unknowns, all equal. If

```<code>x + x +  = x #=> x = -
</code>```

 must equal 0 in which case x = 1, whereas if

```<code>x + x +  = x + 10 #=> x = 10 - ``
</code>```

 must equal 1 in which case x = 9.

Body:
The goal:Trying to optimize solution for the alphametics problem on exercism.

My approach: Rather than brute force trying every possible combination for all letters at once, I would like to try letters corresponding to the ones units first.  If a guess satisfies the ones units, use that guess as a starting point for trying the tens units.  And so on for as many places as the problem requires.

Rationale: Reduce the number of iterations overall by not wasting time with subsets of numbers that won't work for a subset of letters.

Here is my code that solves the puzzles but is very slow (puzzles with 8 letters take around 5-6 seconds and 10 letters MUCH longer).

class Alphametics
  class << self
    def solve(input)
      @input = input
      guess(@input)
    end

    def guess(input)
      letters_to_keys(input)
      left_most_digit_of_sum_max(input, @candidates)
      left_most_digit_is_not_0(first_letters(input), @candidates)
      generate_guess(@candidates)
    end

    def letters_to_keys(input) # create hash of letters and their possible values
      @candidates = {}
      letters(input).each {|ltr| @candidates[ltr] = (0..9).to_a}
      @candidates
    end

    def letters(input) # creates an array of unique letters from summands and sum
      (summands(input) + [sum(input)]).join.chars.uniq
    end

    def summands(input) #takes the input and separates summands from sum, removing the "+" character, returns array of "words" as strings
      input.split(" == ")[0].split(" + ")
    end

    def sum(input) # takes the input and separates sum from summands, returning a string of only letters
      input.split(" == ")[1]
    end

    def left_most_digit_of_sum_max(input, candidates) # the first digit of the sum has its value considerably constrained by the number summands when the sum has more digits than any of the individual summands
      if summands(input).all? {|word| word.length < sum(input).length}
        candidates[sum(input)[0]] = (0..summands(input).length-1).to_a
      end
    end

    def left_most_digit_is_not_0(letters, candidates) # the first digit of any number cannot be zero
      letters.each {|ltr| candidates[ltr] -= [0]}
    end

    def first_letters(input) # create an array of the first letter of each word -- for determining which letters cannot be zero
      a = []
      summands(input).each { |word| a << word[0]}
      a << sum(input)[0]
      a
    end

    def generate_guess(candidates)
      answer = {}
      potential_values = candidates.values
      letters = candidates.keys
      guess_index(potential_values).each do |i|
        dividend = i
        guess = []
        (0..potential_values.length-1).each do |ndx|
          divisor = potential_values[ndx].length
          if guess.include?(potential_values[ndx][dividend % divisor])
            next i
          else
            guess << potential_values[ndx][dividend % divisor]
            dividend = dividend / divisor
          end
        end
        if guess.length == potential_values.length && check_summation(letters, guess)
          answer = solution(guess, letters)
          return answer
        end
      end
      return answer
    end

    def guess_index(potential_values)
      index_length = 1
      potential_values.each { |vals| index_length*=vals.length }
      (0..index_length-1).to_a
    end

    def check_summation(letters, guess) # check that guess satisfies the summation
      nums = int_sub_for_letter(@input, letters, guess)
      summands(nums).collect{|x| x.to_i}.reduce(:+) == sum(nums).to_i
    end

    def int_sub_for_letter(input, letters, guess) # substitute numbers for letters in string
      string = input
      (0..guess.length-1).each do |i|
        string = string.gsub(letters[i], guess[i].to_s)
      end
      return string
    end

    def solution(guess, letters) # generate solution hash without mutating candidates hash
      letters.zip(guess).to_h
    end

  end
end
t1 = Time.now
p Alphametics.solve("SEND + MORE == MONEY")
t2 = Time.now
p t2-t1

I am trying to make this more efficient by reducing the number of iterations required.  I have done this by performing the calculation for each place (column if summation written vertically) sequentially.  Thus letters in the ones place that repeat elsewhere will have fewer potential values, leading to fewer permutations of guesses overall and thus fewer checks that the sum works out.

In essence the problem I'm running up against is this:
Given a hash of "places" with strings from the puzzle's terms as values, how do I iterate one set of values over each "place", expanding the set as needed to accommodate new letters in the next "place"?
To illustrate, for the puzzle "SEND + MORE == MONEY" you have

h = {
      0 => ['D', 'E', 'Y'],
      1 => ['ND', 'RE', 'EY'],
      2 => ['END', 'ORE', 'NEY',
      3 => ['SEND', 'MORE', 'ONEY'],
      4 => ['MONEY']
    }

And after constraining the possible values for each letter based on position and number of summands, you get:

candidate_values = {
      M => [1],
      S => [1,2,3,4,5,6,7,8,9],
      E => [0,1,2,3,4,5,6,7,8,9],
      N => [0,1,2,3,4,5,6,7,8,9],
      D => [0,1,2,3,4,5,6,7,8,9],
      O => [0,1,2,3,4,5,6,7,8,9],
      R => [0,1,2,3,4,5,6,7,8,9],
      Y => [0,1,2,3,4,5,6,7,8,9]
    }

I know how to generate all the possible guesses for each place, but what I want to do is generate all the guesses for the ones place, iterate over that set of guesses and check if the guess satisfies the addition for the ones place.  If it does, I want to take that guess, use it to generate a set of possible guesses for the tens place and iterate over those guesses in the same way.  But if NO solution is found for the tens place, it should go back to the iterations of the ones guesses.

FWIW, these are the methods I've been trying to use to set up the iteration:

def check_guess(guess, candidates, current_segments, current_letters, exp)
  nums_to_chk = current_segments
  current_letters.each do |ltr|
    nums_to_chk = int_sub_for_letter(nums_to_chk, current_letters, ltr, guess)
  end
  nums_to_chk.collect {|i| i.reverse.to_i}[0..-2].reduce(:+).to_s[-(exp+1)..-1] == nums_to_chk[-1].reverse
end
def take_a_guess(guesses, candidates, segments, current_segments, current_letters, exp)
  guesses.each do |guess|
    if check_guess(guess, candidates, current_segments, current_letters, exp)
      partial_solution = current_letters.zip(guess.each_slice(1).to_a).to_h
      exp+=1
      next_segments = segments[exp]
      new_letters = letters_to_chk(next_segments) - current_letters
      new_letters.each{|ltr| partial_solution[ltr] = candidates[ltr]}
      next_letters = partial_solution.keys
      next_values = get_potential_values(partial_solution, next_letters)
      next_guesses = generate_guesses(next_values)
      take_a_guess(next_guesses, partial_solution, segments, next_segments, next_letters, exp)

    end
  end
end

Body:
This is not really an answer, but an extended comment. I would simply like to offer some suggestions for approaching the problem. (I would use recursion, btw.) I've spent an inordinate amount of time on this but what I have to offer is not very satisfactory, wandering all over the place, and incomplete. I've written quite a few more words and equations, and some incomplete code, but have stripped all of that out.

I have come to hate this problem. It's the type of problem where one can figure out a general approach to solving it in just a few minutes, but there are so many special cases and twists and turns that working up code to solve it is very time consuming and about as fun as having a root canal done.

The problem

The link gives an example of the question being addressed. We are given strings or arrays of capital letters that can be viewed as follows.

  S E N D
  M O R E +
-----------
M O N E Y

The idea is to assign a digit to each letter so that the resulting addition is correct. Here that is:

{ "S"=>9, "E"=>5, "N"=>6, "D"=>7, "M"=>1, "O"=>0, "R"=>8, "Y"=>2 }

which gives us the following.

  9 5 6 7
  1 0 8 5 +
-----------
1 0 6 5 2

Observations

For convenience, I will express this problem as follows.

arr = [["*", "S", "E", "N", "D"],
       ["*", "M", "O", "R", "E"],
       ["M", "O", "N", "E", "Y"]]

We can assume that "M" must equal 1, as one would not write 0 in that position. Our beginning hash of known values is therefore

known = { "*"=>0, "M"=>1 }

It is more convenient to work with the following array.

arr.transpose.reverse
  #=> [["D", "E", "Y"],
  #    ["N", "R", "E"],
  #    ["E", "O", "N"],
  #    ["S", "M", "O"],
  #    ["*", "*", "M"]]

The first row represents the column in the 1's place, the second row, the column in the 10's place, and so on. Our search will progress row-by-row until we have valid assignments for all rows.

The third row (for example) represents two equations:

v("E") + v("O") + c = v("N")
v("E") + v("O") + c = v("N") + 10

where v gives the value of each letter (a digit 0-9) and c is the amount carried from the previous column (0 or 1). The two equations correspond, respectively, to 0 and 1 being carried forward to the column to the left (with the next most significant digits).

The idea is to sequentially assign the digits 0-9 to "D", then for each assign digits 0-9 to "E", then compute the associated value of "Y", v("Y"). If v("Y") < 10, the carryover to the next column is 0; else v("Y") is replace with v("Y") % 10 and the carryover to the next column is 1.

Suppose "D" were assigned 6. Then the hash for the current location in the search tree would be

known = { "*"=>0, "M"=>1, "D"=>6 }

If "E" were assigned 7, the hash would become

known = { "*"=>0, "M"=>1, "D"=>6, "E"=>7 }

The value of "Y" would then computed to be

v("Y") = 6 + 7 + 0 #> 13

(Note the carryover for the 1's column is zero.) Since v("Y") > 9, v("Y") = v("Y") % 10 #=> 3, 1 is carried over to the next column and known becomes

known = { "*"=>0, "M"=>1, "D"=>6, "E"=>7, "Y"=> 3 }

When the 10's column is processed the equations are

v("N") + v("R") + 1 = v("E")
v("N") + v("R") + 1 = v("E") + 10

but as v("E") is currently known, these equations reduce to

v("N") + v("R") = 2   (carryover 0)
v("N") + v("R") = 12  (carryover 1)

We may now assign different digits to v("R") (say), and solve for v("N").

In the 3rd row we need only solve for v("R"). If that is between 1 and 9, we continue to the next line; else we abandon that part of the search tree and go back to the 10's column. The algorithm terminates with a solution when the calculation for the first column (the last row of the above array) is successful; else it is concluded that there is no solution.

Suppose a column has letters x, y and z, and c (0 or 1) has been carried from the previous column and v is a function that maps each of these letters to a digit.

Cases to consider

Here are various cases to be considered.

x == y == z

This requires v(x) = 9 and c #=> 1.

x == y, z != x, v(z) known

The equation here is either

2*v(x) + c = v(z)

or

2*v(x) + c = v(z) + 10

If v(z) is known, we can solve for v(x) like so.

v(x) = (v(z) - c)/2

or

v(x) = (v(z) - c + 10)/2

Suppose v(z) #=> 5 and c #=> 1. The two expressions above evaluate to v(x) #=> 2 and v(x) #=> 7. We would need to explore both of these possibilities. If c #=> 0, v(x) takes on a fractional value in both cases, so we would conclude that at this branch of our search tree v(z) cannot equal 5.

x == y, z != x, v(x) known

Here we would solve

v(z) = 2*v(z) + c

or

v(z) = 2*v(z) + c - 10

Notice that 0 <= v(z) <= 4 and 5 <= v(z) <= 9 for the two expressions respectively, regardless of whether c equals 0 or 1. Therefore, there is but one solution. Suppose v(z) #=> 6. Then the expressions evaluate v(z) #=> 14 + c and v(z) #=>4 + c. Therefore, we need only evaluate the first expression. Ifv(x) < 10we setv(x)to that value and carry0to the next column; otherwise we setv(x)to that number less10and carry1` to the next column.

Suppose capital and lowercase letters represent letters with known and unknown values, respectively.  equals the amount carried from the previous column (or or 1).

Solve for one unknown value

x + Y +  = Z      #=> x = Z - Y -        if Z > Y  (carry 0)
x + Y +  = Z + 10 #=> x = Z + 10 - Y -   if Z <= Y (carry 1)

The calculations for the unknown value occupying the other two possible positions is similar.

Solve for two unknown values

Suppose there are two unknown values represented by two letters.

x + y +  = Z

For x to be a positive digit, y <= Z - , which gives a range of values for y to consider, except when Z = 0 and  = 1, where there is no solution. The other case is

x + y +  = Z + 10

For x to be a positive digit, 0 <= y <= [Z -  + 10, 9].min = 9, meaning that y can be assigned any digit.

Again, the calculations are similar when when the known value occupies one of the two other possible positions.

Solve for three unknown values

If all three values are unknown we may sequentially assign the digit 0-9 to the letter in the first row, reducing the problem to one having two unknown values, which I just discussed.

Special cases

x + x +  = Z
x + x +  = Z + 10

If Z -  is odd or -1 there is no integral solution (for x) to these equations. If that amount is non-negative and even,

x = (Z - )/2
x = (Z - )/2 + 5

0 <= x <= 9 for both of these numbers, so both assignments must be explored in the search tree.

If x + Y +  = x or X + y +  = y there is no integral solution. However,

x + Y +  = x + 10 #=> Y #=> 10 -
X + y +  = y + 10 #=> X #=> 10 -

If the known value (Y or Z) equal 10 - , the unknown value (x or y) can equal any digit.

The final case is where there are three unknowns, all equal. If

x + x +  = x #=> x = -

 must equal 0 in which case x = 1, whereas if

x + x +  = x + 10 #=> x = 10 - ``

 must equal 1 in which case x = 9.


来源: stackexchange

问:
Login across two meteor applications with the same database
I have two Meteor applications that share the same database, so they have the same accounts. I want to make it so that when a user login on App1, he will be automatically logged in when he visit App2 as well.

Is this possible? How would you recommend me to do this? Thank you so much!

P.S. The Meteor official guide offers something like this at the "Shared Accounts" of the "Data Structure" section, but when I try it, it does not really work. Is it supposed to work?

答:
P.S. The Meteor official guide offers something like this at the "Shared Accounts" of the "Data Structure" section, but when I try it, it does not really work. Is it supposed to work?

This is the way to go, of course it works! There is a proof of concept of this architecture in this example repository.

You won't be logged in automatically to the second app. You have to programmatically log in to the 2nd app when you log in in the first app.

The code in the guide is the way to go:

```<code>// This is server A's token as the default `Accounts` points at our server
const token = Accounts._storedLoginToken();

// We create a *second* accounts client pointing at server B
const app2 = DDP.connect('url://of.server.b');
const accounts2 = new AccountsClient({ connection: app2 });

// Now we can login with the token. Further calls to `accounts2` will be authenticated
accounts2.loginWithToken(token);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
P.S. The Meteor official guide offers something like this at the "Shared Accounts" of the "Data Structure" section, but when I try it, it does not really work. Is it supposed to work?

This is the way to go, of course it works! There is a proof of concept of this architecture in this example repository.

You won't be logged in automatically to the second app. You have to programmatically log in to the 2nd app when you log in in the first app.

The code in the guide is the way to go:

// This is server A's token as the default `Accounts` points at our server
const token = Accounts._storedLoginToken();

// We create a *second* accounts client pointing at server B
const app2 = DDP.connect('url://of.server.b');
const accounts2 = new AccountsClient({ connection: app2 });

// Now we can login with the token. Further calls to `accounts2` will be authenticated
accounts2.loginWithToken(token);


问:
How to make a view controller as splash screen in swift 3?
I am trying to make a view controller from storyboard as the splash screen in my application using swift 3. I am trying achieve the same effect as the splash screen does while loading the splash using "launch image". Since i have got an animation in the splash screen i wish to use a view controller as the splash screen in Swift 3. How to achieve this?</p>

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.window = UIWindow(frame: UIScreen.main.bounds)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let initialViewController = storyboard.instantiateViewController(withIdentifier: "splashScreen")

    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()
    return true
}
</code>```

答:
Try making A View Controller as rootViewController having a splash screen and after 2-3 seconds of showing that View Controller. Push / Present your initial View Controller.

You can set splash ViewController this way :-

```<code>self.window?.rootViewController = splashVC
</code>```

In ViewDidLoad() of splashVC use timer or delay and after 2-3 seconds. Show your application's main View Controller.

```<code>//MARK:- Life Cycle Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.splashTimeOut(sender:)), userInfo: nil, repeats: false)
        // Do any additional setup after loading the view.
    }

func splashTimeOut(sender : Timer){
    AppDelegate.sharedInstance().window?.rootViewController = yourCustomViewController
    }
</code>```

Add this method in Appdelegate for your convenience :-

```<code>class func sharedInstance() -> AppDelegate{
        return UIApplication.shared.delegate as! AppDelegate
    }
</code>```

Body:
I am trying to make a view controller from storyboard as the splash screen in my application using swift 3. I am trying achieve the same effect as the splash screen does while loading the splash using "launch image". Since i have got an animation in the splash screen i wish to use a view controller as the splash screen in Swift 3. How to achieve this?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.window = UIWindow(frame: UIScreen.main.bounds)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let initialViewController = storyboard.instantiateViewController(withIdentifier: "splashScreen")

    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()
    return true
}

Body:
Try making A View Controller as rootViewController having a splash screen and after 2-3 seconds of showing that View Controller. Push / Present your initial View Controller.

You can set splash ViewController this way :-

self.window?.rootViewController = splashVC

In ViewDidLoad() of splashVC use timer or delay and after 2-3 seconds. Show your application's main View Controller.

//MARK:- Life Cycle Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.splashTimeOut(sender:)), userInfo: nil, repeats: false)
        // Do any additional setup after loading the view.
    }

func splashTimeOut(sender : Timer){
    AppDelegate.sharedInstance().window?.rootViewController = yourCustomViewController
    }

Add this method in Appdelegate for your convenience :-

class func sharedInstance() -> AppDelegate{
        return UIApplication.shared.delegate as! AppDelegate
    }


问:
SQL 2005 - quick way to quickly duplicate a database + data
I have my development database, I want to spin off a duplicate for testing.  I want to do this often.

What's the fastest and easiest way to do this often?  I can get the job done by generating scripts w/ data included but I feel like there must be a better way.  Should I back up database 1 then screw around with it so I can restore it as a different name?

答:
If you want to script it you can use the following.  This is also best if you can't take the db offline:

```<code>USE master
GO

-- the original database (use 'SET @DB = NULL' to disable backup)
DECLARE @DB varchar(200)
SET @DB = 'PcTopp'

    -- the backup filename
DECLARE @BackupFile varchar(2000)
SET @BackupFile = 'c:\pctopp\sqlserver\backup.dat'

-- the new database name
DECLARE @TestDB varchar(200)
SET @TestDB = 'TestDB'

-- the new database files without .mdf/.ldf
DECLARE @RestoreFile varchar(2000)
SET @RestoreFile = 'c:\pctopp\sqlserver\backup'

-- ****************************************************************
--                    no change below this line
-- ****************************************************************

DECLARE @query varchar(2000)

DECLARE @DataFile varchar(2000)
SET @DataFile = @RestoreFile + '.mdf'

DECLARE @LogFile varchar(2000)
SET @LogFile = @RestoreFile + '.ldf'

IF @DB IS NOT NULL
BEGIN
    SET @query = 'BACKUP DATABASE ' + @DB + ' TO DISK = ' + QUOTENAME(@BackupFile, '''')
    EXEC (@query)
END

-- RESTORE FILELISTONLY FROM DISK = 'C:\temp\backup.dat'
-- RESTORE HEADERONLY FROM DISK = 'C:\temp\backup.dat'
-- RESTORE LABELONLY FROM DISK = 'C:\temp\backup.dat'
-- RESTORE VERIFYONLY FROM DISK = 'C:\temp\backup.dat'

IF EXISTS(SELECT * FROM sysdatabases WHERE name = @TestDB)
BEGIN
    SET @query = 'DROP DATABASE ' + @TestDB
    EXEC (@query)
END

RESTORE HEADERONLY FROM DISK = @BackupFile
DECLARE @File int
SET @File = @@ROWCOUNT

DECLARE @Data varchar(500)
DECLARE @Log varchar(500)

SET @query = 'RESTORE FILELISTONLY FROM DISK = ' + QUOTENAME(@BackupFile , '''')

CREATE TABLE #restoretemp
(
 LogicalName varchar(500),
 PhysicalName varchar(500),
 type varchar(10),
 FilegroupName varchar(200),
 size int,
 maxsize bigint
)
INSERT #restoretemp EXEC (@query)

SELECT @Data = LogicalName FROM #restoretemp WHERE type = 'D'
SELECT @Log = LogicalName FROM #restoretemp WHERE type = 'L'

PRINT @Data
PRINT @Log

TRUNCATE TABLE #restoretemp
DROP TABLE #restoretemp

IF @File > 0
BEGIN
    SET @query = 'RESTORE DATABASE ' + @TestDB + ' FROM DISK = ' + QUOTENAME(@BackupFile, '''') +
        ' WITH MOVE ' + QUOTENAME(@Data, '''') + ' TO ' + QUOTENAME(@DataFile, '''') + ', MOVE ' +
        QUOTENAME(@Log, '''') + ' TO ' + QUOTENAME(@LogFile, '''') + ', FILE = ' + CONVERT(varchar, @File)
    EXEC (@query)
END
GO
</code>```

Copied from: http://weblogs.asp.net/mschwarz/archive/2004/08/26/220735.aspx

OwnerDisplayName: BPAndrew

ContentLicense: CC BY-SA 2.5

Body:
If you want to script it you can use the following.  This is also best if you can't take the db offline:

USE master
GO

-- the original database (use 'SET @DB = NULL' to disable backup)
DECLARE @DB varchar(200)
SET @DB = 'PcTopp'

    -- the backup filename
DECLARE @BackupFile varchar(2000)
SET @BackupFile = 'c:\pctopp\sqlserver\backup.dat'

-- the new database name
DECLARE @TestDB varchar(200)
SET @TestDB = 'TestDB'

-- the new database files without .mdf/.ldf
DECLARE @RestoreFile varchar(2000)
SET @RestoreFile = 'c:\pctopp\sqlserver\backup'

-- ****************************************************************
--                    no change below this line
-- ****************************************************************

DECLARE @query varchar(2000)

DECLARE @DataFile varchar(2000)
SET @DataFile = @RestoreFile + '.mdf'

DECLARE @LogFile varchar(2000)
SET @LogFile = @RestoreFile + '.ldf'

IF @DB IS NOT NULL
BEGIN
    SET @query = 'BACKUP DATABASE ' + @DB + ' TO DISK = ' + QUOTENAME(@BackupFile, '''')
    EXEC (@query)
END

-- RESTORE FILELISTONLY FROM DISK = 'C:\temp\backup.dat'
-- RESTORE HEADERONLY FROM DISK = 'C:\temp\backup.dat'
-- RESTORE LABELONLY FROM DISK = 'C:\temp\backup.dat'
-- RESTORE VERIFYONLY FROM DISK = 'C:\temp\backup.dat'

IF EXISTS(SELECT * FROM sysdatabases WHERE name = @TestDB)
BEGIN
    SET @query = 'DROP DATABASE ' + @TestDB
    EXEC (@query)
END

RESTORE HEADERONLY FROM DISK = @BackupFile
DECLARE @File int
SET @File = @@ROWCOUNT

DECLARE @Data varchar(500)
DECLARE @Log varchar(500)

SET @query = 'RESTORE FILELISTONLY FROM DISK = ' + QUOTENAME(@BackupFile , '''')

CREATE TABLE #restoretemp
(
 LogicalName varchar(500),
 PhysicalName varchar(500),
 type varchar(10),
 FilegroupName varchar(200),
 size int,
 maxsize bigint
)
INSERT #restoretemp EXEC (@query)

SELECT @Data = LogicalName FROM #restoretemp WHERE type = 'D'
SELECT @Log = LogicalName FROM #restoretemp WHERE type = 'L'

PRINT @Data
PRINT @Log

TRUNCATE TABLE #restoretemp
DROP TABLE #restoretemp

IF @File > 0
BEGIN
    SET @query = 'RESTORE DATABASE ' + @TestDB + ' FROM DISK = ' + QUOTENAME(@BackupFile, '''') +
        ' WITH MOVE ' + QUOTENAME(@Data, '''') + ' TO ' + QUOTENAME(@DataFile, '''') + ', MOVE ' +
        QUOTENAME(@Log, '''') + ' TO ' + QUOTENAME(@LogFile, '''') + ', FILE = ' + CONVERT(varchar, @File)
    EXEC (@query)
END
GO

Copied from: http://weblogs.asp.net/mschwarz/archive/2004/08/26/220735.aspx

OwnerDisplayName: brendan


问:
Google App Engine: Java version of the python deferred library?
Does anyone know of a java version of the python deferred library? Or maybe an idea on how to implement one?

EDIT: App engine has http://code.google.com/appengine/articles/deferred.html, but that library is only for python.  I'm looking for something similar, but that works with GAE/Java

答: There has been work on a Java version of deferred, but nothing released. Searching the archives of the google-appengine-java group may reveal some user code that implements this. Bear in mind that it's not as neat as Python - you have to declare a serializable class that implements a particular interface, while in Python nearly any function or method will do fine.</p>


问:
Understanding class variables in Java
The following is a simple Linked List from a popular YouTube video.

public class Link {

   public String bookName;
   public int millionsSold;

   public Link next;

   public Link(String bookName, int millionsSold) {
      this.bookName = bookName;
      this.millionsSold = millionsSold;
   }

   @Override
   public String toString() {
       return bookName;
   }

   public static void main(String[] args) {

      LinkList theLinkedList = new LinkList();

      theLinkedList.insertFirstLink("Don Quixote", 500);
      theLinkedList.insertFirstLink("A Tale of Two Cities", 200);
      theLinkedList.insertFirstLink("The Lord of the Rings", 150);
      theLinkedList.insertFirstLink("Harry Potter and the Sorcerer's Stone", 107);

      theLinkedList.removeLink("A Tale of Two Cities");
      System.out.println("\nA Tale of Two Cities Removed\n");
   }
}

class LinkList {
   public Link firstLink;

   LinkList() {
      firstLink = null;
   }

   public void insertFirstLink(String bookName, int millionsSold) {
      Link newLink = new Link(bookName, millionsSold);
      newLink.next = firstLink;
      firstLink = newLink;
   }

   public Link removeLink(String bookName) {

      Link currentLink = firstLink;
      Link previousLink = firstLink;

      while (currentLink.bookName != bookName) {
         if (currentLink.next == null)
            return null;
         else {
            previousLink = currentLink;
            currentLink = currentLink.next;
         }
       }

      if (currentLink == firstLink)
        firstLink = firstLink.next;
      else {
        previousLink.next = currentLink.next;
      }
      return currentLink;
   }
}
```

I am having trouble in understanding the removeLink method of LinkedList class. After executing the statement previousLink.next = currentLink.next in that method, why are the changes also reflected in firstLink variable?

EDIT:

As pointed out in comments and answer, I understand that object variable are reference variables and that more than one variable can refer to the same Object. Consequently changes in values to any one of the referencing variable would affect other variables to the same reference too.

In the above example, after executingpreviousLink.next = currentLink.next line, currentLink is also removed from firstLink, as both previousLink and firstLink point to same Object. Similarly, when currentLink = currentLink.next is executed why doesn't it have any effect on firstLink?

答:
After executing the statement previousLink.next = currentLink.next in
  that method, why are the changes also reflected in firstLink variable?

This has already been answered well, but for completeness: because setting a value on the object locally pointed to by previousLink changes the state of that object on the heap, and any other local variables pointing to it will see those changes.
To put it in real-world terms: Suppose you know Mr. Jones as Bob and I know him as Robert. If you object to something Bob says and punch him in the face, I will see that Robert has a black eye.

when currentLink = currentLink.next is executed why doesn't it have
  any effect on firstLink?

Because here we're simply assigning a value to a local variable. We have set currentLink to point to the next node along the chain - this is a purely local change. It's only when we take some action affecting the state of currentLink that reference comes into play (at that point, we are changing the state of an object on the heap)

ContentLicense: CC BY-SA 4.0

Title: Understanding class variables in Java

Body:
The following is a simple Linked List from a popular YouTube video.

public class Link {

   public String bookName;
   public int millionsSold;

   public Link next;

   public Link(String bookName, int millionsSold) {
      this.bookName = bookName;
      this.millionsSold = millionsSold;
   }

   @Override
   public String toString() {
       return bookName;
   }

   public static void main(String[] args) {

      LinkList theLinkedList = new LinkList();

      theLinkedList.insertFirstLink("Don Quixote", 500);
      theLinkedList.insertFirstLink("A Tale of Two Cities", 200);
      theLinkedList.insertFirstLink("The Lord of the Rings", 150);
      theLinkedList.insertFirstLink("Harry Potter and the Sorcerer's Stone", 107);

      theLinkedList.removeLink("A Tale of Two Cities");
      System.out.println("\nA Tale of Two Cities Removed\n");
   }
}

class LinkList {
   public Link firstLink;

   LinkList() {
      firstLink = null;
   }

   public void insertFirstLink(String bookName, int millionsSold) {
      Link newLink = new Link(bookName, millionsSold);
      newLink.next = firstLink;
      firstLink = newLink;
   }

   public Link removeLink(String bookName) {

      Link currentLink = firstLink;
      Link previousLink = firstLink;

      while (currentLink.bookName != bookName) {
         if (currentLink.next == null)
            return null;
         else {
            previousLink = currentLink;
            currentLink = currentLink.next;
         }
       }

      if (currentLink == firstLink)
        firstLink = firstLink.next;
      else {
        previousLink.next = currentLink.next;
      }
      return currentLink;
   }
}

I am having trouble in understanding the removeLink method of LinkedList class. After executing the statement previousLink.next = currentLink.next in that method, why are the changes also reflected in firstLink variable?

EDIT:

As pointed out in comments and answer, I understand that object variable are reference variables and that more than one variable can refer to the same Object. Consequently changes in values to any one of the referencing variable would affect other variables to the same reference too.

In the above example, after executingpreviousLink.next = currentLink.next line, currentLink is also removed from firstLink, as both previousLink and firstLink point to same Object. Similarly, when currentLink = currentLink.next is executed why doesn't it have any effect on firstLink?


问:
SQLSTATE[42S02]: Base table or view not found Symfony 3
I encounter a problem on my application, I have the following error:

```<code>SQLSTATE[42S02]: Base table or view not found: 1146 Table 'ws.T_GP' doesn't exist
</code>```

With the local server the application works perfectly, but as soon as I use the online server, the error appears.

The local server is however identical to the online server.
Databases are also the same.

The table exists in the database, but the error remains.

Do you have any suggestions?

Thank you

答:
It's likely a case issue. Are you sure that the table is called T_GP and not t_gp?
I had the same problem one day and it was just because of the characters.

You should configure doctrine to use lower case table name. Refer to the doctrine documentation http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#persistent-classes to know how to do so.

I hope it will help you :)

Body:
I encounter a problem on my application, I have the following error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'ws.T_GP' doesn't exist

With the local server the application works perfectly, but as soon as I use the online server, the error appears.

The local server is however identical to the online server.
Databases are also the same.

The table exists in the database, but the error remains.

Do you have any suggestions?

Thank you


问:
Account base: options.password must be a string
I looked into some similar problems and added .value. But always get error:  options.password must be a string, even I cast the password.value.toString().

```<code>import React, {Component} from 'react';
import ReactDom from 'react-dom';
import { Accounts } from 'meteor/accounts-base';

class Register extends Component {

  constructor(props) {
     super(props);
     this.handleSubmit = this.handleSubmit.bind(this);
   }

  handleSubmit (event){
    event.preventDefault();
    console.log(this.email.value);
    console.log(this.password.value);
    const res = Accounts.createUser(this.email.value, this.password.value.toString());
    console.log(res);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div className="form-group">
          <label htmlFor="email">Email:</label>
          <input className="form-control" type="email" ref={(email) => this.email = email}/>
        </div>
        <div className="form-group">
          <label htmlFor="password">Password:</label>
          <input className="form-control" type="password" ref={(password) => this.password = password}/>
        </div>
        <div className="form-group">
          <button type="submit" className="btn btn-primary">Submit</button>
        </div>
      </form>
    );
  }
}

export default Register;
</code>```

答:
You need to pass an object, not 2 string arguments:

```<code>const res = Accounts.createUser({
  email: this.email.value,
  password: this.password.value,
});
</code>```

EDIT:
About your React component, using states and controlled components is a better practice than refs:

```<code>import React, {Component} from 'react';
import ReactDom from 'react-dom';
import { Accounts } from 'meteor/accounts-base';

class Register extends Component {

  constructor(props) {
     super(props);
     this.state = {
       email: '',
       password: '',
     }

     this.handleSubmit = this.handleSubmit.bind(this);
   }

   handleInputChange(event) {
      const target = event.target;
      const name = target.name;

      this.setState({
        [name]: value,
      });
    }

  handleSubmit (event){
    event.preventDefault();
    const res = Accounts.createUser({
      email: this.state.email,
      password: this.state.password,
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div className="form-group">
          <label htmlFor="email">Email:</label>
          <input className="form-control" type="email" name="email" onChange={this.handleInputChange} />
        </div>
        <div className="form-group">
          <label htmlFor="password">Password:</label>
          <input className="form-control" type="password" name="password" onChange={this.handleInputChange} />
        </div>
        <div className="form-group">
          <button type="submit" className="btn btn-primary">Submit</button>
        </div>
      </form>
    );
  }
}
</code>```

Body:
I looked into some similar problems and added .value. But always get error:  options.password must be a string, even I cast the password.value.toString().

import React, {Component} from 'react';
import ReactDom from 'react-dom';
import { Accounts } from 'meteor/accounts-base';

class Register extends Component {

  constructor(props) {
     super(props);
     this.handleSubmit = this.handleSubmit.bind(this);
   }

  handleSubmit (event){
    event.preventDefault();
    console.log(this.email.value);
    console.log(this.password.value);
    const res = Accounts.createUser(this.email.value, this.password.value.toString());
    console.log(res);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>

          Email:
          <input className="form-control" type="email" ref={(email) => this.email = email}/>

          Password:
          <input className="form-control" type="password" ref={(password) => this.password = password}/>

          <button type="submit" className="btn btn-primary">Submit</button>

      </form>
    );
  }
}

export default Register;

Body:
You need to pass an object, not 2 string arguments:

const res = Accounts.createUser({
  email: this.email.value,
  password: this.password.value,
});

EDIT:
About your React component, using states and controlled components is a better practice than refs:

import React, {Component} from 'react';
import ReactDom from 'react-dom';
import { Accounts } from 'meteor/accounts-base';

class Register extends Component {

  constructor(props) {
     super(props);
     this.state = {
       email: '',
       password: '',
     }

     this.handleSubmit = this.handleSubmit.bind(this);
   }

   handleInputChange(event) {
      const target = event.target;
      const name = target.name;

      this.setState({
        [name]: value,
      });
    }

  handleSubmit (event){
    event.preventDefault();
    const res = Accounts.createUser({
      email: this.state.email,
      password: this.state.password,
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div className="form-group">
          <label htmlFor="email">Email:</label>
          <input className="form-control" type="email" name="email" onChange={this.handleInputChange} />
        </div>
        <div className="form-group">
          <label htmlFor="password">Password:</label>
          <input className="form-control" type="password" name="password" onChange={this.handleInputChange} />
        </div>
        <div className="form-group">
          <button type="submit" className="btn btn-primary">Submit</button>
        </div>
      </form>
    );
  }
}


问:
C++ - stat(), access() not working under gnu gcc
I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:

```<code>#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  char path[] = "myfolder/";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}
</code>```

I have also tried the access version:

```<code>#include <iostream>
#include <io.h>

using namespace std;

int main() {
  char path[] = "myfolder/";

  if(access(path,0)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}
</code>```

Neither of them find my folder (which is right there in the same directory as the program).  These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps.  I'm sure it's a quick fix - can someone help out?

(Obviously I'm a noob at this so if you need any other information I've left out please let me know).

UPDATE

The problem was with the base directory.  The updated, working program is as follows:

```<code>#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  cout << "Current directory: " << system("cd") << endl;

  char path[] = "./bin/Release/myfolder";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Directory found." << endl; }
  else { cout << "Can't find directory." << endl; } //Doesn't exist

  cin.get();
  return 0;
}
</code>```

ANOTHER UPDATE

Turns out that a trailing backslash on the path is big trouble.

答: Are you sure that the current directory of your running program is what you expect it to be? Try changing path to an absolute pathname to see if that helps.

Body:
I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  char path[] = "myfolder/";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

I have also tried the access version:

#include <iostream>
#include <io.h>

using namespace std;

int main() {
  char path[] = "myfolder/";

  if(access(path,0)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

Neither of them find my folder (which is right there in the same directory as the program).  These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps.  I'm sure it's a quick fix - can someone help out?

(Obviously I'm a noob at this so if you need any other information I've left out please let me know).

UPDATE

The problem was with the base directory.  The updated, working program is as follows:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  cout << "Current directory: " << system("cd") << endl;

  char path[] = "./bin/Release/myfolder";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Directory found." << endl; }
  else { cout << "Can't find directory." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

ANOTHER UPDATE

Turns out that a trailing backslash on the path is big trouble.


问:
makefile select prerequisites depending on source
Suppose I have the following files:

```<code>.:           include/  01.src  02.src  03.src  Makefile

./include:   01.inc  02-source1.inc  02-source2.inc
</code>```

for which I have the following Makefile (source: Complex pattern rule in Makefile):

```<code>exe = ${patsubst %.src, %.exe, ${wildcard *.src}}

all : ${exe}

.SECONDEXPANSION:
${exe} : %.exe : %.src $${wildcard include/%*.inc}
    @echo compile $@ using $^
</code>```

This says that 01.exe will be compiled using 01.src and include/01*.inc (something similar for 02.exe and 03.exe). In fact, make outputs:

```<code>compile 01.exe using 01.src include/01.inc
compile 02.exe using 02.src include/02-source1.inc include/02-source2.inc
compile 03.exe using 03.src
</code>```

My question is: How should I modify this Makefile if 01.src, 02.src, and 03.src are renamed to 01-first.src, 02-second.src, and 03-third.src? The desired output is:

```<code>compile 01-first.exe using 01-first.src include/01.inc
compile 02-second.exe using 02-second.src include/02-source1.inc include/02-source2.inc
compile 03-third.exe using 03-third.src
</code>```

答:
try this:

```<code>${exe} : %.exe : %.src $${wildcard include/$$(shell echo % | head -c 2)*.inc}
    @echo compile $@ using $^
</code>```

output:

```<code>compile 03-third.exe using 03-third.src
compile 02-second.exe using 02-second.src include/02-source1.inc include/02-source2.inc
compile 01-first.exe using 01-first.src include/01.inc
</code>```

Body:
Suppose I have the following files:

.:           include/  01.src  02.src  03.src  Makefile

./include:   01.inc  02-source1.inc  02-source2.inc

for which I have the following Makefile (source: Complex pattern rule in Makefile):

exe = ${patsubst %.src, %.exe, ${wildcard *.src}}

all : ${exe}

.SECONDEXPANSION:
${exe} : %.exe : %.src $${wildcard include/%*.inc}
    @echo compile $@ using $^

This says that 01.exe will be compiled using 01.src and include/01*.inc (something similar for 02.exe and 03.exe). In fact, make outputs:

compile 01.exe using 01.src include/01.inc
compile 02.exe using 02.src include/02-source1.inc include/02-source2.inc
compile 03.exe using 03.src

My question is: How should I modify this Makefile if 01.src, 02.src, and 03.src are renamed to 01-first.src, 02-second.src, and 03-third.src? The desired output is:

compile 01-first.exe using 01-first.src include/01.inc
compile 02-second.exe using 02-second.src include/02-source1.inc include/02-source2.inc
compile 03-third.exe using 03-third.src

Body:
try this:

${exe} : %.exe : %.src $${wildcard include/$$(shell echo % | head -c 2)*.inc}
    @echo compile $@ using $^

output:

compile 03-third.exe using 03-third.src
compile 02-second.exe using 02-second.src include/02-source1.inc include/02-source2.inc
compile 01-first.exe using 01-first.src include/01.inc


问:
Anime.js backgroundColor giving unexpected results
So I've been playing around with Anime.js. I'm using this short bit of code to try and animate a div tag with a single letter id of a.

```<code>anime({
    targets: "#a",
    translateX: 250,
    color: "#fff",
    backgroundColor: "hsl(200, 50%, 50%)",
    loop: true,
    direction: 'alternate',
    easing: 'easeInOutQuad'
});
</code>```

The problem is that (at least for me in Google Chrome) the element seems to start out at the beginning of the animation with a css background-color of black, even though it doesn't have any background color specifically set in the css. A bit of digging seems to suggest that the default background color of the element is rgba(0,0,0,0) and that Anime.js doesn't seem to work when using colors with alpha channels. I think this explains why the animation starts with black. Setting a background color for the element in the css seems to solve the issue, even if it has an alpha channel, but the alpha channel is never honored in the animation.

But what if I want to animate from a background color of rgba(0,0,0,0) to a solid color? A Google search does not reveal much information since Anime.js is fairly new. Does anybody know of any way that I can make this work in Anime.js? If Anime.js doesn't support this functionality, does anyone know of another JavaScript animation library that does? I need support for animating colors with alpha channels.

For convenience, here's a demo of what I've slapped together so far
in a quick CodePen.

答:
It is unclear to me whether anime.js supports opacity. You can however user JQuery animate, with JQuery UI installed.

```<code>$('#a').animate({ 'background-color': 'rgba(0, 0, 0, 0.7)' },1000);
</code>```

You can see the complete answer in How can I animate the opacity of the background of the div

Body:
So I've been playing around with Anime.js. I'm using this short bit of code to try and animate a div tag with a single letter id of a.

anime({
    targets: "#a",
    translateX: 250,
    color: "#fff",
    backgroundColor: "hsl(200, 50%, 50%)",
    loop: true,
    direction: 'alternate',
    easing: 'easeInOutQuad'
});

The problem is that (at least for me in Google Chrome) the element seems to start out at the beginning of the animation with a css background-color of black, even though it doesn't have any background color specifically set in the css. A bit of digging seems to suggest that the default background color of the element is rgba(0,0,0,0) and that Anime.js doesn't seem to work when using colors with alpha channels. I think this explains why the animation starts with black. Setting a background color for the element in the css seems to solve the issue, even if it has an alpha channel, but the alpha channel is never honored in the animation.

But what if I want to animate from a background color of rgba(0,0,0,0) to a solid color? A Google search does not reveal much information since Anime.js is fairly new. Does anybody know of any way that I can make this work in Anime.js? If Anime.js doesn't support this functionality, does anyone know of another JavaScript animation library that does? I need support for animating colors with alpha channels.

For convenience, here's a demo of what I've slapped together so far
in a quick CodePen.

Body:
It is unclear to me whether anime.js supports opacity. You can however user JQuery animate, with JQuery UI installed.

$('#a').animate({ 'background-color': 'rgba(0, 0, 0, 0.7)' },1000);

You can see the complete answer in How can I animate the opacity of the background of the div


问:
How do I pass `rails new` flags from my Rails template
Rails application templates sound great, and I want to create my own custom template instead of repeating myself to create a common base for every single application I create.

How do I run the equivalent of rails new --api --webpack=react --database=postgresql from inside my template so that it automatically does this when I run rails new myapp -m http://example.com/template.rb

答:
You don't. Application template is applied after rails app is already generated.

What you can do is overwrite some files/lines in your application template (replace database.yml, etc.). Or just add those flags in the rails new command, along with your template parameter.

If you want to always create apps with those flags, just put them in the .railsrc file and they'll be picked up automatically.

~/.railsrc

```<code>--api
--webpack=react
--database=postgresql
</code>```

Body:
You don't. Application template is applied after rails app is already generated.

What you can do is overwrite some files/lines in your application template (replace database.yml, etc.). Or just add those flags in the rails new command, along with your template parameter.

If you want to always create apps with those flags, just put them in the .railsrc file and they'll be picked up automatically.

~/.railsrc

--api
--webpack=react
--database=postgresql


问:
Create a program that calculates the square root of a number without using Math.sqrt
This is the formula that can be used to calculate the square root of a number.

```<code>result=(guess+(number/guess))/2;
</code>```

For example, I need to get the square root of 9. First, I need to make a guess. For this one, it's 6. Although, I know that the square root of 9 is 3, I chose 6 to show how the program should work.

that makes...

```<code>result=(6+(9/6))/2 which is equal to 3.75.
</code>```

To get the actual square root of 9, I need to make the result the new guess.The program should continue as...

```<code>result=(3.75+(9/3.75))/2 which is equal to 3.075.
</code>```

This process should continue till difference between result and the result after it is equal to 0. For example

```<code>result=(3+(9/3))/2 is always equal to 3.
</code>```

When the value of result is passed to guess, the next result will also be 3. That means 3 is the square root of nine.

Here's my code:

```<code>package javaPackage;

public class SquareRoot {

    public static void main(String[] args) {
        calcRoot();
    }

    public static void calcRoot(){
        double num=9;
        double guess=6;
        double result=0;

        while(Math.abs(guess-ans)!=0){
            result=(guess+(num/guess))/2;
            guess=result;
        }
    System.out.print(result);
    }
}
</code>```

Output

```<code>3.75
</code>```

My problem is I can't compare the value of result and the previous result. Since guess is equal to result, the program immediately since guess and result are already equal. How can I fix it?

答:
```<code>public static double sqrt(double number)
{
    double dd=number, sqi, sqrt=0;
    long i, b=0, e=0, c=1, z, d=(long)number, r=0, j;
    for (i=1l, sqi=1; ; i*=100l, sqi*=10)
    {
        if (i>dd)
        {
            i/=100;
            sqi/=10;
            j=i;
            break;
        }
    }
    for (z=0l; z<16; dd=(dd-(double)(r*i))*100, j/=100l, sqi/=10, z++)
    {
        r=(long)(dd/i);
        d=(e*100l)+r;
        int a=9;
        for (c=((b*10l)+a)*a; ; a--)
        {
            c=((b*10l)+a)*a;
            if (c<=d)
                break;
        }
        //if (a>=0)
        //    System.out.print(a);
        e=d-c;
        sqrt+=a*sqi;
        if (number==sqrt*sqrt && j==1)
            break;
        //if (j==1)
        //    System.out.print('.');
        b=b*10l+2l*(a);
    }
    return sqrt;
}
</code>```

Sorry for the undefined variable names....but this program really works!
This program is based on long division method of finding square root

Body:
This is the formula that can be used to calculate the square root of a number.

result=(guess+(number/guess))/2;

For example, I need to get the square root of 9. First, I need to make a guess. For this one, it's 6. Although, I know that the square root of 9 is 3, I chose 6 to show how the program should work.

that makes...

result=(6+(9/6))/2 which is equal to 3.75.

To get the actual square root of 9, I need to make the result the new guess.The program should continue as...

result=(3.75+(9/3.75))/2 which is equal to 3.075.

This process should continue till difference between result and the result after it is equal to 0. For example

result=(3+(9/3))/2 is always equal to 3.

When the value of result is passed to guess, the next result will also be 3. That means 3 is the square root of nine.

Here's my code:

package javaPackage;

public class SquareRoot {

    public static void main(String[] args) {
        calcRoot();
    }

    public static void calcRoot(){
        double num=9;
        double guess=6;
        double result=0;

        while(Math.abs(guess-ans)!=0){
            result=(guess+(num/guess))/2;
            guess=result;
        }
    System.out.print(result);
    }
}

Output

3.75

My problem is I can't compare the value of result and the previous result. Since guess is equal to result, the program immediately since guess and result are already equal. How can I fix it?

Body:
public static double sqrt(double number)
{
    double dd=number, sqi, sqrt=0;
    long i, b=0, e=0, c=1, z, d=(long)number, r=0, j;
    for (i=1l, sqi=1; ; i*=100l, sqi*=10)
    {
        if (i>dd)
        {
            i/=100;
            sqi/=10;
            j=i;
            break;
        }
    }
    for (z=0l; z<16; dd=(dd-(double)(r*i))*100, j/=100l, sqi/=10, z++)
    {
        r=(long)(dd/i);
        d=(e*100l)+r;
        int a=9;
        for (c=((b*10l)+a)*a; ; a--)
        {
            c=((b*10l)+a)*a;
            if (c<=d)
                break;
        }
        //if (a>=0)
        //    System.out.print(a);
        e=d-c;
        sqrt+=a*sqi;
        if (number==sqrt*sqrt && j==1)
            break;
        //if (j==1)
        //    System.out.print('.');
        b=b*10l+2l*(a);
    }
    return sqrt;
}

Sorry for the undefined variable names....but this program really works!
This program is based on long division method of finding square root


问:
Sending image with post
I want to fill some web-form with python script and send with POST-request. The problem is that form has fileuploading. I found this: poster for python. So, I came with FireBug at website with form and filled it. What I saw:

```<code>values[action]  add_save
values[mod] blog
values[depth]   2
values[pid] 121
values[title]   title
values[title_eng]   title_en
img PNG...[a lot of binary image data]
</code>```

That site uses authorization, so I have:

```<code>passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)

opener = poster.streaminghttp.register_openers()
opener.add_handler(authhandler)
</code>```

Now I came with default sample from website and wrote the code:

```<code>index = """some parsed integer"""
datagen, headers = multipart_encode({
        'values[action]': 'add_save',
        'values[mod]': 'blog',
        'values[depth]': '2',
        'values[pid]': index,
        'values[title]' : 'title',
        'values[title_eng]' : 'title_eng',
        'img': open('1.png', 'rb')
    })

request = urllib2.Request(theurl, datagen, headers)
getdata = urllib2.urlopen(request)
print getdata.read()
</code>```

I don't have errors, etc. But after sending POST the script doesn't add it into database (when I do that by hands everything is fine).

I added this code:

```<code>for value in datagen:
    print value
</code>```

And the result is: link. (123 number in text is that index variable value).

答: Have you checked the response of each of the requests you made(including logging in to the site) to make sure you have been served the correct page and have the correct cookie set?</p>

Title: Sending image with post

Body:
I want to fill some web-form with python script and send with POST-request. The problem is that form has fileuploading. I found this: poster for python. So, I came with FireBug at website with form and filled it. What I saw:

values[action]  add_save
values[mod] blog
values[depth]   2
values[pid] 121
values[title]   title
values[title_eng]   title_en
img PNG...[a lot of binary image data]

That site uses authorization, so I have:

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)

opener = poster.streaminghttp.register_openers()
opener.add_handler(authhandler)

Now I came with default sample from website and wrote the code:

index = """some parsed integer"""
datagen, headers = multipart_encode({
        'values[action]': 'add_save',
        'values[mod]': 'blog',
        'values[depth]': '2',
        'values[pid]': index,
        'values[title]' : 'title',
        'values[title_eng]' : 'title_eng',
        'img': open('1.png', 'rb')
    })

request = urllib2.Request(theurl, datagen, headers)
getdata = urllib2.urlopen(request)
print getdata.read()

I don't have errors, etc. But after sending POST the script doesn't add it into database (when I do that by hands everything is fine).

I added this code:

for value in datagen:
    print value

And the result is: link. (123 number in text is that index variable value).


问:
Enforce attribute addition for all classes that implement an interface
Let's say I have the simplest of interfaces for all components in my program.

```<code>public interface IComponent
{
}
</code>```

I know that every single component to be written for the project has to implement this interface, and I know that all of these components will be saved to disk using C#'s BinaryFormatter. That means that every component has to be decorated with the [Serializable] attribute. Is there a way to enforce the addition of this attribute now?

I say "now" because I can find various SO questions that tell me this isn't possible - but all of the questions I can find are from 2008. Has anything in the C# spec changed since then? Or do I have to use one of the workarounds described in the old answers?

答: You could write unit tests that picks ups all implementation of IComponent from your library using reflection and checks if they have the Serializable attribute on them. I don't belive anything new was introduced in .NET since 2008 that could make that check compile time specific, sorry.

Body:
Let's say I have the simplest of interfaces for all components in my program.

public interface IComponent
{
}

I know that every single component to be written for the project has to implement this interface, and I know that all of these components will be saved to disk using C#'s BinaryFormatter. That means that every component has to be decorated with the [Serializable] attribute. Is there a way to enforce the addition of this attribute now?

I say "now" because I can find various SO questions that tell me this isn't possible - but all of the questions I can find are from 2008. Has anything in the C# spec changed since then? Or do I have to use one of the workarounds described in the old answers?


问:
Rails 5.1.: destroy records in "has_many: through" association with restriction
I have classic has_many: through relationship:

```<code>class UserGroup < ApplicationRecord
  has_many :user_groups_users
  has_many :users, through: :user_groups_users
end

class UserGroupsUser < ApplicationRecord
  belongs_to :user_group
  belongs_to :user
end

class User < ApplicationRecord
  has_many :user_groups_users
  has_many :user_groups, through: :user_groups_users
end
</code>```

and in order to destroy UserGroup record, I need to destroy appropriate records in UserGroupsUser, which both is part of a gem. Otherwise I will get back error that there are Users tied to UserGroups and I cannot destroy particular UserGroup.

At the moment in my Controller I have this:

```<code>  def destroy
    @user_group = UserGroup.find(params[:id])
    UserGroupsUser.where(user_group_id: @user_group).destroy_all
    respond_to do |format|
    if @user_group.destroy
      format.js { flash.now[:notice] = "User group #{@user_group.name} deleted!" }
      format.html { redirect_to user_groups_url }
      format.json { head :no_content }
    else
      format.js { flash[:danger] = "User group #{@user_group.name} cannot be deleted because
                                   #{@user_group.users.size} users belong to it" }
    end
    end
  end
</code>```

however when I click Delete button in View, it destroys a record before I accept that in my modal window. How do I make it do destroy action, after accept in view, please? As I undestand it would require that after accept, it would firs destroy records in through models and then UserGroup.

My "Delete" action in View is quite regular:

```<code><%= link_to 'Delete', user_group, method: :delete, remote: true,
data: { confirm: "Do you confirm deleting #{user_group.name}?" }, class: 'btn-danger btn btn-xs' %>
</code>```

答:
Just change has_many :user_groups_users to has_many :user_groups_users, :dependent => :destroy

See more at Association Basics.

Edit: You said it was in a gem. Not an issue, still! Find the class, and add this in an initializer (I know, I know, there are better places, but for the sake of moving on from this):

```<code>Whatever::To::UserGroupThing.class_eval do
  has_many :user_group_users, :dependent => :destroy
end
</code>```

But maintenance may not be your friend here if there's some sort of change to the association made down the line by the maintainer.

You could also use a before_destroy hook in user_group.rb

```<code>before_destroy do
  UserGroupUser.where(:user_group => self).destroy_all
end
</code>```

Body:
I have classic has_many: through relationship:

class UserGroup < ApplicationRecord
  has_many :user_groups_users
  has_many :users, through: :user_groups_users
end

class UserGroupsUser < ApplicationRecord
  belongs_to :user_group
  belongs_to :user
end

class User < ApplicationRecord
  has_many :user_groups_users
  has_many :user_groups, through: :user_groups_users
end

and in order to destroy UserGroup record, I need to destroy appropriate records in UserGroupsUser, which both is part of a gem. Otherwise I will get back error that there are Users tied to UserGroups and I cannot destroy particular UserGroup.

At the moment in my Controller I have this:

  def destroy
    @user_group = UserGroup.find(params[:id])
    UserGroupsUser.where(user_group_id: @user_group).destroy_all
    respond_to do |format|
    if @user_group.destroy
      format.js { flash.now[:notice] = "User group #{@user_group.name} deleted!" }
      format.html { redirect_to user_groups_url }
      format.json { head :no_content }
    else
      format.js { flash[:danger] = "User group #{@user_group.name} cannot be deleted because
                                   #{@user_group.users.size} users belong to it" }
    end
    end
  end

however when I click Delete button in View, it destroys a record before I accept that in my modal window. How do I make it do destroy action, after accept in view, please? As I undestand it would require that after accept, it would firs destroy records in through models and then UserGroup.

My "Delete" action in View is quite regular:

<%= link_to 'Delete', user_group, method: :delete, remote: true,
data: { confirm: "Do you confirm deleting #{user_group.name}?" }, class: 'btn-danger btn btn-xs' %>

Body:
Just change has_many :user_groups_users to has_many :user_groups_users, :dependent => :destroy

See more at Association Basics.

Edit: You said it was in a gem. Not an issue, still! Find the class, and add this in an initializer (I know, I know, there are better places, but for the sake of moving on from this):

Whatever::To::UserGroupThing.class_eval do
  has_many :user_group_users, :dependent => :destroy
end

But maintenance may not be your friend here if there's some sort of change to the association made down the line by the maintainer.

You could also use a before_destroy hook in user_group.rb

before_destroy do
  UserGroupUser.where(:user_group => self).destroy_all
end


问:
Catchable fatal error: Object of class mysqli_result could not be converted to string on line 73
I am making a form for updating the data in the database, but it is throwing me this error Catchable fatal error: Object of class mysqli_result could not be converted to string on line 73

I have tried outputting all the data and all are printing but not updating in the database.

Please give some suggestion, how to solve it?

$id = $_GET['id'];
$t_id = $_GET['table_id'] - 2;

if(isset($_POST['submit'])){

  $name = $_POST['name'];
  $phone = $_POST['phone'];
  $email = $_POST['email'];
  $gender = intval($_POST['gender']);
  $treatment = intval($_POST['treatment']);
  $source = intval($_POST['source']);
  $status_ = intval($_POST['status']);
  $remark = $_POST['remark'];

//below code is line 73

$leadUpdateSql = "UPDATE lead SET
                     name = $name
                    ,phone = $phone
                    ,email = $email
                    ,gender_id = $gender
                    ,treatment_id = $treatment
                    ,source_id = $source
                    ,status_id = $status
                    ,remark = $remark
                     WHERE lead.id = $id";

if ($conn->query($leadUpdateSql) === TRUE) {
    echo "Record updated successfully";
    header("location:edit.php?id=$id&table_id=$t_id&updated=successfully");
   }

}```

答:
I have managed to solve the issue. I have added quotes for string values.

$id = $_GET['id'];
$t_id = $_GET['table_id'] - 2;

if(isset($_POST['submit'])){

    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $gender = intval($_POST['gender']);
    $treatment = intval($_POST['treatment']);
    $source = intval($_POST['source']);
    $status_ = intval($_POST['status']);
    $remark = $_POST['remark'];

$leadUpdateSql = "UPDATE lead SET
         name='$name' // here was the issue, now added quotes
        ,phone='$phone' // here was the issue
        ,email='$email' // here was the issue
        ,gender_id=$gender
        ,treatment_id=$treatment
        ,source_id=$source
        ,status_id=$status_
        ,remark='$remark'   // here was the issue
         WHERE lead.id=$id";

if ($conn->query($leadUpdateSql) === TRUE) {

    header("location:index.php?updated=successfully&table_id=$table_id#$t_id");
   }

else{
    header("location:edit.php?id=$id&table_id=$t_id&error=unsuccess");
}
}```


问:
Setting up singleton connection with node.js and mongo
Previously I used mongodb with php and to query a database I was using a singleton. This way I instantiated connection only once and then reused it:

```<code>class MDB{
    protected static $instance;
    public static function use(){
        if(!self::$instance) self::$instance = new MongoClient();
        $db = self::$instance->selectDB('DB_name');
        return $db;
    }
}
</code>```

Than I can create class Cats and have too methods addCat and showCats with something like this:

```<code>MDB::use->{'cats'}->insert([...]);
MDB::use->{'cats'}->find([...]);
</code>```

Right now I started to use mongodb with node.js. Mongodb tutorial shows me something like this:

```<code>var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(err) { return console.dir(err); }

  var collection = db.collection('test');
  var doc1 = {'hello':'doc1'};
  collection.insert(doc1);
});
</code>```

Which basically tells me that I have to set up all node operations as a callback inside of connect. Reading similar question the person offers:

You open do MongoClient.connect once when your app boots up and reuse
  the db object. It's not a singleton connection pool each .connect
  creates a new connection pool.

But I can not understand how should I use it (for example with my cat class)?

答:
Here is what uses async await on singleton.
In my db.js

```<code>var MongoClient = require('mongodb').MongoClient;

var DbConnection = function () {

    var db = null;
    var instance = 0;

    async function DbConnect() {
        try {
            let url = 'mongodb://myurl.blablabla';
            let _db = await MongoClient.connect(url);

            return _db
        } catch (e) {
            return e;
        }
    }

   async function Get() {
        try {
            instance++;     // this is just to count how many times our singleton is called.
            console.log(`DbConnection called ${instance} times`);

            if (db != null) {
                console.log(`db connection is already alive`);
                return db;
            } else {
                console.log(`getting new db connection`);
                db = await DbConnect();
                return db;
            }
        } catch (e) {
            return e;
        }
    }

    return {
        Get: Get
    }
}

module.exports = DbConnection();
</code>```

And in all modules that will use the same connection

```<code>var DbConnection = require('./db');

async function insert(data) {
    try {
        let db = await DbConnection.Get();
        let result = await db.collection('mycollection').insert(data);

        return result;
    } catch (e) {
        return e;
    }
}
</code>```

Body:
Previously I used mongodb with php and to query a database I was using a singleton. This way I instantiated connection only once and then reused it:

class MDB{
    protected static $instance;
    public static function use(){
        if(!self::$instance) self::$instance = new MongoClient();
        $db = self::$instance->selectDB('DB_name');
        return $db;
    }
}

Than I can create class Cats and have too methods addCat and showCats with something like this:

MDB::use->{'cats'}->insert([...]);
MDB::use->{'cats'}->find([...]);

Right now I started to use mongodb with node.js. Mongodb tutorial shows me something like this:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(err) { return console.dir(err); }

  var collection = db.collection('test');
  var doc1 = {'hello':'doc1'};
  collection.insert(doc1);
});

Which basically tells me that I have to set up all node operations as a callback inside of connect. Reading similar question the person offers:

You open do MongoClient.connect once when your app boots up and reuse
  the db object. It's not a singleton connection pool each .connect
  creates a new connection pool.

But I can not understand how should I use it (for example with my cat class)?

Body:
Here is what uses async await on singleton.
In my db.js

var MongoClient = require('mongodb').MongoClient;

var DbConnection = function () {

    var db = null;
    var instance = 0;

    async function DbConnect() {
        try {
            let url = 'mongodb://myurl.blablabla';
            let _db = await MongoClient.connect(url);

            return _db
        } catch (e) {
            return e;
        }
    }

   async function Get() {
        try {
            instance++;     // this is just to count how many times our singleton is called.
            console.log(`DbConnection called ${instance} times`);

            if (db != null) {
                console.log(`db connection is already alive`);
                return db;
            } else {
                console.log(`getting new db connection`);
                db = await DbConnect();
                return db;
            }
        } catch (e) {
            return e;
        }
    }

    return {
        Get: Get
    }
}

module.exports = DbConnection();

And in all modules that will use the same connection

var DbConnection = require('./db');

async function insert(data) {
    try {
        let db = await DbConnection.Get();
        let result = await db.collection('mycollection').insert(data);

        return result;
    } catch (e) {
        return e;
    }
}


问:
Sorted a Python dictionary by changing a key, now when I try to iterate through it, it iterates through the changed key
I have a dictionary of Arrays in Python such that

```<code>dictionary={a:[1,2,3,4],b:[2,3,4,8],c:[3,5,6,5]}
</code>```

and so on and so on

I've already sorted the dictionary so that it is now sorted by the fourth item of every array so the order goes b,c,a

```<code>dictionary=sorted(dictionary.values(),key=itemgetter(3),reverse=True)
</code>```

The problem is, when I try to iterate through the keys, it shoots out the key as the array itself.

```<code>for key in dictionary:
    print(key)
</code>```

prints out [2,3,4,8], however, I want it to iterate through b,c,a in that order.

Is there an easy way to do this?

答:
You are forgetting a small but very important point about python dictionaries. They cannot be sorted!

What you are actually doing in your code is sorting the dictionary values. To make a dictionary appear to be sorted, you need to created a sorted list which is made up of the dictionary keys.

```<code>keys = sorted(dictionary, key=lambda x: (dictionary[x][3],x))
for k in keys:
   print (k, dictionary[k])
</code>```

Body:
I have a dictionary of Arrays in Python such that

dictionary={a:[1,2,3,4],b:[2,3,4,8],c:[3,5,6,5]}

and so on and so on

I've already sorted the dictionary so that it is now sorted by the fourth item of every array so the order goes b,c,a

dictionary=sorted(dictionary.values(),key=itemgetter(3),reverse=True)

The problem is, when I try to iterate through the keys, it shoots out the key as the array itself.

for key in dictionary:
    print(key)

prints out [2,3,4,8], however, I want it to iterate through b,c,a in that order.

Is there an easy way to do this?

Body:
You are forgetting a small but very important point about python dictionaries. They cannot be sorted!

What you are actually doing in your code is sorting the dictionary values. To make a dictionary appear to be sorted, you need to created a sorted list which is made up of the dictionary keys.

keys = sorted(dictionary, key=lambda x: (dictionary[x][3],x))
for k in keys:
   print (k, dictionary[k])


问:
GIT error - this exceeds GitHubs file size limit - but the file has already been removed
I tried to publish a file which was over 100MB

I then looked it up and realised GitHub has a limit.

Whilst it looks like I can make changes to use larger file Git lfs - "this exceeds GitHub's file size limit of 100.00 MB" that's not my goal. Instead, I edited the file and it's now under around 80MB

The issue is, when I try to git pull (or sync using the web application) I still get told this file is too big...

I can only guess git has got a handle to something which no longer exists but I have no idea how to remove it from attempted to upload this file.

This is my effort which also shows the failure (the first line). This is copied from the Git Shell

```<code>remote: error: File Photoshop/Originals/homePage.psd is 119.97 MB; this exceeds GitHub's file size limit of 100.00 MB
To https://github.com/company/site.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/company/site.git'
G:\websites\GitHub\site\Website\site[master ↑3 +0 ~1 -0 !]> git rm --cached Photoshop/Originals/homePage.psd
fatal: pathspec 'Photoshop/Originals/homePage.psd' did not match any files
G:\websites\GitHub\site\Website\site [master ↑3 +0 ~1 -0 !]> git rm Photoshop/Originals/homePage.psd
fatal: pathspec 'Photoshop/Originals/homePage.psd' did not match any files
G:\websites\GitHub\site\Website\site [master ↑3 +0 ~1 -0 !]>
</code>```

答:
Try and use BFG Repo-Cleaner, but make sure your current working tree has no change in progress (add and commit first)

```<code>cd /path/to/your/local/repo
java -jar bfg.jar --strip-blobs-bigger-than 100M some-big-repo.git
git reflog expire --expire=now --all && git gc --prune=now --aggressive
</code>```

Then push the new history (force push to overwrite: make sure you are the only one working on that repo, or do communicate your rewrite)

```<code>git push --force
</code>```

Body:
I tried to publish a file which was over 100MB

I then looked it up and realised GitHub has a limit.

Whilst it looks like I can make changes to use larger file Git lfs - "this exceeds GitHub's file size limit of 100.00 MB" that's not my goal. Instead, I edited the file and it's now under around 80MB

The issue is, when I try to git pull (or sync using the web application) I still get told this file is too big...

I can only guess git has got a handle to something which no longer exists but I have no idea how to remove it from attempted to upload this file.

This is my effort which also shows the failure (the first line). This is copied from the Git Shell

remote: error: File Photoshop/Originals/homePage.psd is 119.97 MB; this exceeds GitHub's file size limit of 100.00 MB
To https://github.com/company/site.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/company/site.git'
G:\websites\GitHub\site\Website\site[master ↑3 +0 ~1 -0 !]> git rm --cached Photoshop/Originals/homePage.psd
fatal: pathspec 'Photoshop/Originals/homePage.psd' did not match any files
G:\websites\GitHub\site\Website\site [master ↑3 +0 ~1 -0 !]> git rm Photoshop/Originals/homePage.psd
fatal: pathspec 'Photoshop/Originals/homePage.psd' did not match any files
G:\websites\GitHub\site\Website\site [master ↑3 +0 ~1 -0 !]>

Body:
Try and use BFG Repo-Cleaner, but make sure your current working tree has no change in progress (add and commit first)

cd /path/to/your/local/repo
java -jar bfg.jar --strip-blobs-bigger-than 100M some-big-repo.git
git reflog expire --expire=now --all && git gc --prune=now --aggressive

Then push the new history (force push to overwrite: make sure you are the only one working on that repo, or do communicate your rewrite)

git push --force


问:
How to create WPF/Silverlight module utilizing prism but also that can be embedded in non-prism applicationss
I want to have create a WPF or Silverlight module  which cannot only be utilised by Shell's bootstrapper, but also can be embedded in non-PRISM applications.

In short is there a way PRISM module can be intialised from module itself rather than initialsing from Shell?

Ulimate goal is to have WPF/Silverlight PRISM module, which can be initialsed by non-PRISM applications.

答:
There is no barrier to this.

The IModule interface has a single, parameterless void method: Initialize().

A non-prism application can initialize the module by calling that method. That's it.

If the other application has a different plugin system, with a different interface, your module can implement that interface as well, and the body of whatever initialization method that interface uses can simply call Initialize(), or vice versa.

For example:

```<code>public interface IMyPluginModule
{
    void StartModule();
}

public class MyModule : IModule, IMyPluginModule
{
    public void Initialize()
    {
        // actual initialization code here
    }

    public void StartModule()
    {
        Initialize();
    }
}
</code>```

Body:
There is no barrier to this.

The IModule interface has a single, parameterless void method: Initialize().

A non-prism application can initialize the module by calling that method. That's it.

If the other application has a different plugin system, with a different interface, your module can implement that interface as well, and the body of whatever initialization method that interface uses can simply call Initialize(), or vice versa.

For example:

public interface IMyPluginModule
{
    void StartModule();
}

public class MyModule : IModule, IMyPluginModule
{
    public void Initialize()
    {
        // actual initialization code here
    }

    public void StartModule()
    {
        Initialize();
    }
}