问:
calculates highest count words across lines error in ruby coursera
it's almost 2 weeks now I can't remove this from my head. I'm a newbie in ruby and I'm stuck with this last bit of Ruby on Rails an introduction course on coursera. It'll certainly be easy to figure out what's wrong here but I need help to finish this course in time this time around.

#Implement all parts of this assignment within (this) module2_assignment2.rb file

#Implement a class called LineAnalyzer.
class LineAnalyzer
  #Implement the following read-only attributes in the LineAnalyzer class.
  #* highest_wf_count - a number with maximum number of occurrences for a single word (calculated)
  #* highest_wf_words - an array of words with the maximum number of occurrences (calculated)
  #* content          - the string analyzed (provided)
  #* line_number      - the line number analyzed (provided)

  #Add the following methods in the LineAnalyzer class.
  #* initialize() - taking a line of text (content) and a line number
  #* calculate_word_frequency() - calculates result

  #Implement the initialize() method to:
  #* take in a line of text and line number
  #* initialize the content and line_number attributes
  #* call the calculate_word_frequency() method.

  #Implement the calculate_word_frequency() method to:
  #* calculate the maximum number of times a single word appears within
  #  provided content and store that in the highest_wf_count attribute.
  #* identify the words that were used the maximum number of times and
  #  store that in the highest_wf_words attribute.

    attr_accessor :highest_wf_count, :highest_wf_words, :content, :line_number

    def initialize(content, line)
    @content = content
    @line_number = line
    @highest_wf_count=0
    @highest_wf_words = []
    calculate_word_frequency()
  end

  def calculate_word_frequency()
    @highest_wf_words = Hash.new
    words = @content.split
    words.each { |w|
      if @highest_wf_words.has_key?(w)
        @highest_wf_words[w] += 1
      else
        @highest_wf_words[w] = 1
      end
    }
    @highest_wf_words.sort_by { |word, count| count }
    @highest_wf_words.each do |key, value|
      if value > @highest_wf_count
        @highest_wf_count = value
      end
    end
  end

  def highest_wf_count= (number)
    @highest_wf_count = number
  end

end

#  Implement a class called Solution.
class Solution

  # Implement the following read-only attributes in the Solution class.
  #* analyzers - an array of LineAnalyzer objects for each line in the file
  #* highest_count_across_lines - a number with the maximum value for highest_wf_words attribute in the analyzers array.
  #* highest_count_words_across_lines - a filtered array of LineAnalyzer objects with the highest_wf_words attribute
  #  equal to the highest_count_across_lines determined previously.

  # Implement the following methods in the Solution class.
  #* analyze_file() - processes 'test.txt' into an array of LineAnalyzers and stores them in analyzers.
  #* calculate_line_with_highest_frequency() - determines the highest_count_across_lines and
  #  highest_count_words_across_lines attribute values
  #* print_highest_word_frequency_across_lines() - prints the values of LineAnalyzer objects in
  #  highest_count_words_across_lines in the specified format

  # Implement the analyze_file() method() to:
  #* Read the 'test.txt' file in lines
  #* Create an array of LineAnalyzers for each line in the file

  # Implement the calculate_line_with_highest_frequency() method to:
  #* calculate the maximum value for highest_wf_count contained by the LineAnalyzer objects in analyzers array
  #  and stores this result in the highest_count_across_lines attribute.
  #* identifies the LineAnalyzer objects in the analyzers array that have highest_wf_count equal to highest_count_across_lines
  #  attribute value determined previously and stores them in highest_count_words_across_lines.

  #Implement the print_highest_word_frequency_across_lines() method to
  #* print the values of objects in highest_count_words_across_lines in the specified format

  attr_reader  :analyzers, :highest_count_across_lines, :highest_count_words_across_lines

  def initialize
    @highest_count_across_lines = nil
    @highest_count_words_across_lines = nil
    @analyzers = []
  end

  def analyze_file()
    File.foreach('test.txt') do |content, line|
      LineAnalyzer = LineAnalyzer.new(content, line)
      @analyzers << LineAnalyzer
    end
  end

  def calculate_line_with_highest_frequency()
    @highest_count_across_lines = 0
    @highest_count_words_across_lines = []
    @analyzers.each do |analyzers|
      if analyzers.highest_wf_words > @highest_count_across_lines
        @highest_count_across_lines = analyzers.highest_wf_count
      end
      analyzers.highest_wf_words.each do |key, value|
       if analyzers.highest_count_words_across_lines < value
          @highest_count_words_across_lines << key
       end
      end
    end
  end

  def print_highest_word_frequency_across_lines()
    @highest_count_words_across_lines = Array.new
    puts "The following words have the highest word frequency per line:"
  end
end```
</div>
</div>
</p>

<p>I keep on having 1 fail out of 19 on rspec like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>LineAnalyzer
  has accessor for highest_wf_count
  has accessor for highest_wf_words
  has accessor for content
  has accessor for line_number
  has method calculate_word_frequency
  calls calculate_word_frequency when created
  attributes and values
    has attributes content and line_number
    content attribute should have value "test"
    line_number attribute should have value 1
  #calculate_word_frequency
    highest_wf_count value is 3
    highest_wf_words will include "really" and "you"
    content attribute will have value "This is a really really really cool cool you you you"
    line_number attribute will have value 2

Solution
  should respond to #analyze_file
  should respond to #calculate_line_with_highest_frequency
  should respond to #print_highest_word_frequency_across_lines
  #analyze_file
    creates 3 line analyzers
  #calculate_line_with_highest_frequency
    calculates highest count across lines to be 4
    calculates highest count words across lines to be will, it, really (FAILED - 1)

Failures:

  1) Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really
     Failure/Error: words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten

     NoMethodError:
       undefined method `highest_wf_words' for "This":String
     # ./spec/solution_spec.rb:38:in `map'
     # ./spec/solution_spec.rb:38:in `block (3 levels) in <top (required)>'

Finished in 0.10817 seconds (files took 0.37345 seconds to load)
19 examples, 1 failure

Failed examples:

rspec ./spec/solution_spec.rb:31 # Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really</code>```

And this is the solution_spec file.
Where am I going astray? Please help, it ia a desperate call!

require_relative "../module2_assignment"
require 'rspec'

describe Solution do
  subject(:solution) { Solution.new }

  it { is_expected.to respond_to(:analyze_file) }
  it { is_expected.to respond_to(:calculate_line_with_highest_frequency) }
  it { is_expected.to respond_to(:print_highest_word_frequency_across_lines) }

  context "#analyze_file" do
    it "creates 3 line analyzers" do
      expect(solution.analyzers.length).to eq 0
      solution.analyze_file
      expect(solution.analyzers.length).to eq 3
    end
  end

  context "#calculate_line_with_highest_frequency" do

    it "calculates highest count across lines to be 4" do
      solution.analyze_file

      expect(solution.highest_count_across_lines).to be nil

      solution.calculate_line_with_highest_frequency

      expect(solution.highest_count_across_lines).to be 4
    end
    it "calculates highest count words across lines to be will, it, really" do
      solution.analyze_file

      expect(solution.highest_count_words_across_lines).to be nil

      solution.calculate_line_with_highest_frequency

      words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten
      expect(words_found).to match_array ["will", "it", "really"]
    end
  end

end```

答:
You have many problems.

Your Solution#analyze_file method, you are trying to use a constant (LineAnalyzer) as a variable: LineAnalyzer = LineAnalyzer.new(content, line). You need to change to:

```<code>line_analyzer = LineAnalyzer.new(content, line)
@analyzers << line_analyzer
</code>```

Your line variable in the same method is always nil. You can fix this by replacing the first line of the method with File.foreach('test.txt').with_index(1) do |content, line|.

Your calculation of @highest_count_across_lines doesn't work at all. Instead of setting it to zero and iterating as you do, just do:

```<code>@highest_count_across_lines = analyzers.map(&:highest_wf_count).max
</code>```

I'm frankly confused by the tests, and not super excited about figuring out how to make them pass. IMHO this course is teaching you non-idiomatic Ruby. But hopefully the above will get you on the right track.

Body:
it's almost 2 weeks now I can't remove this from my head. I'm a newbie in ruby and I'm stuck with this last bit of Ruby on Rails an introduction course on coursera. It'll certainly be easy to figure out what's wrong here but I need help to finish this course in time this time around.

#Implement all parts of this assignment within (this) module2_assignment2.rb file

#Implement a class called LineAnalyzer.
class LineAnalyzer
  #Implement the following read-only attributes in the LineAnalyzer class.
  #* highest_wf_count - a number with maximum number of occurrences for a single word (calculated)
  #* highest_wf_words - an array of words with the maximum number of occurrences (calculated)
  #* content          - the string analyzed (provided)
  #* line_number      - the line number analyzed (provided)

  #Add the following methods in the LineAnalyzer class.
  #* initialize() - taking a line of text (content) and a line number
  #* calculate_word_frequency() - calculates result

  #Implement the initialize() method to:
  #* take in a line of text and line number
  #* initialize the content and line_number attributes
  #* call the calculate_word_frequency() method.

  #Implement the calculate_word_frequency() method to:
  #* calculate the maximum number of times a single word appears within
  #  provided content and store that in the highest_wf_count attribute.
  #* identify the words that were used the maximum number of times and
  #  store that in the highest_wf_words attribute.

    attr_accessor :highest_wf_count, :highest_wf_words, :content, :line_number

    def initialize(content, line)
    @content = content
    @line_number = line
    @highest_wf_count=0
    @highest_wf_words = []
    calculate_word_frequency()
  end

  def calculate_word_frequency()
    @highest_wf_words = Hash.new
    words = @content.split
    words.each { |w|
      if @highest_wf_words.has_key?(w)
        @highest_wf_words[w] += 1
      else
        @highest_wf_words[w] = 1
      end
    }
    @highest_wf_words.sort_by { |word, count| count }
    @highest_wf_words.each do |key, value|
      if value > @highest_wf_count
        @highest_wf_count = value
      end
    end
  end

  def highest_wf_count= (number)
    @highest_wf_count = number
  end

end

#  Implement a class called Solution.
class Solution

  # Implement the following read-only attributes in the Solution class.
  #* analyzers - an array of LineAnalyzer objects for each line in the file
  #* highest_count_across_lines - a number with the maximum value for highest_wf_words attribute in the analyzers array.
  #* highest_count_words_across_lines - a filtered array of LineAnalyzer objects with the highest_wf_words attribute
  #  equal to the highest_count_across_lines determined previously.

  # Implement the following methods in the Solution class.
  #* analyze_file() - processes 'test.txt' into an array of LineAnalyzers and stores them in analyzers.
  #* calculate_line_with_highest_frequency() - determines the highest_count_across_lines and
  #  highest_count_words_across_lines attribute values
  #* print_highest_word_frequency_across_lines() - prints the values of LineAnalyzer objects in
  #  highest_count_words_across_lines in the specified format

  # Implement the analyze_file() method() to:
  #* Read the 'test.txt' file in lines
  #* Create an array of LineAnalyzers for each line in the file

  # Implement the calculate_line_with_highest_frequency() method to:
  #* calculate the maximum value for highest_wf_count contained by the LineAnalyzer objects in analyzers array
  #  and stores this result in the highest_count_across_lines attribute.
  #* identifies the LineAnalyzer objects in the analyzers array that have highest_wf_count equal to highest_count_across_lines
  #  attribute value determined previously and stores them in highest_count_words_across_lines.

  #Implement the print_highest_word_frequency_across_lines() method to
  #* print the values of objects in highest_count_words_across_lines in the specified format

  attr_reader  :analyzers, :highest_count_across_lines, :highest_count_words_across_lines

  def initialize
    @highest_count_across_lines = nil
    @highest_count_words_across_lines = nil
    @analyzers = []
  end

  def analyze_file()
    File.foreach('test.txt') do |content, line|
      LineAnalyzer = LineAnalyzer.new(content, line)
      @analyzers << LineAnalyzer
    end
  end

  def calculate_line_with_highest_frequency()
    @highest_count_across_lines = 0
    @highest_count_words_across_lines = []
    @analyzers.each do |analyzers|
      if analyzers.highest_wf_words > @highest_count_across_lines
        @highest_count_across_lines = analyzers.highest_wf_count
      end
      analyzers.highest_wf_words.each do |key, value|
       if analyzers.highest_count_words_across_lines < value
          @highest_count_words_across_lines << key
       end
      end
    end
  end

  def print_highest_word_frequency_across_lines()
    @highest_count_words_across_lines = Array.new
    puts "The following words have the highest word frequency per line:"
  end
end

I keep on having 1 fail out of 19 on rspec like this:

LineAnalyzer
  has accessor for highest_wf_count
  has accessor for highest_wf_words
  has accessor for content
  has accessor for line_number
  has method calculate_word_frequency
  calls calculate_word_frequency when created
  attributes and values
    has attributes content and line_number
    content attribute should have value "test"
    line_number attribute should have value 1
  #calculate_word_frequency
    highest_wf_count value is 3
    highest_wf_words will include "really" and "you"
    content attribute will have value "This is a really really really cool cool you you you"
    line_number attribute will have value 2

Solution
  should respond to #analyze_file
  should respond to #calculate_line_with_highest_frequency
  should respond to #print_highest_word_frequency_across_lines
  #analyze_file
    creates 3 line analyzers
  #calculate_line_with_highest_frequency
    calculates highest count across lines to be 4
    calculates highest count words across lines to be will, it, really (FAILED - 1)

Failures:

  1) Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really
     Failure/Error: words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten

     NoMethodError:
       undefined method `highest_wf_words' for "This":String
     # ./spec/solution_spec.rb:38:in `map'
     # ./spec/solution_spec.rb:38:in `block (3 levels) in <top (required)>'

Finished in 0.10817 seconds (files took 0.37345 seconds to load)
19 examples, 1 failure

Failed examples:

rspec ./spec/solution_spec.rb:31 # Solution#calculate_line_with_highest_frequency calculates highest count words across lines to be will, it, really

And this is the solution_spec file.
Where am I going astray? Please help, it ia a desperate call!

require_relative "../module2_assignment"
require 'rspec'

describe Solution do
  subject(:solution) { Solution.new }

  it { is_expected.to respond_to(:analyze_file) }
  it { is_expected.to respond_to(:calculate_line_with_highest_frequency) }
  it { is_expected.to respond_to(:print_highest_word_frequency_across_lines) }

  context "#analyze_file" do
    it "creates 3 line analyzers" do
      expect(solution.analyzers.length).to eq 0
      solution.analyze_file
      expect(solution.analyzers.length).to eq 3
    end
  end

  context "#calculate_line_with_highest_frequency" do

    it "calculates highest count across lines to be 4" do
      solution.analyze_file

      expect(solution.highest_count_across_lines).to be nil

      solution.calculate_line_with_highest_frequency

      expect(solution.highest_count_across_lines).to be 4
    end
    it "calculates highest count words across lines to be will, it, really" do
      solution.analyze_file

      expect(solution.highest_count_words_across_lines).to be nil

      solution.calculate_line_with_highest_frequency

      words_found = solution.highest_count_words_across_lines.map(&:highest_wf_words).flatten
      expect(words_found).to match_array ["will", "it", "really"]
    end
  end

end

Body:
You have many problems.

Your Solution#analyze_file method, you are trying to use a constant (LineAnalyzer) as a variable: LineAnalyzer = LineAnalyzer.new(content, line). You need to change to:

line_analyzer = LineAnalyzer.new(content, line)
@analyzers << line_analyzer

Your line variable in the same method is always nil. You can fix this by replacing the first line of the method with File.foreach('test.txt').with_index(1) do |content, line|.

Your calculation of @highest_count_across_lines doesn't work at all. Instead of setting it to zero and iterating as you do, just do:

@highest_count_across_lines = analyzers.map(&:highest_wf_count).max

I'm frankly confused by the tests, and not super excited about figuring out how to make them pass. IMHO this course is teaching you non-idiomatic Ruby. But hopefully the above will get you on the right track.


来源: stackexchange

问:
Display count results of requests with results of jobs horizontally and locations vertically 3 tables
So I have a primary table of data which holds IDs against a job and location, so for example:

Requests Table dbo.Requests

```<code>RequestID    JobID    LocationID
1            3        5
2            4        8
3            3        2
</code>```

Job Table dbo.Jobs

```<code>JobID    JobTitle
1        Job 1
2        Job 2
3        Job 3
</code>```

Location Table dbo.Locations

```<code>LocationID   LocationName
1            Location 1
2            Location 2
3            Location 3
</code>```

Now what I want to do is display a list of counts for jobs done and for locations, something like:

```<code>Job Title      Total Jobs    Location 1   Location 2  Location 3
Job 1          30            5            15          10
Job 2          10            2            2           6
Job 3          40            22           0           18
</code>```

So I've got the first part fine for displaying the jobs and total count, but I'm stuck getting the locations to list to the right hand side?

```<code>SELECT
 job.JobTitle
,isnull(COUNT(req.JobID),0) AS 'Total Jobs'

FROM  Requests req

RIGHT OUTER JOIN Jobs job
ON req.JobID = job.JobID

GROUP BY job.JobTitle
ORDER BY JobTitle
</code>```

Many thanks

答:
You can use the following query

```<code>SELECT JobID,JobTitle,[1],[2],[3],[4],[5],[6],[7],[8]
FROM
  (
    SELECT j.JobID,j.JobTitle,r.LocationID,r.RequestID
    FROM Jobs j
    LEFT JOIN Requests r ON r.JobID=j.JobID
  ) q PIVOT(COUNT(RequestID) FOR LocationID IN([1],[2],[3],[4],[5],[6],[7],[8])) p
</code>```

And if you want use dynamic number of columns you can generate script and execute it using EXEC

```<code>DECLARE @locationIDs varchar(200)=''

SELECT @locationIDs+=CONCAT(',[',LocationID,']')
FROM Locations
ORDER BY LocationID

SET @locationIDs=STUFF(@locationIDs,1,1,'')

--PRINT @locationIDs

DECLARE @query varchar(1000)=CONCAT('SELECT JobID,JobTitle,',@locationIDs,'
FROM
  (
    SELECT j.JobID,j.JobTitle,r.LocationID,r.RequestID
    FROM Jobs j
    LEFT JOIN Requests r ON r.JobID=j.JobID
  ) q PIVOT(COUNT(RequestID) FOR LocationID IN(',@locationIDs,')) p')

--PRINT @query

EXEC(@query)
</code>```

The variant with location titles

```<code>DECLARE
  @locationIDs varchar(200)='',
  @locationTitles varchar(2000)=''

SELECT
  @locationIDs+=CONCAT(',[',LocationID,']'),
  @locationTitles+=CONCAT(',[',LocationID,'] [',LocationName,']')
FROM Locations
ORDER BY LocationID

SET @locationIDs=STUFF(@locationIDs,1,1,'')
SET @locationTitles=STUFF(@locationTitles,1,1,'')

--PRINT @locationIDs
--PRINT @locationTitles

DECLARE @query varchar(2000)=CONCAT('SELECT JobID,JobTitle,',@locationTitles,'
FROM
  (
    SELECT j.JobID,j.JobTitle,r.LocationID,r.RequestID
    FROM Jobs j
    LEFT JOIN Requests r ON r.JobID=j.JobID
  ) q PIVOT(COUNT(RequestID) FOR LocationID IN(',@locationIDs,')) p')

--PRINT @query

EXEC(@query)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have a primary table of data which holds IDs against a job and location, so for example:

Requests Table dbo.Requests

RequestID    JobID    LocationID
1            3        5
2            4        8
3            3        2

Job Table dbo.Jobs

JobID    JobTitle
1        Job 1
2        Job 2
3        Job 3

Location Table dbo.Locations

LocationID   LocationName
1            Location 1
2            Location 2
3            Location 3

Now what I want to do is display a list of counts for jobs done and for locations, something like:

Job Title      Total Jobs    Location 1   Location 2  Location 3
Job 1          30            5            15          10
Job 2          10            2            2           6
Job 3          40            22           0           18

So I've got the first part fine for displaying the jobs and total count, but I'm stuck getting the locations to list to the right hand side?

SELECT
 job.JobTitle
,isnull(COUNT(req.JobID),0) AS 'Total Jobs'

FROM  Requests req

RIGHT OUTER JOIN Jobs job
ON req.JobID = job.JobID

GROUP BY job.JobTitle
ORDER BY JobTitle

Many thanks

Body:
You can use the following query

SELECT JobID,JobTitle,[1],[2],[3],[4],[5],[6],[7],[8]
FROM
  (
    SELECT j.JobID,j.JobTitle,r.LocationID,r.RequestID
    FROM Jobs j
    LEFT JOIN Requests r ON r.JobID=j.JobID
  ) q PIVOT(COUNT(RequestID) FOR LocationID IN([1],[2],[3],[4],[5],[6],[7],[8])) p

And if you want use dynamic number of columns you can generate script and execute it using EXEC

DECLARE @locationIDs varchar(200)=''

SELECT @locationIDs+=CONCAT(',[',LocationID,']')
FROM Locations
ORDER BY LocationID

SET @locationIDs=STUFF(@locationIDs,1,1,'')

--PRINT @locationIDs

DECLARE @query varchar(1000)=CONCAT('SELECT JobID,JobTitle,',@locationIDs,'
FROM
  (
    SELECT j.JobID,j.JobTitle,r.LocationID,r.RequestID
    FROM Jobs j
    LEFT JOIN Requests r ON r.JobID=j.JobID
  ) q PIVOT(COUNT(RequestID) FOR LocationID IN(',@locationIDs,')) p')

--PRINT @query

EXEC(@query)

The variant with location titles

DECLARE
  @locationIDs varchar(200)='',
  @locationTitles varchar(2000)=''

SELECT
  @locationIDs+=CONCAT(',[',LocationID,']'),
  @locationTitles+=CONCAT(',[',LocationID,'] [',LocationName,']')
FROM Locations
ORDER BY LocationID

SET @locationIDs=STUFF(@locationIDs,1,1,'')
SET @locationTitles=STUFF(@locationTitles,1,1,'')

--PRINT @locationIDs
--PRINT @locationTitles

DECLARE @query varchar(2000)=CONCAT('SELECT JobID,JobTitle,',@locationTitles,'
FROM
  (
    SELECT j.JobID,j.JobTitle,r.LocationID,r.RequestID
    FROM Jobs j
    LEFT JOIN Requests r ON r.JobID=j.JobID
  ) q PIVOT(COUNT(RequestID) FOR LocationID IN(',@locationIDs,')) p')

--PRINT @query

EXEC(@query)


问:
Array/Results Code not working
Good afternoon! I have 5 job titles in an array (mechanic, cleaner, driver, cashier, electrician). I'm also looking to have an input box and a submit button. I want to be able to put a number (let's say 3) and have the JS print out jobs 1,2 and 3, in this case it would print out mechanic, cleaner and driver. I'm a little confused on what to do. I'd appreciate some help.</p>

答:
Please refer below code:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

Input values to display
<input type="number" name="countval" id="countval" min="1" max="5"/>
<input type="button" value="submit" onclick="updatedisplay()" />

```

Title: Array/Results Code not working

Body:
Please refer below code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script>
   var jobTitles = ['mechanic', 'cleaner', 'driver', 'cashier', 'electrician']
   function updatedisplay(){
   var displayStr="";
   for(var i=0;i<document.getElementById("countval").value;i++)
   {
  displayStr+=jobTitles[i]+" ";
   }
 document.getElementById("selectedDisplay").innerHTML = displayStr;
   }
</script>
</head>
<body>
<label for="countval">Input values to display</label>
<input type="number" name="countval" id="countval" min="1" max="5"/>
<input type="button" value="submit" onclick="updatedisplay()" />
<div id="selectedDisplay"></div>

</body>
</html>


问:
Is there any race condition below?
I have below code in my express server (have cut it down for brevity). I have a common object which I'm adding/modifying/reading in three different restful end points. Since all http requests in nodejs are asynchronous, I could get both put and get request at the same time. So although PUT happened but lets say status is not updated, my GET could get a slightly stale response?

From what I understand, and my testing shows that there is no race condition here. Because updating results object is a synchronous operation and all async operations should wait for it. Can somebody help with a better explanation whether this is correct or not?

```<code>    var obj = {};
    const exec = require('child_process').exec;
    app.post('/foo', (req, res) => {
         var result = {};
         result.id = generateSomeRandomId();
         result.failed = 0;
         result.status = 'running'
         //execute some command and update result
         const child = exec('some command');
         child.stdout.on('data',  (data) => {
             //some logic
         });
         child.stderr.on('data',  (data) => {
             result.failed = result.failed + 1;
          });
         child.on('close',  (code, signal) => {
              if (signal !== null && signal !== undefined) {
                    result.status = 'cancelled';
              } else {
                    result.status = 'completed';
                    result.runtime = calculateRunTime();
                }
         });
         result.pid = child.pid;
         obj[result.id] = result;
         res.send(result);
    }

    app.put('/foo/:id', (req, res) => {
         var result =  obj[req.params.id];
         if (result.status === 'running' && result.pid !== undefined) {
              kill(result.pid, 'SIGKILL');
              result.status = 'cancelled';
              result.runtime = calculateRunTime();
         }
         res.send(result);
    }
    app.get('/foo/:id', (req, res) => {
         var result =  obj[req.params.id];
         res.send(result);
    }
</code>```

答:
You don't have anything I would call a "race condition"; there is an element of uncertainty at play here, but in practice it's not likely to matter.

It looks like your post starts a process and returns the ID, your put cancels the process, and your get returns the current state of the process. From this I gather that you'll never be able to get until your post completes and provides the ID.

If you make a get call that is received and returned before your exec asynchronous listeners complete, you'll get whatever the last in-progress state is - I assume that's by design. So the only possible conflict here is if you've made a put call to halt your process.

Both your put and your get are synchronous when it comes to interacting with your result object, so whichever one is received first is the one that will complete first. You can ignore the process cancellation request for our purposes because it doesn't modify the result object. There's no guarantee that they will be received in the same order they were sent by the client(s), that may or may not be a practical concern in your scenario.

I believe (though my memory may be faulty here), that if you were using cluster to handle requests in different processes, you wouldn't be able to pass data around via a shared object anyway, so any complexity added by that possibility is already ruled out.

So, variances in network performance and reliability are your only real wildcard here. The server will handle requests in the order they come in and give you the expected results. If you only have a single client, you can wait until you get the response from your previous request to send the next one, which would potentially slow down your performance unacceptably, but make it more or less bulletproof. Otherwise, just send off your requests and don't worry about it, just make your app robust enough to recognize & handle a 2nd cancellation request even if you've already cancelled the process.

Title: Is there any race condition below?

Body:
I have below code in my express server (have cut it down for brevity). I have a common object which I'm adding/modifying/reading in three different restful end points. Since all http requests in nodejs are asynchronous, I could get both put and get request at the same time. So although PUT happened but lets say status is not updated, my GET could get a slightly stale response?

From what I understand, and my testing shows that there is no race condition here. Because updating results object is a synchronous operation and all async operations should wait for it. Can somebody help with a better explanation whether this is correct or not?

    var obj = {};
    const exec = require('child_process').exec;
    app.post('/foo', (req, res) => {
         var result = {};
         result.id = generateSomeRandomId();
         result.failed = 0;
         result.status = 'running'
         //execute some command and update result
         const child = exec('some command');
         child.stdout.on('data',  (data) => {
             //some logic
         });
         child.stderr.on('data',  (data) => {
             result.failed = result.failed + 1;
          });
         child.on('close',  (code, signal) => {
              if (signal !== null && signal !== undefined) {
                    result.status = 'cancelled';
              } else {
                    result.status = 'completed';
                    result.runtime = calculateRunTime();
                }
         });
         result.pid = child.pid;
         obj[result.id] = result;
         res.send(result);
    }

    app.put('/foo/:id', (req, res) => {
         var result =  obj[req.params.id];
         if (result.status === 'running' && result.pid !== undefined) {
              kill(result.pid, 'SIGKILL');
              result.status = 'cancelled';
              result.runtime = calculateRunTime();
         }
         res.send(result);
    }
    app.get('/foo/:id', (req, res) => {
         var result =  obj[req.params.id];
         res.send(result);
    }


问:
TypeError: Cannot read property 'isCompleted' of undefined
Why is it undefined? when I tried to console log the foundTodo variable it will display undefine everytime I clicked the task.

```<code>const todos = [
{
    task: 'watching react tuts',
    isCompleted: true
},
{
    task: 'eat dinner',
    isCompleted: false
}
];

App.js
        toggleTask(task) {
        const foundTodo = _.find(this.state.todos, todo => task.todo == task);

        foundTodo.isCompleted = !foundTodo.isCompleted;
        this.setState({ todos: this.state.todos });
      }
</code>```

I'm new to react...so I try to create a todos app.

答:
Just change :

```<code>todo => task.todo == task
</code>```

to

```<code>todo => todo.task == task
</code>```

Body:
Why is it undefined? when I tried to console log the foundTodo variable it will display undefine everytime I clicked the task.

const todos = [
{
    task: 'watching react tuts',
    isCompleted: true
},
{
    task: 'eat dinner',
    isCompleted: false
}
];

App.js
        toggleTask(task) {
        const foundTodo = _.find(this.state.todos, todo => task.todo == task);

        foundTodo.isCompleted = !foundTodo.isCompleted;
        this.setState({ todos: this.state.todos });
      }

I'm new to react...so I try to create a todos app.

Body:
Just change :

todo => task.todo == task

to

todo => todo.task == task


问:
extract record on basis of date span
I have 2 tables MEMBEN and MEMELIG, data is as below.

MEMBEN details:

MEMELIG details:

i want to join two tables in such way that it does not give cartesian product but selective data on basis of datespan of Benefit eff and benefit end date, so consider for above example we take member with id = '1001',

below picture contains all details which i am looking for.

Expected result details

Please help on this i tried using WITH clause but not able to proceed with result.

答:
Looking into you sample data, it seems that you are looking for something like below.

```<code>SELECT m1.member_id
    ,lis_eff_dt
    ,lis_end_dt
    ,benefit_eff_dt
    ,benefit_end_dt
FROM memben m1
INNER JOIN memlig m2 ON m1.member_id = m2.member_id
    AND m1.member_id = '1001'
    AND m1.lis_eff_dt >= m2.benefit_eff_dt
    AND m1.lis_end_dt <= m2.benefit_end_dt;
</code>```

The cte version can be.

```<code>WITH cte (
    member_id
    ,lis_eff_dt
    ,lis_end_dt
    ,benefit_eff_dt
    ,benefit_end_dt
    )
AS (
    SELECT m1.member_id
        ,lis_eff_dt
        ,lis_end_dt
        ,benefit_eff_dt
        ,benefit_end_dt
    FROM memben m1
    INNER JOIN memlig m2 ON m1.member_id = m2.member_id
        AND m1.member_id = '1001'
        AND m1.lis_eff_dt >= m2.benefit_eff_dt
        AND m1.lis_end_dt <= m2.benefit_end_dt
    )
SELECT *
FROM cte;
</code>```

You can check the demo here

Title: extract record on basis of date span

Body:
Looking into you sample data, it seems that you are looking for something like below.

SELECT m1.member_id
    ,lis_eff_dt
    ,lis_end_dt
    ,benefit_eff_dt
    ,benefit_end_dt
FROM memben m1
INNER JOIN memlig m2 ON m1.member_id = m2.member_id
    AND m1.member_id = '1001'
    AND m1.lis_eff_dt >= m2.benefit_eff_dt
    AND m1.lis_end_dt <= m2.benefit_end_dt;

The cte version can be.

WITH cte (
    member_id
    ,lis_eff_dt
    ,lis_end_dt
    ,benefit_eff_dt
    ,benefit_end_dt
    )
AS (
    SELECT m1.member_id
        ,lis_eff_dt
        ,lis_end_dt
        ,benefit_eff_dt
        ,benefit_end_dt
    FROM memben m1
    INNER JOIN memlig m2 ON m1.member_id = m2.member_id
        AND m1.member_id = '1001'
        AND m1.lis_eff_dt >= m2.benefit_eff_dt
        AND m1.lis_end_dt <= m2.benefit_end_dt
    )
SELECT *
FROM cte;

You can check the demo here


答:
Assuming that the code in your example is exactly what you have in your application, then it is probably due to bad variable naming. You have:

```<code>toggleTask(task) {
  const foundTodo = _.find(this.state.todos, todo => task.todo == task);
  ..
}
</code>```

In your arrow function todo is the param, but then you do task.todo == task.

It probably should be:

```<code>toggleTask(task) {
  const foundTodo = _.find(this.state.todos, todo => todo.task == task);
  ..
}
</code>```

Title: TypeError: Cannot read property 'isCompleted' of undefined

Body:
Assuming that the code in your example is exactly what you have in your application, then it is probably due to bad variable naming. You have:

toggleTask(task) {
  const foundTodo = _.find(this.state.todos, todo => task.todo == task);
  ..
}

In your arrow function todo is the param, but then you do task.todo == task.

It probably should be:

toggleTask(task) {
  const foundTodo = _.find(this.state.todos, todo => todo.task == task);
  ..
}


问:
Adding GD file resize and rename to php image upload script
I have this script which allows a picture to be uploaded and then a pointer is stored in a DB to the file on the file system. I got this script from another StackOverflow question and it does pretty much everything I need except for 2 things.
The first thing I need is to be able to resize the images and the second part I've just read about is to rename the file to prevent user errors etc.

Here is the upload file that takes the form data from the user input form and writes the data to DB and the picture to the images dir.

```<code> <?php

//This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];

// Connects to your Database
mysql_connect("yourhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("dbName") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
</code>```

答:
For resizing, here is an article explaining resizing images to any arbitrary size using GD. It has options for cropping or letter boxing to fit the destination aspect ratio.

http://www.spotlesswebdesign.com/blog.php?id=1

For filenames, just rename the files to a random id, and make sure you are not already using that id.

```<code>do {
    $filename = uniqid().'jpg';
} while (file_exists('image/path/'.$filename);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this script which allows a picture to be uploaded and then a pointer is stored in a DB to the file on the file system. I got this script from another StackOverflow question and it does pretty much everything I need except for 2 things.
The first thing I need is to be able to resize the images and the second part I've just read about is to rename the file to prevent user errors etc.

Here is the upload file that takes the form data from the user input form and writes the data to DB and the picture to the images dir.

 <?php

//This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];

// Connects to your Database
mysql_connect("yourhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("dbName") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>

Body:
For resizing, here is an article explaining resizing images to any arbitrary size using GD. It has options for cropping or letter boxing to fit the destination aspect ratio.

http://www.spotlesswebdesign.com/blog.php?id=1

For filenames, just rename the files to a random id, and make sure you are not already using that id.

do {
    $filename = uniqid().'jpg';
} while (file_exists('image/path/'.$filename);


问:
Sugar ORM No such table exception
Sugar ORM works perfectly on Android <5, but on Android 5> it crashes.
I am using version 1.4

Please help me.

Error: android.database.sqlite.SQLiteException: no such table: AUDIO (code 1): , while compiling: SELECT * FROM AUDIO

proguard-rules.pro

```<code>-keep class me.lobanov.mp3downloadsfree.models.** { *; }
</code>```

My model class:

```<code>package me.lobanov.mp3downloadsfree.models;

import com.orm.SugarRecord;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class Audio extends SugarRecord {
    private long aud_id;
    private String aud_artist;
    private String aud_title;
    private String aud_url;
    private long aud_duration;

    public Audio() {
    }

    public Audio(long aud_id, String aud_artist, String aud_title, String aud_url, long aud_duration){
        this.aud_id = aud_id;
        this.aud_artist = aud_artist;
        this.aud_title = aud_title;
        this.aud_url = aud_url;
        this.aud_duration = aud_duration;
    }
}
</code>```

My application class:

```<code>public class App extends SugarApp {
    @Override
    public void onCreate() {
        super.onCreate();
    }
}
</code>```

My manifest:

```<code><meta-data android:name="DATABASE" android:value="mp3downloadsfree.db" />
        <meta-data android:name="VERSION" android:value="5" />
        <meta-data android:name="QUERY_LOG" android:value="true" />
        <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="me.lobanov.mp3downloadsfree.models" />
</code>```

答: And after you disable instant run, make sure you uninstall the app from the phone/emulator before running again.</p>

Title: Sugar ORM No such table exception

Body:
Sugar ORM works perfectly on Android <5, but on Android 5> it crashes.
I am using version 1.4

Please help me.

Error: android.database.sqlite.SQLiteException: no such table: AUDIO (code 1): , while compiling: SELECT * FROM AUDIO

proguard-rules.pro

-keep class me.lobanov.mp3downloadsfree.models.** { *; }

My model class:

package me.lobanov.mp3downloadsfree.models;

import com.orm.SugarRecord;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class Audio extends SugarRecord {
    private long aud_id;
    private String aud_artist;
    private String aud_title;
    private String aud_url;
    private long aud_duration;

    public Audio() {
    }

    public Audio(long aud_id, String aud_artist, String aud_title, String aud_url, long aud_duration){
        this.aud_id = aud_id;
        this.aud_artist = aud_artist;
        this.aud_title = aud_title;
        this.aud_url = aud_url;
        this.aud_duration = aud_duration;
    }
}

My application class:

public class App extends SugarApp {
    @Override
    public void onCreate() {
        super.onCreate();
    }
}

My manifest:

<meta-data android:name="DATABASE" android:value="mp3downloadsfree.db" />
        <meta-data android:name="VERSION" android:value="5" />
        <meta-data android:name="QUERY_LOG" android:value="true" />
        <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="me.lobanov.mp3downloadsfree.models" />


问:
Execute code when website is closed
Is there a method to run code every time the user closes out of an ASP.NET webpage? I am pretty new to ASP and don't know very much about HTML.</p>

答:
I usually creat an unload function, and add a onbeforeunload to the parent body of where you'd like the function run, like so

```<code><body onbeforeunload="closingFunction()">

function closingFunction(){
    //DO STUFF
}
</code>```

There may be some more relevant information for you here

Title: Execute code when website is closed

Body:
I usually creat an unload function, and add a onbeforeunload to the parent body of where you'd like the function run, like so

<body onbeforeunload="closingFunction()">

function closingFunction(){
    //DO STUFF
}

There may be some more relevant information for you here


问:
Multiple URL are not opening from anchor tag by using window.open in safari
I am trying to open multiple URL in one click by using window.open but In Safari only one URL is opened in new tab other not.

Safari version is 11.0.1.

```<code>onclick="window.open('URL1','_blank');window.open('URL2','_blank');window.open('URL3','_blank');"
</code>```

答:
The pop up blocker in Chrome prevents opening multiple windows from one click. I assume Safari is the same. Firefox is more lenient but (I believe) there must be a user click to start with.

Hopefully you will not be able to resolve this - by design allowing multiple tabs to be opened from a single click has been prevented.

Body:
I am trying to open multiple URL in one click by using window.open but In Safari only one URL is opened in new tab other not.

Safari version is 11.0.1.

onclick="window.open('URL1','_blank');window.open('URL2','_blank');window.open('URL3','_blank');"


问:
AspectJ - pointcut to match a method that has generic parameters
I have a generic method that accepts any type as its parameter.

For example, I would like a pointcut that matches the calls made to the method only with 'String' type as its parameter. Ultimately the requirement is to limit the scope which the advices get executed for to 'String' parameters.

Here is my generic class and method:

```<code>public class Param<T> {
    public T execute(T s){
        return s;
    }
}
</code>```

Main class:  My app makes calls to the method with both Boolean and String as parameters.

```<code>public static void main(String[] args) {
    Param<String> sp = new Param<String>();
    String rs = sp.execute("myString"); //want a joint point

    Param<Boolean> bp = new Param<Boolean>();
    Boolean rb = bp.execute(true); //dont want a joint point
}
</code>```

Below pointcuts are valid for both String and Boolean parameters (work for any type actually). But I would like a pointcut to intercept method calls only when parameter is of type String.

```<code>@Pointcut("call(* com.amazon.auiqa.aspectj.generics.Param.execute(**))")
void param(){}

@Pointcut("execution(Object com.amazon.auiqa.aspectj.generics.Param.execute(Object))")
void param(){}
</code>```

Below ones did not work for me:

```<code> @Pointcut("execution(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")
 @Pointcut("call(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")
</code>```

I was wondering if it is possible to achieve what I want to achieve here. I would like to do the same thing with method return types.

答:
It's true what the other posting mentioned about Java erasure.

AspectJ 5 does not allow the use of type variables in pointcut expressions and type patterns. Instead, members that use type parameters as part of their signature are matched by their erasure. Java 5 defines the rules for determing the erasure of a type as follows.

Let |T| represent the erasure of some type T. Then:

The erasure of a parameterized type T<T1,...,Tn> is |T|. For example, the erasure of List<String> is List.

The erasure of a nested type T.C is |T|.C. For example, the erasure of the nested type Foo<T>.Bar is Foo.Bar.

The erasure of an array type T[] is |T|[]. For example, the erasure of List<String>[] is List[].

The erasure of a type variable is its leftmost bound. For example, the erasure of a type variable P is Object, and the erasure of a type variable N extends Number is Number.

You can find more here.

However, you can do the following:

Capture all execute method executions of Param.

Filter your requirements of String arguments by the type of argument by using instanceof.

Remember, a plus sign (+) is needed to indicate a generic.

Here is an example,

```<code>@Component
@Aspect
public class ParamAspect {

    @Pointcut("execution(public * com.amazon.auiqa.aspectj.generics.Param+.execute(..))")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void intercept(JoinPoint jp) {
        System.out.println(
                "Entering class: " + jp.getSignature().getDeclaringTypeName() +
                        " - before method: " + jp.getSignature().getName());

        // check for argument type of String
        Object[] args = jp.getArgs();
        if (args.length == 1) {
            if (args[0] instanceof String) {
                System.out.println("1. parameter type is string");
            } else {
                System.out.println("2. parameter type is not string");
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a generic method that accepts any type as its parameter.

For example, I would like a pointcut that matches the calls made to the method only with 'String' type as its parameter. Ultimately the requirement is to limit the scope which the advices get executed for to 'String' parameters.

Here is my generic class and method:

public class Param<T> {
    public T execute(T s){
        return s;
    }
}

Main class:  My app makes calls to the method with both Boolean and String as parameters.

public static void main(String[] args) {
    Param<String> sp = new Param<String>();
    String rs = sp.execute("myString"); //want a joint point

    Param<Boolean> bp = new Param<Boolean>();
    Boolean rb = bp.execute(true); //dont want a joint point
}

Below pointcuts are valid for both String and Boolean parameters (work for any type actually). But I would like a pointcut to intercept method calls only when parameter is of type String.

@Pointcut("call(* com.amazon.auiqa.aspectj.generics.Param.execute(**))")
void param(){}

@Pointcut("execution(Object com.amazon.auiqa.aspectj.generics.Param.execute(Object))")
void param(){}

Below ones did not work for me:

 @Pointcut("execution(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")
 @Pointcut("call(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")

I was wondering if it is possible to achieve what I want to achieve here. I would like to do the same thing with method return types.

Body:
It's true what the other posting mentioned about Java erasure.

AspectJ 5 does not allow the use of type variables in pointcut expressions and type patterns. Instead, members that use type parameters as part of their signature are matched by their erasure. Java 5 defines the rules for determing the erasure of a type as follows.

Let |T| represent the erasure of some type T. Then:

The erasure of a parameterized type T<T1,...,Tn> is |T|. For example, the erasure of List<String> is List.

The erasure of a nested type T.C is |T|.C. For example, the erasure of the nested type Foo<T>.Bar is Foo.Bar.

The erasure of an array type T[] is |T|[]. For example, the erasure of List<String>[] is List[].

The erasure of a type variable is its leftmost bound. For example, the erasure of a type variable P is Object, and the erasure of a type variable N extends Number is Number.

You can find more here.

However, you can do the following:

Capture all execute method executions of Param.

Filter your requirements of String arguments by the type of argument by using instanceof.

Remember, a plus sign (+) is needed to indicate a generic.

Here is an example,

@Component
@Aspect
public class ParamAspect {

    @Pointcut("execution(public * com.amazon.auiqa.aspectj.generics.Param+.execute(..))")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void intercept(JoinPoint jp) {
        System.out.println(
                "Entering class: " + jp.getSignature().getDeclaringTypeName() +
                        " - before method: " + jp.getSignature().getName());

        // check for argument type of String
        Object[] args = jp.getArgs();
        if (args.length == 1) {
            if (args[0] instanceof String) {
                System.out.println("1. parameter type is string");
            } else {
                System.out.println("2. parameter type is not string");
            }
        }
    }
}


问:
SVN dump of Apache Lucene’s repository
I want to take SVN dump of Apache Lucene’s repository. How to replicate the above repo to my local machine?</p>

答:
One option is to first create a local repository:

```<code>$ svnadmin create /path/to/your/repo
</code>```

Once you've created the repository, initialize it for syncing:

```<code>$ svnsync init /path/to/your/repo /path/to/source/repo
</code>```

Now that you're setup for syncing, sync to the new repository:

```<code>$ svnsync sync /path/to/source/repo
</code>```

When you don't want to keep the whole repository because you only need a single subdirectory, but you still want the whole history in subversion, you can then create a repository containing only the relevant sections:

```<code>$ svnadmin dump /path/to/your/repo | svndumpfilter include /path/to/correct/tree \
  > /path/to/filtered/repository/backup
</code>```

We now have a backup that has been filtered to include only the relevant tree.  So, now let's restore that to a new, usable repository:

```<code>$ svnadmin load --ignore-uuid /path/to/treeonly/repository \
  < /path/to/filtered/repository/backup
</code>```

See the help on svnsync, on repository replication, and repository filtering.

Title: SVN dump of Apache Lucene’s repository

Body:
One option is to first create a local repository:

$ svnadmin create /path/to/your/repo

Once you've created the repository, initialize it for syncing:

$ svnsync init /path/to/your/repo /path/to/source/repo

Now that you're setup for syncing, sync to the new repository:

$ svnsync sync /path/to/source/repo

When you don't want to keep the whole repository because you only need a single subdirectory, but you still want the whole history in subversion, you can then create a repository containing only the relevant sections:

$ svnadmin dump /path/to/your/repo | svndumpfilter include /path/to/correct/tree \
  > /path/to/filtered/repository/backup

We now have a backup that has been filtered to include only the relevant tree.  So, now let's restore that to a new, usable repository:

$ svnadmin load --ignore-uuid /path/to/treeonly/repository \
  < /path/to/filtered/repository/backup

See the help on svnsync, on repository replication, and repository filtering.


问:
how to remove both first and last line of csv file using sed
I can remove the first line of csv file's starting with myfile and merge them using:

```<code>sed 1d myfile*.csv > myfile_merged.csv
</code>```

I'd like to also remove the last line of the csv files.

I've tried:

```<code>sed 1d -i '$d' myfile*.csv > myfile_merged.csv
</code>```

But get the error:

```<code>sed: can't read $d: No such file or directory
</code>```

答:
What you're probably trying to do is:

```<code>sed -e '1d' -e '$d' myfile*.csv > merged.csv
</code>```

But this won't work, because it tells sed to remove the first and last line of ALL files, rather than EACH file.  In other words, you'll strip the first line of the first file, and the last line of the last file ... and that's it.

To process each file individually, you probably need to process each file .. individually.  :)

```<code>for f in myfile*.csv
    sed -e '1d;$d' "$f"
done > merged.csv
</code>```

Note that while this will run in bash, it's also POSIX compatible (both the shell and sed parts). And it does not care whether your input is CSV or any other format, as long as it can be parsed line by line using sed.

Body:
I can remove the first line of csv file's starting with myfile and merge them using:

sed 1d myfile*.csv > myfile_merged.csv

I'd like to also remove the last line of the csv files.

I've tried:

sed 1d -i '$d' myfile*.csv > myfile_merged.csv

But get the error:

sed: can't read $d: No such file or directory

Body:
What you're probably trying to do is:

sed -e '1d' -e '$d' myfile*.csv > merged.csv

But this won't work, because it tells sed to remove the first and last line of ALL files, rather than EACH file.  In other words, you'll strip the first line of the first file, and the last line of the last file ... and that's it.

To process each file individually, you probably need to process each file .. individually.  :)

for f in myfile*.csv
    sed -e '1d;$d' "$f"
done > merged.csv

Note that while this will run in bash, it's also POSIX compatible (both the shell and sed parts). And it does not care whether your input is CSV or any other format, as long as it can be parsed line by line using sed.


问:
Can I test SmtpClient before calling client.Send()?
This is related to a question I asked the other day on how to send email.

My new, related question is this... what if the user of my application is behind a firewall or some other reason why the line client.Send(mail) won't work...

After the lines:

```<code>SmtpClient client = new SmtpClient("mysmtpserver.com", myportID);
client.Credentials = new System.Net.NetworkCredential("myusername.com", "mypassword");
</code>```

is there something I can do to test client before I try sending?

I thought about putting this in a try/catch loop, but I'd rather do a test and then pop up a dialog saying:  can't access smtp or something like that.

(I'm presuming that neither I, nor potentially my application user, has the ability to adjust their firewall settings.  For example... they install the app at work and don't have control over their internet at work)

-Adeena

答:
```<code>    private bool isValidSMTP(string hostName)
    {
        bool hostAvailable= false;
        try
        {
            TcpClient smtpTestClient = new TcpClient();
            smtpTestClient.Connect(hostName, 25);
            if (smtpTestClient.Connected)//connection is established
            {
                NetworkStream netStream = smtpTestClient.GetStream();
                StreamReader sReader = new StreamReader(netStream);
                if (sReader.ReadLine().Contains("220"))//host is available for communication
                {
                    hostAvailable= true;
                }
                smtpTestClient.Close();
            }
        }
        catch
        {
          //some action like writing to error log
        }
        return hostAvailable;
    }
</code>```

OwnerDisplayName: adeena

Body:
This is related to a question I asked the other day on how to send email.

My new, related question is this... what if the user of my application is behind a firewall or some other reason why the line client.Send(mail) won't work...

After the lines:

SmtpClient client = new SmtpClient("mysmtpserver.com", myportID);
client.Credentials = new System.Net.NetworkCredential("myusername.com", "mypassword");

is there something I can do to test client before I try sending?

I thought about putting this in a try/catch loop, but I'd rather do a test and then pop up a dialog saying:  can't access smtp or something like that.

(I'm presuming that neither I, nor potentially my application user, has the ability to adjust their firewall settings.  For example... they install the app at work and don't have control over their internet at work)

-Adeena


问:
Create small polygons inside large polygons in SVG using javascript
I am very new to SVG graphics.I am trying to create multiple SVG polygons inside a svg rectangle.

I am facing challenge in creating smaller polygon inside big polygon.

My polygons are multi sided and not just triangles and rectangles. How do I get points of inner polygon , I have points of parent polygon and spacing distance between parent and child polygon

<svg width="120" height="120" viewBox="0 0 120 120"
     xmlns="http://www.w3.org/2000/svg">

  <polygon id="poly_depth1" points="60,20 100,40 100,80 60,100 20,80 20,40" fill="blue"/>
</svg>```

Consider above example , I have a polygon with id poly_depth1, I want to create another polygon 10px inside this polygon.I want to create this child polygon  using plain JavaScript or D3.The polygon should retain the same shape.

答:
The points attribute defines the x and y coordinates for each corner of the polygon. If you want smaller or bigger polygon you need to either add or subtract the distance from the x and y coordinates of the polygon.</p>

```<code><svg width="140" height="140" viewBox="0 0 120 120"
     xmlns="http://www.w3.org/2000/svg">

  <polygon id="poly_depth1" points="60,20 100,40 100,80 60,100 20,80 20,40" fill="blue"/>
  <polygon id="poly_depth2" points="60,35 90,50 90,70 60,85 30,70 30,50" fill="red"/>
</svg>
</code>```

Body:
I am very new to SVG graphics.I am trying to create multiple SVG polygons inside a svg rectangle.

I am facing challenge in creating smaller polygon inside big polygon.

My polygons are multi sided and not just triangles and rectangles. How do I get points of inner polygon , I have points of parent polygon and spacing distance between parent and child polygon

<svg width="120" height="120" viewBox="0 0 120 120"
     xmlns="http://www.w3.org/2000/svg">

  <polygon id="poly_depth1" points="60,20 100,40 100,80 60,100 20,80 20,40" fill="blue"/>
</svg>

Consider above example , I have a polygon with id poly_depth1, I want to create another polygon 10px inside this polygon.I want to create this child polygon  using plain JavaScript or D3.The polygon should retain the same shape.

Body:
The points attribute defines the x and y coordinates for each corner of the polygon. If you want smaller or bigger polygon you need to either add or subtract the distance from the x and y coordinates of the polygon.

<svg width="140" height="140" viewBox="0 0 120 120"
     xmlns="http://www.w3.org/2000/svg">

  <polygon id="poly_depth1" points="60,20 100,40 100,80 60,100 20,80 20,40" fill="blue"/>
  <polygon id="poly_depth2" points="60,35 90,50 90,70 60,85 30,70 30,50" fill="red"/>
</svg>


问:
DatabaseConnecton issue in GRDB swift
I would like to use SQLite database in my iOS app and there are different frameworks available. So my current focus is on GRDB and I have successfully created, inserted values, and received back with SQL commands as shown here.

However, once the app is closed, how am I going to access the same DataBaseQueue and what should be the constant path to my database?

```<code>import GRDB

// Open a simple database connection

if let dbQueue = try DatabaseQueue(path: "what should be the correct path ")!= nil{
    setupDatabase()
}
else
{
    dbQueue = DatabaseQueue()
}
</code>```

答:
The GRDB FAQ answers your question:

How do I create a database in my application?

The database has to be stored in a valid place where it can be created and modified. For example, in the Application Support directory:

```<code>let databaseURL = try FileManager.default
    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("db.sqlite")
let dbQueue = try DatabaseQueue(path: databaseURL.path)
</code>```

Title: DatabaseConnecton issue in GRDB swift

Body:
I would like to use SQLite database in my iOS app and there are different frameworks available. So my current focus is on GRDB and I have successfully created, inserted values, and received back with SQL commands as shown here.

However, once the app is closed, how am I going to access the same DataBaseQueue and what should be the constant path to my database?

import GRDB

// Open a simple database connection

if let dbQueue = try DatabaseQueue(path: "what should be the correct path ")!= nil{
    setupDatabase()
}
else
{
    dbQueue = DatabaseQueue()
}

Body:
The GRDB FAQ answers your question:

How do I create a database in my application?

The database has to be stored in a valid place where it can be created and modified. For example, in the Application Support directory:

let databaseURL = try FileManager.default
    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("db.sqlite")
let dbQueue = try DatabaseQueue(path: databaseURL.path)


问:
How to use python structure array similar to matlab
Good morning
   I have thoroughly looked around to try figuring out a way to create a
   matlab like struct array in python. My input .csv file is header less

My matlab code

```<code>  dumpdata = csvread('dumpdata.csv');
  N_dumpdata_samples = length(dumpdata);

  rec_sample_1second = struct('UTC_time',{},'sv_id_set',{},'pseudorange',
  {},'state',{});

  for s=1:1:N_dumpdata_samples

    rec_sample_1second(s).UTC_time = dumpdata(s,1);
   rec_sample_1second(s).UTC_time = round(rec_sample_1second(s).
   UTC_time * 10);
   rec_sample_1second(s).UTC_time = rec_sample_1second(s).
   UTC_time / 10;

   for t=1:1:15

       rec_sample_1second(s).sv_id_set(t) = dumpdata(s,t+1);
       rec_sample_1second(s).pseudorange(t) = dumpdata(s,t+16);
       rec_sample_1second(s).state(t) = dumpdata(s,t+31);
       end;
    end;
</code>```

Trying to implement in python

```<code>   import numpy as np
   import pandas as pd

   df = pd.read_csv('path'/Dumpdata.csv',header=None)
   N_dumpdata_samples=len(df)
   structure={}
   structure["parent1"] = {}
  UTC_time=[]
  for s in range(N_dumpdata_samples):
      # structure['parent1']['UTC_time']=df[s,0] -> this line give error
      UTC_time=df['s',0]
  .......
</code>```

My question is : How can I implement same logic and structure in python.

Thanks

答:
In Octave:

```<code>>> data = struct('A',{}, 'B', {});
>> for s=1:1;5
       data(s).A = s
       for t=1:1:3
           data(s).B(t) = s+t
       end;
   end;
</code>```

producing

```<code>>> data.A
ans =  1
ans =  2
ans =  3
ans =  4
ans =  5
>> data.B
ans =
   2   3   4
ans =
   3   4   5
ans =
   4   5   6
ans =
   5   6   7
ans =
   6   7   8
>> save -7 stack47277436.mat data
</code>```

Loading that in numpy with the scipy.io.loadmat:

```<code>In [17]: res = loadmat('stack47277436.mat')
In [18]: res
Out[18]:
{'__globals__': [],
 '__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.0.0, 2017-11-14 04:48:21 UTC',
 '__version__': '1.0',
 'data': array([[(array([[ 1.]]), array([[ 2.,  3.,  4.]])),
         (array([[ 2.]]), array([[ 3.,  4.,  5.]])),
         (array([[ 3.]]), array([[ 4.,  5.,  6.]])),
         (array([[ 4.]]), array([[ 5.,  6.,  7.]])),
         (array([[ 5.]]), array([[ 6.,  7.,  8.]]))]],
       dtype=[('A', 'O'), ('B', 'O')])}
</code>```

Or load with squeeze_me to remove the singular dimensions

```<code>In [22]: res = loadmat('stack47277436.mat',squeeze_me=True)
In [24]: res['data']
Out[24]:
array([(1.0, array([ 2.,  3.,  4.])), (2.0, array([ 3.,  4.,  5.])),
       (3.0, array([ 4.,  5.,  6.])), (4.0, array([ 5.,  6.,  7.])),
       (5.0, array([ 6.,  7.,  8.]))],
      dtype=[('A', 'O'), ('B', 'O')])
In [25]: _.shape
Out[25]: (5,)
</code>```

The struct has been translated into a structured array with 2 fields, corresponding to the struct fields (is that the MATLAB name?)

```<code>In [26]: res['data']['A']
Out[26]: array([1.0, 2.0, 3.0, 4.0, 5.0], dtype=object)
In [27]: res['data']['B']
Out[27]:
array([array([ 2.,  3.,  4.]), array([ 3.,  4.,  5.]),
       array([ 4.,  5.,  6.]), array([ 5.,  6.,  7.]),
       array([ 6.,  7.,  8.])], dtype=object)
</code>```

A is an array (object dtype).  B is also object dtype, but contains arrays.  That's how loadmat handles MATLAB cells.

MATLAB struct could also be implemented as custom class with attributes A and B, or as a dictionary with those keys.

I know numpy better than pandas, but lets try to put this array into a dataframe:

```<code>In [28]: import pandas as pd
In [29]: df = pd.DataFrame(res['data'])
In [30]: df
Out[30]:
   A                B
0  1  [2.0, 3.0, 4.0]
1  2  [3.0, 4.0, 5.0]
2  3  [4.0, 5.0, 6.0]
3  4  [5.0, 6.0, 7.0]
4  5  [6.0, 7.0, 8.0]
In [31]: df.dtypes
Out[31]:
A    object
B    object
dtype: object
</code>```

In numpy the fields could be cleaned up and assigned to variables:

```<code>In [37]: A = res['data']['A'].astype(int)
In [38]: B = np.stack(res['data']['B'])
In [39]: A
Out[39]: array([1, 2, 3, 4, 5])
In [40]: B
Out[40]:
array([[ 2.,  3.,  4.],
       [ 3.,  4.,  5.],
       [ 4.,  5.,  6.],
       [ 5.,  6.,  7.],
       [ 6.,  7.,  8.]])
</code>```

One is a (5,) shape array, the other (5,3).

I could pack those back into a structured array with a prettier dtype:

```<code>In [48]: C = np.empty((5,), [('A',int), ('B', int, (3,))])
In [49]: C['A'] = A
In [50]: C['B'] = B
In [51]: C
Out[51]:
array([(1, [2, 3, 4]), (2, [3, 4, 5]), (3, [4, 5, 6]), (4, [5, 6, 7]),
       (5, [6, 7, 8])],
      dtype=[('A', '<i4'), ('B', '<i4', (3,))])
</code>```

Body:
Good morning
   I have thoroughly looked around to try figuring out a way to create a
   matlab like struct array in python. My input .csv file is header less

My matlab code

  dumpdata = csvread('dumpdata.csv');
  N_dumpdata_samples = length(dumpdata);

  rec_sample_1second = struct('UTC_time',{},'sv_id_set',{},'pseudorange',
  {},'state',{});

  for s=1:1:N_dumpdata_samples

    rec_sample_1second(s).UTC_time = dumpdata(s,1);
   rec_sample_1second(s).UTC_time = round(rec_sample_1second(s).
   UTC_time * 10);
   rec_sample_1second(s).UTC_time = rec_sample_1second(s).
   UTC_time / 10;

   for t=1:1:15

       rec_sample_1second(s).sv_id_set(t) = dumpdata(s,t+1);
       rec_sample_1second(s).pseudorange(t) = dumpdata(s,t+16);
       rec_sample_1second(s).state(t) = dumpdata(s,t+31);
       end;
    end;

Trying to implement in python

   import numpy as np
   import pandas as pd

   df = pd.read_csv('path'/Dumpdata.csv',header=None)
   N_dumpdata_samples=len(df)
   structure={}
   structure["parent1"] = {}
  UTC_time=[]
  for s in range(N_dumpdata_samples):
      # structure['parent1']['UTC_time']=df[s,0] -> this line give error
      UTC_time=df['s',0]
  .......

My question is : How can I implement same logic and structure in python.

Thanks

Body:
In Octave:

>> data = struct('A',{}, 'B', {});
>> for s=1:1;5
       data(s).A = s
       for t=1:1:3
           data(s).B(t) = s+t
       end;
   end;

producing

>> data.A
ans =  1
ans =  2
ans =  3
ans =  4
ans =  5
>> data.B
ans =
   2   3   4
ans =
   3   4   5
ans =
   4   5   6
ans =
   5   6   7
ans =
   6   7   8
>> save -7 stack47277436.mat data

Loading that in numpy with the scipy.io.loadmat:

In [17]: res = loadmat('stack47277436.mat')
In [18]: res
Out[18]:
{'__globals__': [],
 '__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.0.0, 2017-11-14 04:48:21 UTC',
 '__version__': '1.0',
 'data': array([[(array([[ 1.]]), array([[ 2.,  3.,  4.]])),
         (array([[ 2.]]), array([[ 3.,  4.,  5.]])),
         (array([[ 3.]]), array([[ 4.,  5.,  6.]])),
         (array([[ 4.]]), array([[ 5.,  6.,  7.]])),
         (array([[ 5.]]), array([[ 6.,  7.,  8.]]))]],
       dtype=[('A', 'O'), ('B', 'O')])}

Or load with squeeze_me to remove the singular dimensions

In [22]: res = loadmat('stack47277436.mat',squeeze_me=True)
In [24]: res['data']
Out[24]:
array([(1.0, array([ 2.,  3.,  4.])), (2.0, array([ 3.,  4.,  5.])),
       (3.0, array([ 4.,  5.,  6.])), (4.0, array([ 5.,  6.,  7.])),
       (5.0, array([ 6.,  7.,  8.]))],
      dtype=[('A', 'O'), ('B', 'O')])
In [25]: _.shape
Out[25]: (5,)

The struct has been translated into a structured array with 2 fields, corresponding to the struct fields (is that the MATLAB name?)

In [26]: res['data']['A']
Out[26]: array([1.0, 2.0, 3.0, 4.0, 5.0], dtype=object)
In [27]: res['data']['B']
Out[27]:
array([array([ 2.,  3.,  4.]), array([ 3.,  4.,  5.]),
       array([ 4.,  5.,  6.]), array([ 5.,  6.,  7.]),
       array([ 6.,  7.,  8.])], dtype=object)

A is an array (object dtype).  B is also object dtype, but contains arrays.  That's how loadmat handles MATLAB cells.

MATLAB struct could also be implemented as custom class with attributes A and B, or as a dictionary with those keys.

I know numpy better than pandas, but lets try to put this array into a dataframe:

In [28]: import pandas as pd
In [29]: df = pd.DataFrame(res['data'])
In [30]: df
Out[30]:
   A                B
0  1  [2.0, 3.0, 4.0]
1  2  [3.0, 4.0, 5.0]
2  3  [4.0, 5.0, 6.0]
3  4  [5.0, 6.0, 7.0]
4  5  [6.0, 7.0, 8.0]
In [31]: df.dtypes
Out[31]:
A    object
B    object
dtype: object

In numpy the fields could be cleaned up and assigned to variables:

In [37]: A = res['data']['A'].astype(int)
In [38]: B = np.stack(res['data']['B'])
In [39]: A
Out[39]: array([1, 2, 3, 4, 5])
In [40]: B
Out[40]:
array([[ 2.,  3.,  4.],
       [ 3.,  4.,  5.],
       [ 4.,  5.,  6.],
       [ 5.,  6.,  7.],
       [ 6.,  7.,  8.]])

One is a (5,) shape array, the other (5,3).

I could pack those back into a structured array with a prettier dtype:

In [48]: C = np.empty((5,), [('A',int), ('B', int, (3,))])
In [49]: C['A'] = A
In [50]: C['B'] = B
In [51]: C
Out[51]:
array([(1, [2, 3, 4]), (2, [3, 4, 5]), (3, [4, 5, 6]), (4, [5, 6, 7]),
       (5, [6, 7, 8])],
      dtype=[('A', '<i4'), ('B', '<i4', (3,))])


问:
Putting current time into label
Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.</p>

```<code>NSDate *StrDate = [NSDate date];
        NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
        [Dateformat setDateFormat:@"DD-MM-YYYY"];
        NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
        [UserCntrl.timeDisplay setText:DateStr];
        [Dateformat setDateFormat:@"HH:MM"];
        NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];
</code>```

答: [NSDate date] makes a date object of the time you call it. You must call it again to update the date. In other words, you must do StrDate = [NSDate date]; whenever you want to get the current date in your method.</p>

Title: Putting current time into label

Body:
Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.

NSDate *StrDate = [NSDate date];
        NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
        [Dateformat setDateFormat:@"DD-MM-YYYY"];
        NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
        [UserCntrl.timeDisplay setText:DateStr];
        [Dateformat setDateFormat:@"HH:MM"];
        NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];


问:
ES6 spread elements vs nested forEach performance
I have the following function

```<code>const modules = [{courses:[...]},{courses:[...]},...]
const deleteCourses = [];
modules.forEach((mod) => {
    mod.courses.forEach((course) => {
        deleteCourses.push(course));
    }
    // versus
    deleteCourses = [...deleteCourses, ...mod.courses];
});
</code>```

Assuming modules and courses to have between 30-100 length I was wondering which one of those is more efficient?

On the one hand I was taught to avoid nesting forEach loops. In the other hand array literal creates a new Array instance each time.

Thanks!

答:
It would seem that nested forEach is very much faster, as this jsPerf shows:

Setup:

```<code>const modules = Array(30).fill({courses:Array(30).fill(1)}) //30x30 elements
let deleteCourses = [];
</code>```

Case 1: nested forEach - 29,293 ops/sec

```<code>modules.forEach((mod) => {
    mod.courses.forEach((course) => {
        deleteCourses.push(course);
    })
})
</code>```

Case 2: ES6 Spread Operator - 49.13 ops/sec

```<code>modules.forEach((mod) => {
    deleteCourses = [...deleteCourses, ...mod.courses];
})
</code>```

That's about 600x faster for that 30x30 sample

This makes sense when you consider the amount of redundancy in respreading deleteCourses on every iteration. In contrast to nested forEach, the number of addition operations performed per iteration is about the length of deleteCourses for that iteration. That number is also growing on every iteration.

So the difference in performance has little to do with the creation of new Array instances, and much to do with the multitude of redundant steps created by this misusage of the spread operator.

To be sure, looking at the two cases individually, we can see that:

the ES6 Spread Operator algorithm is exponential: O(2^n)

the nested forEach algorithm is linear: O(n)

Body:
I have the following function

const modules = [{courses:[...]},{courses:[...]},...]
const deleteCourses = [];
modules.forEach((mod) => {
    mod.courses.forEach((course) => {
        deleteCourses.push(course));
    }
    // versus
    deleteCourses = [...deleteCourses, ...mod.courses];
});

Assuming modules and courses to have between 30-100 length I was wondering which one of those is more efficient?

On the one hand I was taught to avoid nesting forEach loops. In the other hand array literal creates a new Array instance each time.

Thanks!

Body:
It would seem that nested forEach is very much faster, as this jsPerf shows:

Setup:

const modules = Array(30).fill({courses:Array(30).fill(1)}) //30x30 elements
let deleteCourses = [];

Case 1: nested forEach - 29,293 ops/sec

modules.forEach((mod) => {
    mod.courses.forEach((course) => {
        deleteCourses.push(course);
    })
})

Case 2: ES6 Spread Operator - 49.13 ops/sec

modules.forEach((mod) => {
    deleteCourses = [...deleteCourses, ...mod.courses];
})

That's about 600x faster for that 30x30 sample

This makes sense when you consider the amount of redundancy in respreading deleteCourses on every iteration. In contrast to nested forEach, the number of addition operations performed per iteration is about the length of deleteCourses for that iteration. That number is also growing on every iteration.

So the difference in performance has little to do with the creation of new Array instances, and much to do with the multitude of redundant steps created by this misusage of the spread operator.

To be sure, looking at the two cases individually, we can see that:

the ES6 Spread Operator algorithm is exponential: O(2^n)

the nested forEach algorithm is linear: O(n)


问:
AWS SQS sender setting a time for message to be avilable for the consumer
I have seen an option called visibility timeout in AWS SQS which sets a time for other consumers to ignore the message which is being processed by one.
Is there an option to set a time before the message actually becomes available for consumers to use it, may be set while message actually is inserted into Queue

答:
Found an option called Amazon SQS Message Timers
Amazon SQS message timers allow you to specify an initial invisibility period for a message that you add to a queue. For example, if you send a message with the DelaySeconds parameter set to 45, the message isn't visible to consumers for the first 45 seconds during which the message stays in the queue.
The default value for DelaySeconds is 0.

To set a delay period that applies to all messages in a queue, use delay queues. A message timer setting for an individual message overrides any DelaySeconds value that applies to the entire delay queue.

For more info on SQS check  this  detailed PDF by AWS


问:
Passing value as key in Firebase database rule
I have a database where family has members.

Family member database.

```<code>// Family 1 has user 1, user 2, user 3.
// Family 2 has user 4, user 5.
// family_id_x is uniquely generated by firebase.
// uid is uniquely generated by firebase on registration. (auth.uid)
// database 'family-member'
'family-member':[
  'family_id_1': 'uid_1',
  'family_id_1': 'uid_2',
  'family_id_1': 'uid_3'
  'family_id_2': 'uid_4'
  'family_id_2': 'uid_5'
]
</code>```

Furniture database

```<code>// A family member can create furniture for the family.
// database 'furniture'
'furniture':[
  'furniture_id_1': {
    'furnitureName': "Mahogany Dining Table",
    'familyKey': 'family_id_1'
  }
]
</code>```

So I created a database rule to see if the user is able to make a new furniture.
I've logged in with uid_1.
Then I tried the following.

```<code>// database rule for furniture.
"furniture": {
   ".write": "auth != null && (root.child('family-member').child(
   newData.child(familyKey).val() // Problem!
   ).child(auth.uid).exists())
}
</code>```

This fails. I suspected the underlined part is the cause. So I hard coded.

```<code>"furniture": {
   ".write": "auth != null && (root.child('family-member').child(
   'family_id_1' // HardCode! Now works.
   ).child(auth.uid).exists())
}
</code>```

It works.

Please let me know what I should do in order to solve this problem.

Edit: product => furniture, Miscellaneous syntax errors

答:
Correct me if I am wrong (I may not fully understand what you are asking but would this work):

```<code>"product": {
   "$familyKey": {
      ".write": "auth != null && (root.child('family-member').child(
      newData.child(familyKey).val() // Problem!
      ).child(auth.uid).exists())
   }
}
</code>```

This is specifying a variable (a wild card) which you might want to make an == type of comparison such as the path you are trying to get might always exist.

```<code>"root.child('family-member').child($familyKey).val() == family_id_1"
</code>```

Body:
I have a database where family has members.

Family member database.

// Family 1 has user 1, user 2, user 3.
// Family 2 has user 4, user 5.
// family_id_x is uniquely generated by firebase.
// uid is uniquely generated by firebase on registration. (auth.uid)
// database 'family-member'
'family-member':[
  'family_id_1': 'uid_1',
  'family_id_1': 'uid_2',
  'family_id_1': 'uid_3'
  'family_id_2': 'uid_4'
  'family_id_2': 'uid_5'
]

Furniture database

// A family member can create furniture for the family.
// database 'furniture'
'furniture':[
  'furniture_id_1': {
    'furnitureName': "Mahogany Dining Table",
    'familyKey': 'family_id_1'
  }
]

So I created a database rule to see if the user is able to make a new furniture.
I've logged in with uid_1.
Then I tried the following.

// database rule for furniture.
"furniture": {
   ".write": "auth != null && (root.child('family-member').child(
   newData.child(familyKey).val() // Problem!
   ).child(auth.uid).exists())
}

This fails. I suspected the underlined part is the cause. So I hard coded.

"furniture": {
   ".write": "auth != null && (root.child('family-member').child(
   'family_id_1' // HardCode! Now works.
   ).child(auth.uid).exists())
}

It works.

Please let me know what I should do in order to solve this problem.

Edit: product => furniture, Miscellaneous syntax errors

Body:
Correct me if I am wrong (I may not fully understand what you are asking but would this work):

"product": {
   "$familyKey": {
      ".write": "auth != null && (root.child('family-member').child(
      newData.child(familyKey).val() // Problem!
      ).child(auth.uid).exists())
   }
}

This is specifying a variable (a wild card) which you might want to make an == type of comparison such as the path you are trying to get might always exist.

"root.child('family-member').child($familyKey).val() == family_id_1"


问:
Gnuplot 4d map colorbar with different transparency based on data
I am trying to plot 4d plot using splot (x y z value). I would like to have 4th column shown as heat color. Up to this point, I am fine. What I can't figure out, after searching answers online, is to have the color of the dots being transparent but with different transparency based on their value.

For example, let's say I have the following data set:

```<code>0 0 0 0.1
0 0 1 0.2

0 1 0 0.2
0 1 1 2

1 0 0 1
1 0 1 3

1 1 0 0.5
1 1 1 4
</code>```

Now, I want to make the colorbar (for the 4th column) to be as such: the closer the 4th column value is to 1, the more transparent the dot/point in the figure it will be. All the places I've look can only give me uniform transparency for the entire colorbar.

I wonder if anyone has dealt with this before, or has an idea how to do this.
Thank you very much!

答:
I did not fully understand how you want the transparency to depend on the value, so I will give a general answer, where you can substitute the transparency function for your own.

While you can specify transparency for line colors, this appears to not be possible when using palette, which would be the most straightforward way to achieve what you want. The furthest you can go with only using gnuplot is to make the colors appear transparent, as in the following script, where in.data is a file with your sample data.

```<code>#!/usr/bin/env gnuplot

set term pngcairo
in_data = "in.data"
set out "out.png"

# function to combine color and alpha channels with white background
# 0: no transparency, 1: fully transparent
make_transparent(x1, t) = (1-t)*x1 + t

# a function to decide transparency
# the input and output must be in range of [0,1]
#get_transparency(x1) = 0      # no transparency
#get_transparency(x1) = 1      # fully transparent
get_transparency(x1) = 1 - x1  # smaller values are more transparent

# convenience function to truncate values
minval(x1, x2) = x1<x2?x1:x2
maxval(x1, x2) = x1>x2?x1:x2
truncval(x1, xmin, xmax) = maxval(minval(x1, xmax), xmin)
trunc(x1) = truncval(x1, 0, 1)

# the default palette consists of rgbfunctions 7,5,15
# we redefine their transparency enabled versions here
# the input and output must be in range of [0,1]
# see other formulae with "show palette rgbformulae" command in gnuplot
f7(x1)  = make_transparent(sqrt(x1)           , get_transparency(x1))
f5(x1)  = make_transparent(x1**3              , get_transparency(x1))
f15(x1) = make_transparent(trunc(sin(2*pi*x1)), get_transparency(x1))

set palette model RGB functions f7(gray),f5(gray),f15(gray)

splot in_data palette
</code>```

This script assumes that the background is white, but can be adapted to any other solid background.  It falls apart once the points start overlapping however.

To get real transparency, you would need to plot each data point as a separate line and give it a distinct line color. This could be achieved by pre-processing the data, as in the following bash script.

```<code>#!/usr/bin/env bash

set -eu

in_data="in.data"
out_png="out.png"

pi=3.141592653589793

# function to convert data value into rgba value
function value2rgba()
{
  # arguments to function
  local val="${1}"
  local min="${2}"
  local max="${3}"

  # normalized value
  local nval=$( bc -l <<< "(${val}-${min})/(${max}-${min})" )

  #### alpha channel value ####
  local alpha="$( bc -l <<< "255 * (1-${nval})" )"
  # round to decimal
  alpha=$( printf "%0.f" "${alpha}" )

  #### red channel value ####
  # rgbformulae 7 in gnuplot
  local red="$( bc -l <<< "255 * sqrt(${nval})" )"
  # round to decimal
  red=$( printf "%0.f" "${red}" )

  #### green channel value ####
  # rgbformulae 5 in gnuplot
  local red="$( bc -l <<< "255 * sqrt(${nval})" )"
  local green="$( bc -l <<< "255 * ${nval}^3" )"
  # round to decimal
  green=$( printf "%0.f" "${green}" )

  #### blue channel value ####
  # rgbformulae 15 in gnuplot
  local blue="$( bc -l <<< "255 * s(2*${pi}*${nval})" )"
  # round to decimal
  blue=$( printf "%0.f" "${blue}" )
  # make sure blue is positive
  if (( blue < 0 ))
  then
    blue=0
  fi

  ### whole rgba value
  local rgba="#"
  rgba+="$( printf "%02x" "${alpha}" )"
  rgba+="$( printf "%02x" "${red}" )"
  rgba+="$( printf "%02x" "${green}" )"
  rgba+="$( printf "%02x" "${blue}" )"

  echo "${rgba}"

}

# data without blank lines
data="$( sed -E  "/^[[:space:]]*$/d" "${in_data}" )"

# number of lines
nline=$( wc -l <<< "${data}" )

# get the minimum and maximum value of the 4-th column
min_max=( $( awk '{ print $4 }' <<< "${data}" | sort -g | sed -n '1p;$p' ) )

# array of colors for each point
colors=()
while read -r line
do
  colors+=( $( value2rgba "${line}" "${min_max[@]}" ) )
done < <( awk '{ print $4 }' <<< "${data}" )

# gather coordinates into one row
coords=( $( awk '{ print $1,$2,$3 }' <<< "${data}" ) )

gnuplot << EOF

set term pngcairo

set out "${out_png}"

\$DATA << EOD
${coords[@]}
EOD

nline=${nline}
colors="${colors[@]}"

unset key

splot for [i=0:nline-1] \$DATA \
  u (column(3*i+1)):(column(3*i+2)):(column(3*i+3)) \
  pt 1 lc rgb word(colors, i+1)

EOF
</code>```

These scripts were tested with gnuplot 5.

Body:
I am trying to plot 4d plot using splot (x y z value). I would like to have 4th column shown as heat color. Up to this point, I am fine. What I can't figure out, after searching answers online, is to have the color of the dots being transparent but with different transparency based on their value.

For example, let's say I have the following data set:

0 0 0 0.1
0 0 1 0.2

0 1 0 0.2
0 1 1 2

1 0 0 1
1 0 1 3

1 1 0 0.5
1 1 1 4

Now, I want to make the colorbar (for the 4th column) to be as such: the closer the 4th column value is to 1, the more transparent the dot/point in the figure it will be. All the places I've look can only give me uniform transparency for the entire colorbar.

I wonder if anyone has dealt with this before, or has an idea how to do this.
Thank you very much!

Body:
I did not fully understand how you want the transparency to depend on the value, so I will give a general answer, where you can substitute the transparency function for your own.

While you can specify transparency for line colors, this appears to not be possible when using palette, which would be the most straightforward way to achieve what you want. The furthest you can go with only using gnuplot is to make the colors appear transparent, as in the following script, where in.data is a file with your sample data.

#!/usr/bin/env gnuplot

set term pngcairo
in_data = "in.data"
set out "out.png"

# function to combine color and alpha channels with white background
# 0: no transparency, 1: fully transparent
make_transparent(x1, t) = (1-t)*x1 + t

# a function to decide transparency
# the input and output must be in range of [0,1]
#get_transparency(x1) = 0      # no transparency
#get_transparency(x1) = 1      # fully transparent
get_transparency(x1) = 1 - x1  # smaller values are more transparent

# convenience function to truncate values
minval(x1, x2) = x1<x2?x1:x2
maxval(x1, x2) = x1>x2?x1:x2
truncval(x1, xmin, xmax) = maxval(minval(x1, xmax), xmin)
trunc(x1) = truncval(x1, 0, 1)

# the default palette consists of rgbfunctions 7,5,15
# we redefine their transparency enabled versions here
# the input and output must be in range of [0,1]
# see other formulae with "show palette rgbformulae" command in gnuplot
f7(x1)  = make_transparent(sqrt(x1)           , get_transparency(x1))
f5(x1)  = make_transparent(x1**3              , get_transparency(x1))
f15(x1) = make_transparent(trunc(sin(2*pi*x1)), get_transparency(x1))

set palette model RGB functions f7(gray),f5(gray),f15(gray)

splot in_data palette

This script assumes that the background is white, but can be adapted to any other solid background.  It falls apart once the points start overlapping however.

To get real transparency, you would need to plot each data point as a separate line and give it a distinct line color. This could be achieved by pre-processing the data, as in the following bash script.

#!/usr/bin/env bash

set -eu

in_data="in.data"
out_png="out.png"

pi=3.141592653589793

# function to convert data value into rgba value
function value2rgba()
{
  # arguments to function
  local val="${1}"
  local min="${2}"
  local max="${3}"

  # normalized value
  local nval=$( bc -l <<< "(${val}-${min})/(${max}-${min})" )

  #### alpha channel value ####
  local alpha="$( bc -l <<< "255 * (1-${nval})" )"
  # round to decimal
  alpha=$( printf "%0.f" "${alpha}" )

  #### red channel value ####
  # rgbformulae 7 in gnuplot
  local red="$( bc -l <<< "255 * sqrt(${nval})" )"
  # round to decimal
  red=$( printf "%0.f" "${red}" )

  #### green channel value ####
  # rgbformulae 5 in gnuplot
  local red="$( bc -l <<< "255 * sqrt(${nval})" )"
  local green="$( bc -l <<< "255 * ${nval}^3" )"
  # round to decimal
  green=$( printf "%0.f" "${green}" )

  #### blue channel value ####
  # rgbformulae 15 in gnuplot
  local blue="$( bc -l <<< "255 * s(2*${pi}*${nval})" )"
  # round to decimal
  blue=$( printf "%0.f" "${blue}" )
  # make sure blue is positive
  if (( blue < 0 ))
  then
    blue=0
  fi

  ### whole rgba value
  local rgba="#"
  rgba+="$( printf "%02x" "${alpha}" )"
  rgba+="$( printf "%02x" "${red}" )"
  rgba+="$( printf "%02x" "${green}" )"
  rgba+="$( printf "%02x" "${blue}" )"

  echo "${rgba}"

}

# data without blank lines
data="$( sed -E  "/^[[:space:]]*$/d" "${in_data}" )"

# number of lines
nline=$( wc -l <<< "${data}" )

# get the minimum and maximum value of the 4-th column
min_max=( $( awk '{ print $4 }' <<< "${data}" | sort -g | sed -n '1p;$p' ) )

# array of colors for each point
colors=()
while read -r line
do
  colors+=( $( value2rgba "${line}" "${min_max[@]}" ) )
done < <( awk '{ print $4 }' <<< "${data}" )

# gather coordinates into one row
coords=( $( awk '{ print $1,$2,$3 }' <<< "${data}" ) )

gnuplot << EOF

set term pngcairo

set out "${out_png}"

\$DATA << EOD
${coords[@]}
EOD

nline=${nline}
colors="${colors[@]}"

unset key

splot for [i=0:nline-1] \$DATA \
  u (column(3*i+1)):(column(3*i+2)):(column(3*i+3)) \
  pt 1 lc rgb word(colors, i+1)

EOF

These scripts were tested with gnuplot 5.


问:
Break out a loop from within a (yielded) block inside the loop
```<code>jobs.each do |job|
  msg job.name do
    break if stop_all_jobs?
    job.run!
  end
end

def msg(msg, &block)
  puts 'START ' + msg
  yield
  puts 'END ' + msg
end
</code>```

In the above example break does not break out of the loop as expected. It only breaks out of the msg code block.

This seems a little odd, but I guess it is based on context, that said, how do I break out of the loop from code which is within a yielded code block?

答: Use next instead of break.

Body:
jobs.each do |job|
  msg job.name do
    break if stop_all_jobs?
    job.run!
  end
end

def msg(msg, &block)
  puts 'START ' + msg
  yield
  puts 'END ' + msg
end

In the above example break does not break out of the loop as expected. It only breaks out of the msg code block.

This seems a little odd, but I guess it is based on context, that said, how do I break out of the loop from code which is within a yielded code block?

Body: Use next instead of break.