问:
Assigning a value to all imported data from CSV in Rails 5
I am relatively new to rails development and would appreciate some guidance.

I have an application where I am importing data from a CSV file. My goal is to assign a value to the imported CSV (Move ID) to group all the imported data.

For example (what I currently have working). I have a group of employees needing to move to a new location, I have a table called Move which has_many employee_moves (another table). I have a collection_select where I can pick from Move_IDs that exist. I can also import a CSV file where I am assigning each row to my existing Employee_Move table.

I would like, if possible, to be able to select a Move_ID, select my CSV file to import and associate each record from the CSV file to my selected Move_ID. Essentially assigning that CSV of employees moving to a specific move.

I am able to assign these values manually one at a time once imported in a edit view using a partial I have created.

```<code><%= render 'form' %>
</code>```

I hope that this is all making sense...

I have been trying to solve this for a while now so please excuse (and feel free to point out) any redundant code that may be remaining from my previous attempts.

EmployeeMove Model

```<code>  require 'csv'

  attr_accessor :move

  belongs_to :move, optional: true
  belongs_to :location, optional: true

  def self.import(file)
    CSV.foreach(file.path, headers: false) do |row|
      EmployeeMove.create!({
        :person => row[1],
        :from_building => row[2],
        :from_floor => row[3],
        :from_room => row[4],
        :to_building => row[5],
        :to_floor => row[6],
        :to_room => row[7],
        :notes => row[8],
        :move_id => move.id   <-- I know this is my problem.
        })
    end
  end
</code>```

EmployeeMovesController

```<code>class EmployeeMovesController < ApplicationController

  def index
    @employee_moves = EmployeeMove.all
  end

  def new
    @employee_move = EmployeeMove.new
  end

  def create
    @employee_move = EmployeeMove.new(employee_move_params)
    if @employee_move.save
      flash[:notice] = "Employee Move successfully added"
      redirect_to employee_move_path(@employee_move)
    else
      render 'new'
    end
  end

  def show
    @employee_move = EmployeeMove.find(params[:id])
  end

  def edit
    @employee_move = EmployeeMove.find(params[:id])
  end

  def update
    @employee_move = EmployeeMove.find(params[:id])
    if @employee_move.update(employee_move_params)
      flash[:notice] = "Emplyee Move successfully updated"
      redirect_to employee_move_path(@employee_move)
    else
      render 'edit'
    end
  end

  def import
    EmployeeMove.import(params[:file])
    redirect_to employee_moves_path, notice: "CSV Imported."
  end

  private
  def employee_move_params
    params.require(:employee_move).permit(:id, :person, :from_building, :from_floor, :from_room, :to_building, :to_floor, :to_room, :comments, :notes,
                                          :Complete, :move_id, :location_id)
  end

end
</code>```

My Collection_Select

Currently located in the new and edit pages of Employee Move, also using a _form partial.

```<code><%= form_for @employee_move do |f| %>

<p>
  <%= f.label :Move_ID %>&nbsp
  <%= collection_select(:employee_move, :move_id, Move.all, :id, :id, { :prompt => true }, { :multiple => false} ) %>
</p>
<p>
  <%= f.label :employee_move_name %>&nbsp
  <%= f.text_field :person %>
</p>
<p>
  <%= f.label :From_Building %>&nbsp
  <%= f.text_field :from_building %>
</p>
<p>
  <%= f.label :From_Floor %>&nbsp
  <%= f.text_field :from_floor %>
</p>
<p>
  <%= f.label :From_Room %>&nbsp
  <%= f.text_field :from_room %>
</p>
<p>
  <%= f.label :To_Building %>&nbsp
  <%= f.text_field :to_building %>
</p>
<p>
  <%= f.label :To_Floor %>&nbsp
  <%= f.text_field :to_floor %>
</p>
<p>
  <%= f.label :To_Room %>&nbsp
  <%= f.text_field :to_room %>
</p>
<p>
  <%= f.label :Comment %>&nbsp
  <%= f.text_field :comments %>
</p>
<p>
  <%= f.label :Note %>&nbsp
  <%= f.text_field :notes %>
</p>
<p>
  <%= f.submit %>
</p>

<% end %>
</code>```

A thought while writing this, I would prefer for my CSV import to be located in my Move show page (not meaning Employee Move show page). I currently have a Move index page where I can select from a list of created moves. Selecting a move from this list I can see the move details followed by a table populated with every Employee part of that move. This is currently working, but like I stated before, only if I manually assign the Move_ID to an employee after the CSV file has been imported.

=======================================================

Update

Thanks Simple Lime for the help thus far. The following are the suggested changes. As I mention in my comment below, I get a "undefined method 'import' for # <Move:0x00000004388a20>" currently. These are the changes I have made since my original post.

Import Method

I have moved my import method from my EmployeeMoveController to my MoveController.

```<code>  def import
    @move = Move.find(params[:move_id])
    @move.import(params[:file])
    redirect_to moves_path(@move), notice: "CSV Imported."
  end
</code>```

Rake Routes

```<code>  import_moves POST   /moves/import(.:format)            moves#import
   move_import GET    /moves/:move_id/import(.:format)   moves#import
</code>```

I manually added the second route "move_import", but since the original (import_moves) also points to the same Controller#Action, maybe there is some form of conflict happening here? I'm not sure.

The following code in my Move show page correctly directs me to the correct URL, /moves/1/import.

```<code><%= link_to "Add Employees to Move", move_import_path(@move.id) %>
</code>```

Employee Move Model

I have removed the :move_id => move.id.

```<code>class EmployeeMove < ActiveRecord::Base
  require 'csv'

   attr_accessor :move

  belongs_to :move, optional: true
  belongs_to :location, optional: true

  def self.import(file)
    CSV.foreach(file.path, headers: false) do |row|
      self.employee_moves.create!({
        :person => row[1],
        :from_building => row[2],
        :from_floor => row[3],
        :from_room => row[4],
        :to_building => row[5],
        :to_floor => row[6],
        :to_room => row[7],
        :notes => row[8]
        })
    end
  end
end
</code>```

Import View (html)

My import.html.erb file is located in /views/employee_moves.

```<code><div class="col-md-6">
  <div class="panel panel-default ">
    <div class="panel-body">
      <h1>move</h1>
        <h1>Move</h1>
      <p>
        Move ID:
        <%= @move.id if @move%>
      </p>

      <%= form_tag import_employee_moves_path, multipart: true do %>
        <%= file_field_tag :file %>
        <%= submit_tag "Import" %>
      <% end %>

      <%= link_to "All Moves", moves_path %>
    </div>
  </div>
</div>
</code>```

I hope that this update explains well enough the current state of my problem. Please let me know if anymore information would be required.

Again! Thank you for all the help and patience with my learning.

============================================================

Final Changes that got this working me for me

I moved my self.import from my Employee_Move model to my Move model and removed self, making it an instance method.

I changed the get 'import' in my routes.rb to post 'import'

Hope this is of help to anyone with the problem I've had. Thanks again to Simple Lime for all the help!

答:
So, assuming I understand everything correctly, you have a 2 models Move and EmployeeMove. You want to be able to upload a CSV from the Move show page and parse that CSV, creating an EmployeeMove record for each row in the CSV and the Move whose page you are currently on.

To do this, I would first move EmployeeMove.import into Move#import (so, an instance method on the Move model instead of a class method on EmployeeMove). Then, since you mention Move has_many employee_moves, instead of EmployeeMove.create!({...}), you can do

```<code>self.employee_moves.create!({...})
</code>```

and not need the :move_id => move.id line in the create anymore

Lastly, move the import method from the EmployeeMovesController into MovesController and change the route in config/routes.rb to look more like /moves/:id/import (the only important part here is that it goes to the MovesController and has an :id for which move it's importing to. Then your import method on the controller should look something like

```<code>def import
  @move = Move.find(params[:id])
  @move.import(params[:file]) # been a while since I've done a file upload, but I assume params[:file] is working here
  redirect_to moves_path(@move) # or wherever you'd like to send them
end
</code>```

and that should do it for ya. Let me know if I misunderstood your problem or you want something clarified further.

ContentLicense: CC BY-SA 4.0

Body:
I am relatively new to rails development and would appreciate some guidance.

I have an application where I am importing data from a CSV file. My goal is to assign a value to the imported CSV (Move ID) to group all the imported data.

For example (what I currently have working). I have a group of employees needing to move to a new location, I have a table called Move which has_many employee_moves (another table). I have a collection_select where I can pick from Move_IDs that exist. I can also import a CSV file where I am assigning each row to my existing Employee_Move table.

I would like, if possible, to be able to select a Move_ID, select my CSV file to import and associate each record from the CSV file to my selected Move_ID. Essentially assigning that CSV of employees moving to a specific move.

I am able to assign these values manually one at a time once imported in a edit view using a partial I have created.

<%= render 'form' %>

I hope that this is all making sense...

I have been trying to solve this for a while now so please excuse (and feel free to point out) any redundant code that may be remaining from my previous attempts.

EmployeeMove Model

  require 'csv'

  attr_accessor :move

  belongs_to :move, optional: true
  belongs_to :location, optional: true

  def self.import(file)
    CSV.foreach(file.path, headers: false) do |row|
      EmployeeMove.create!({
        :person => row[1],
        :from_building => row[2],
        :from_floor => row[3],
        :from_room => row[4],
        :to_building => row[5],
        :to_floor => row[6],
        :to_room => row[7],
        :notes => row[8],
        :move_id => move.id   <-- I know this is my problem.
        })
    end
  end

EmployeeMovesController

class EmployeeMovesController < ApplicationController

  def index
    @employee_moves = EmployeeMove.all
  end

  def new
    @employee_move = EmployeeMove.new
  end

  def create
    @employee_move = EmployeeMove.new(employee_move_params)
    if @employee_move.save
      flash[:notice] = "Employee Move successfully added"
      redirect_to employee_move_path(@employee_move)
    else
      render 'new'
    end
  end

  def show
    @employee_move = EmployeeMove.find(params[:id])
  end

  def edit
    @employee_move = EmployeeMove.find(params[:id])
  end

  def update
    @employee_move = EmployeeMove.find(params[:id])
    if @employee_move.update(employee_move_params)
      flash[:notice] = "Emplyee Move successfully updated"
      redirect_to employee_move_path(@employee_move)
    else
      render 'edit'
    end
  end

  def import
    EmployeeMove.import(params[:file])
    redirect_to employee_moves_path, notice: "CSV Imported."
  end

  private
  def employee_move_params
    params.require(:employee_move).permit(:id, :person, :from_building, :from_floor, :from_room, :to_building, :to_floor, :to_room, :comments, :notes,
                                          :Complete, :move_id, :location_id)
  end

end

My Collection_Select

Currently located in the new and edit pages of Employee Move, also using a _form partial.

<%= form_for @employee_move do |f| %>

  <%= f.label :Move_ID %>&nbsp
  <%= collection_select(:employee_move, :move_id, Move.all, :id, :id, { :prompt => true }, { :multiple => false} ) %>

  <%= f.label :employee_move_name %>&nbsp
  <%= f.text_field :person %>

  <%= f.label :From_Building %>&nbsp
  <%= f.text_field :from_building %>

  <%= f.label :From_Floor %>&nbsp
  <%= f.text_field :from_floor %>

  <%= f.label :From_Room %>&nbsp
  <%= f.text_field :from_room %>

  <%= f.label :To_Building %>&nbsp
  <%= f.text_field :to_building %>

  <%= f.label :To_Floor %>&nbsp
  <%= f.text_field :to_floor %>

  <%= f.label :To_Room %>&nbsp
  <%= f.text_field :to_room %>

  <%= f.label :Comment %>&nbsp
  <%= f.text_field :comments %>

  <%= f.label :Note %>&nbsp
  <%= f.text_field :notes %>

  <%= f.submit %>

<% end %>

A thought while writing this, I would prefer for my CSV import to be located in my Move show page (not meaning Employee Move show page). I currently have a Move index page where I can select from a list of created moves. Selecting a move from this list I can see the move details followed by a table populated with every Employee part of that move. This is currently working, but like I stated before, only if I manually assign the Move_ID to an employee after the CSV file has been imported.

=======================================================

Update

Thanks Simple Lime for the help thus far. The following are the suggested changes. As I mention in my comment below, I get a "undefined method 'import' for # <Move:0x00000004388a20>" currently. These are the changes I have made since my original post.

Import Method

I have moved my import method from my EmployeeMoveController to my MoveController.

  def import
    @move = Move.find(params[:move_id])
    @move.import(params[:file])
    redirect_to moves_path(@move), notice: "CSV Imported."
  end

Rake Routes

  import_moves POST   /moves/import(.:format)            moves#import
   move_import GET    /moves/:move_id/import(.:format)   moves#import

I manually added the second route "move_import", but since the original (import_moves) also points to the same Controller#Action, maybe there is some form of conflict happening here? I'm not sure.

The following code in my Move show page correctly directs me to the correct URL, /moves/1/import.

<%= link_to "Add Employees to Move", move_import_path(@move.id) %>

Employee Move Model

I have removed the :move_id => move.id.

class EmployeeMove < ActiveRecord::Base
  require 'csv'

   attr_accessor :move

  belongs_to :move, optional: true
  belongs_to :location, optional: true

  def self.import(file)
    CSV.foreach(file.path, headers: false) do |row|
      self.employee_moves.create!({
        :person => row[1],
        :from_building => row[2],
        :from_floor => row[3],
        :from_room => row[4],
        :to_building => row[5],
        :to_floor => row[6],
        :to_room => row[7],
        :notes => row[8]
        })
    end
  end
end

Import View (html)

My import.html.erb file is located in /views/employee_moves.

move

Move

        Move ID:
        <%= @move.id if @move%>

      <%= form_tag import_employee_moves_path, multipart: true do %>
        <%= file_field_tag :file %>
        <%= submit_tag "Import" %>
      <% end %>

      <%= link_to "All Moves", moves_path %>

I hope that this update explains well enough the current state of my problem. Please let me know if anymore information would be required.

Again! Thank you for all the help and patience with my learning.

============================================================

Final Changes that got this working me for me

I moved my self.import from my Employee_Move model to my Move model and removed self, making it an instance method.

I changed the get 'import' in my routes.rb to post 'import'

Hope this is of help to anyone with the problem I've had. Thanks again to Simple Lime for all the help!

Body:
So, assuming I understand everything correctly, you have a 2 models Move and EmployeeMove. You want to be able to upload a CSV from the Move show page and parse that CSV, creating an EmployeeMove record for each row in the CSV and the Move whose page you are currently on.

To do this, I would first move EmployeeMove.import into Move#import (so, an instance method on the Move model instead of a class method on EmployeeMove). Then, since you mention Move has_many employee_moves, instead of EmployeeMove.create!({...}), you can do

self.employee_moves.create!({...})

and not need the :move_id => move.id line in the create anymore

Lastly, move the import method from the EmployeeMovesController into MovesController and change the route in config/routes.rb to look more like /moves/:id/import (the only important part here is that it goes to the MovesController and has an :id for which move it's importing to. Then your import method on the controller should look something like

def import
  @move = Move.find(params[:id])
  @move.import(params[:file]) # been a while since I've done a file upload, but I assume params[:file] is working here
  redirect_to moves_path(@move) # or wherever you'd like to send them
end

and that should do it for ya. Let me know if I misunderstood your problem or you want something clarified further.


来源: stackexchange

问:
operators precedence in C
have a trouble understanding this expression:

```<code>(x + y - 1) / y * y
</code>```

The operators precedence is as follows (as per my understanding and K&R2, 2.12 table 2.1):

1) evaluate what is in the parens: firstly (x+y), then (x+y) -1

2) '*' operator has higher priority then '/' so it's supposed to go first, bit it appears  that (y * y)  is evaluated and then the result of (x+y-1) is divided by the product (y*y). I don't quite get it.

3) I ever heard that normally rounding up iw written in this form:

```<code>(x + y - 1) / y * y
</code>```

Is that correct? Thank you very much in advance!

答:
As mentioned earlier the "*" and "/" have the same precedence so they are evaluated left to right. Totally disambiguating the expression gives:</p>

```<code>( ( ( (x + y) - 1) / y) * y)
</code>```

ContentLicense: CC BY-SA 2.5

Title: operators precedence in C

Body:
have a trouble understanding this expression:

(x + y - 1) / y * y

The operators precedence is as follows (as per my understanding and K&R2, 2.12 table 2.1):

1) evaluate what is in the parens: firstly (x+y), then (x+y) -1

2) '*' operator has higher priority then '/' so it's supposed to go first, bit it appears  that (y * y)  is evaluated and then the result of (x+y-1) is divided by the product (y*y). I don't quite get it.

3) I ever heard that normally rounding up iw written in this form:

(x + y - 1) / y * y

Is that correct? Thank you very much in advance!

Body:
As mentioned earlier the "*" and "/" have the same precedence so they are evaluated left to right. Totally disambiguating the expression gives:

( ( ( (x + y) - 1) / y) * y)


问:
Elminating duplicate selection in two fields in Oracle
I have a table and I am doing inner join with the same table. Here is the table structure

```<code>Acct#|Name |Med_Rec|Admit Date
-----|-----|-------|----------
   1 |MIKE |100    |7/1/2017
   2 |MIKE |100    |7/2/2017
   3 |MIKE |100    |7/3/2017
   4 |CHRIS|101    |5/5/2017
   5 |CHRIS|101    |5/7/2017
</code>```

My goal is to get accounts with admit date within 3 consecutive days(i.e. Mike was admitted first on 7/1/2017 then next day was admitted again and the day after too). My goal result should be like this

```<code>Acct|Name |Admit_Date|Othr_Acct|Admit_Date
----|-----|----------|---------|-----------
   1|MIKE |7/1/2017  |    2    |7/2/2017
   1|MIKE |7/1/2017  |    3    |7/3/2017
   4|CHRIS|5/5/2017  |    5    |5/7/2017
</code>```

The issue I am facing is that I am getting my query results where Acct number is selected again. It should not appear again as I already listed it under "Othr_Acct"

```<code>Acct|Name |Admit_Date|Othr_Acct|Admit_Date
----|-----|----------|---------|-----------
   1|MIKE |7/1/2017  |    2    |7/2/2017
   1|MIKE |7/1/2017  |    3    |7/3/2017
   2|MIKE |7/2/2017  |    3    |7/3/2017<-wrong it was already selected
   4|CHRIS|5/5/2017  |    5    |5/7/2017

SELECT
A.Acct
A.Name
A.Admit_Date
B.Acct AS Othr_Acct
B.Admit_Date

FROM
A.TABLE
B.TABLE

WHERE

A.Med_Rec=B.Med_Rec
AND B.Admit_Date-A.Admit_Date BETWEEN 0 AND 2
AND A.Acct<>B.Acct
</code>```

答:
Join table B only to the first row from table A.

Use a subquery and row_number function to number rows in A

```<code>SELECT
    A.Acct,
    A.Name ,
    A.Admit_Date,
    B.Acct AS Othr_Acct,
    B.Admit_Date
FROM (
   SELECT t.*,
    row_number() over (partition by Med_Rec order by Admit_Date) As rn
   FROM TABLE1 t
) a
JOIN TABLE1 b
ON A.rn = 1 AND A.Med_Rec=B.Med_Rec
AND B.Admit_Date-A.Admit_Date BETWEEN 0 AND 2
AND A.Acct<>B.Acct
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table and I am doing inner join with the same table. Here is the table structure

Acct#|Name |Med_Rec|Admit Date
-----|-----|-------|----------
   1 |MIKE |100    |7/1/2017
   2 |MIKE |100    |7/2/2017
   3 |MIKE |100    |7/3/2017
   4 |CHRIS|101    |5/5/2017
   5 |CHRIS|101    |5/7/2017

My goal is to get accounts with admit date within 3 consecutive days(i.e. Mike was admitted first on 7/1/2017 then next day was admitted again and the day after too). My goal result should be like this

Acct|Name |Admit_Date|Othr_Acct|Admit_Date
----|-----|----------|---------|-----------
   1|MIKE |7/1/2017  |    2    |7/2/2017
   1|MIKE |7/1/2017  |    3    |7/3/2017
   4|CHRIS|5/5/2017  |    5    |5/7/2017

The issue I am facing is that I am getting my query results where Acct number is selected again. It should not appear again as I already listed it under "Othr_Acct"

Acct|Name |Admit_Date|Othr_Acct|Admit_Date
----|-----|----------|---------|-----------
   1|MIKE |7/1/2017  |    2    |7/2/2017
   1|MIKE |7/1/2017  |    3    |7/3/2017
   2|MIKE |7/2/2017  |    3    |7/3/2017<-wrong it was already selected
   4|CHRIS|5/5/2017  |    5    |5/7/2017

SELECT
A.Acct
A.Name
A.Admit_Date
B.Acct AS Othr_Acct
B.Admit_Date

FROM
A.TABLE
B.TABLE

WHERE

A.Med_Rec=B.Med_Rec
AND B.Admit_Date-A.Admit_Date BETWEEN 0 AND 2
AND A.Acct<>B.Acct

Body:
Join table B only to the first row from table A.

Use a subquery and row_number function to number rows in A

SELECT
    A.Acct,
    A.Name ,
    A.Admit_Date,
    B.Acct AS Othr_Acct,
    B.Admit_Date
FROM (
   SELECT t.*,
    row_number() over (partition by Med_Rec order by Admit_Date) As rn
   FROM TABLE1 t
) a
JOIN TABLE1 b
ON A.rn = 1 AND A.Med_Rec=B.Med_Rec
AND B.Admit_Date-A.Admit_Date BETWEEN 0 AND 2
AND A.Acct<>B.Acct


问:
Accurate (Music-grade) Timing of Audio Playback
I'm attempting to write an app that can arrange timed playback of some (mostly tiny) audio files. The catch: it needs to be timed with accuracy worthy of music. The sounds won't be played frequently (it's not, for example, a sampler or a drum kit), but they will need to be absolutely precisely placed. There are two parts to this question:

How should I organize the timing? I've heard NSTimer is inaccurate, or at least unreliable? Should I use MIDI somehow? Or a tight loop and some time-getting function with high resolution?

Once I've got the timing set up, and I know when to play my sounds... how should I play them? Is NSSound fast and reliable enough to maintain the accuracy needed?

答:
General Info On Music Quality Audio

This is something that needs to be shouted from the mountaintops to anybody making an instrument for iOS:

If you are using MIDI, you will wrestle much less with these issues (the sound renderer had to deal with much of this), but all instruments have to deal with these requirements:

What Musicians Expect

The first thing is to make the buffers used by AudioQueue as small as possible.  The default on iPad is 1024 samples, which is a painfully long 23 milliseconds.  When you want to play a sound, with that buffer size, it will take from 0 to 23 ms for a response, even if the computer is infinitely fast.  If the buffer is more than 256 samples long, you won't be able to do much of a real instrument with it.  In practice, also add as much as 30ms on top of that for overhead (from touch response to graphics, etc).

```<code>//   256 / ( 44.1khz) ~  5.8ms
float latency = 0.005; //in seconds gives a 256 sample buffer
//on an infinitely fast computer, we'd make sure we got a buffer of size 1.
// but it will take too much CPU. :-)  some latency is inevitable.
OSStatus status = AudioSessionSetProperty(
  kAudioSessionProperty_PreferredHardwareIOBufferDuration,
  sizeof(latency),&latency
);
</code>```

Latency - Pro musicians expect finger-to-ear latency to be about 8 milliseconds.  That seems like a fantasy on the iPad for me, but that's the goal.  Just for playing fast, think of 120 (quarternote) beats per minute and target 4x accuracy of 16th notes, etc.  Even when not playing fast, musicians are irritated by high latency, and will stop using an otherwise great instrument that goes above 100ms(!!!!) Anything above 30ms, they are unhappily going into pro-tools and time-shifting the recorded sound a few ms back to fix your screw-up.  The better apps on the store get to about 30ms.  Some really good ones are still OK at about 50ms.

Measure latency by placing a microphone on top of the surface of the ipad, and running it into the left channel of a mixer.  Then run the ipad out into the right channel.  Record the sound in stereo.  Then bring it up into a sound editor that lets you view stereo waveforms.  You can look at the time that the finger hit the touchscreen, then to the time that the electronic sound began.  That distance is latency.  The variance in it is jitter.

Jitter - Jitter is variance in latency.  Jitter of more than a few milliseconds makes rhythm sound wrong.  I got to about 5ms.  It's very directly tied to the AudioQueue buffer size.  Example with 1024 sample buffer: If you press your finger down at some random point in time that the buffer then the expectation is to be at sample 512 when you need to respond.  So it varies from 0 to 1024 ms minimum, but it's 512 on average... 12ms of waiting for the buffer to finish as an average case, before you add in latency from other sources.

Touch Latency - It's most important that touchesBegan get serviced as quickly as possible.  Even if that means that touchesMoved, touchesEnded, touchesCancelled take a little longer.  So, you might end up having some asymmetry in the workload to achieve this.  This was a confusing revelation to me at first, because the profiler was telling me that there wasn't much time being spent in touchesBegan, yet it can make a big difference to defer some work until the touch ended.

OpenGL - You should at least consider it.  I am not convinced that it is as easy to hit these latency goals when using UIKit directly, and used OpenGL on my main app.

Real-Time Clock - For things that aren't really instruments, but have stringent beat-sync requirements like drum machines, you could keep track of what time it really is and make the samples track to the clock and assume that there is drift when you aren't watching the clock.  But I got tired of fighting that battle on my older MIDI instruments ... if you have MIDI, then MIDI does clock signals; it might be the only thing that works to sync a couple of electronic instruments together.

Sound Skips - Everything that your app does competes for CPU time.  Given that you have made your sound engine as efficient as you can, making the buffers smaller uses more CPU.  You might have to trade a little latency for better continuity.  I have my bias, cut out eye-candy nonsense and live within your means if the sound engine will get more cycles back.

Timers.  Using CADisplayLink.  I haven't had to think about it much.  This is what I have.

```<code>- (NSInteger)animationFrameInterval
{
    return animationFrameInterval;
}

- (void)setAnimationFrameInterval:(NSInteger)frameInterval
{
    if (frameInterval >= 16)
    {
        animationFrameInterval = frameInterval;

        if (animating)
        {
            [self stopAnimation];
            [self startAnimation];
        }
    }
}

- (void)startAnimation
{
    if (!animating)
    {
      displayLink = [NSClassFromString(@"CADisplayLink")
            displayLinkWithTarget:self
            selector:@selector(drawView:)];
        [displayLink setFrameInterval:animationFrameInterval];
        [displayLink addToRunLoop:[NSRunLoop
              currentRunLoop]
            forMode:NSDefaultRunLoopMode];

        animating = TRUE;
    }
}

- (void)stopAnimation
{
    if (animating)
    {
      [displayLink invalidate];
      displayLink = nil;

        animating = FALSE;
    }
}
</code>```

I am not making this stuff up.  Please don't put up "music instruments" in the store until you are addressing these issues.  Jordan Rudess, Leon Gruenbaum, Chris Dudley and other pro musicians used to bring these issues up constantly when talking about iPad/iPhone apps.  The situation seems to have improved somewhat, but I don't think most developers know what numbers real musicians expect.

Body:
General Info On Music Quality Audio

This is something that needs to be shouted from the mountaintops to anybody making an instrument for iOS:

If you are using MIDI, you will wrestle much less with these issues (the sound renderer had to deal with much of this), but all instruments have to deal with these requirements:

What Musicians Expect

The first thing is to make the buffers used by AudioQueue as small as possible.  The default on iPad is 1024 samples, which is a painfully long 23 milliseconds.  When you want to play a sound, with that buffer size, it will take from 0 to 23 ms for a response, even if the computer is infinitely fast.  If the buffer is more than 256 samples long, you won't be able to do much of a real instrument with it.  In practice, also add as much as 30ms on top of that for overhead (from touch response to graphics, etc).

//   256 / ( 44.1khz) ~  5.8ms
float latency = 0.005; //in seconds gives a 256 sample buffer
//on an infinitely fast computer, we'd make sure we got a buffer of size 1.
// but it will take too much CPU. :-)  some latency is inevitable.
OSStatus status = AudioSessionSetProperty(
  kAudioSessionProperty_PreferredHardwareIOBufferDuration,
  sizeof(latency),&latency
);

Latency - Pro musicians expect finger-to-ear latency to be about 8 milliseconds.  That seems like a fantasy on the iPad for me, but that's the goal.  Just for playing fast, think of 120 (quarternote) beats per minute and target 4x accuracy of 16th notes, etc.  Even when not playing fast, musicians are irritated by high latency, and will stop using an otherwise great instrument that goes above 100ms(!!!!) Anything above 30ms, they are unhappily going into pro-tools and time-shifting the recorded sound a few ms back to fix your screw-up.  The better apps on the store get to about 30ms.  Some really good ones are still OK at about 50ms.

Measure latency by placing a microphone on top of the surface of the ipad, and running it into the left channel of a mixer.  Then run the ipad out into the right channel.  Record the sound in stereo.  Then bring it up into a sound editor that lets you view stereo waveforms.  You can look at the time that the finger hit the touchscreen, then to the time that the electronic sound began.  That distance is latency.  The variance in it is jitter.

Jitter - Jitter is variance in latency.  Jitter of more than a few milliseconds makes rhythm sound wrong.  I got to about 5ms.  It's very directly tied to the AudioQueue buffer size.  Example with 1024 sample buffer: If you press your finger down at some random point in time that the buffer then the expectation is to be at sample 512 when you need to respond.  So it varies from 0 to 1024 ms minimum, but it's 512 on average... 12ms of waiting for the buffer to finish as an average case, before you add in latency from other sources.

Touch Latency - It's most important that touchesBegan get serviced as quickly as possible.  Even if that means that touchesMoved, touchesEnded, touchesCancelled take a little longer.  So, you might end up having some asymmetry in the workload to achieve this.  This was a confusing revelation to me at first, because the profiler was telling me that there wasn't much time being spent in touchesBegan, yet it can make a big difference to defer some work until the touch ended.

OpenGL - You should at least consider it.  I am not convinced that it is as easy to hit these latency goals when using UIKit directly, and used OpenGL on my main app.

Real-Time Clock - For things that aren't really instruments, but have stringent beat-sync requirements like drum machines, you could keep track of what time it really is and make the samples track to the clock and assume that there is drift when you aren't watching the clock.  But I got tired of fighting that battle on my older MIDI instruments ... if you have MIDI, then MIDI does clock signals; it might be the only thing that works to sync a couple of electronic instruments together.

Sound Skips - Everything that your app does competes for CPU time.  Given that you have made your sound engine as efficient as you can, making the buffers smaller uses more CPU.  You might have to trade a little latency for better continuity.  I have my bias, cut out eye-candy nonsense and live within your means if the sound engine will get more cycles back.

Timers.  Using CADisplayLink.  I haven't had to think about it much.  This is what I have.

- (NSInteger)animationFrameInterval
{
    return animationFrameInterval;
}

- (void)setAnimationFrameInterval:(NSInteger)frameInterval
{
    if (frameInterval >= 16)
    {
        animationFrameInterval = frameInterval;

        if (animating)
        {
            [self stopAnimation];
            [self startAnimation];
        }
    }
}

- (void)startAnimation
{
    if (!animating)
    {
      displayLink = [NSClassFromString(@"CADisplayLink")
            displayLinkWithTarget:self
            selector:@selector(drawView:)];
        [displayLink setFrameInterval:animationFrameInterval];
        [displayLink addToRunLoop:[NSRunLoop
              currentRunLoop]
            forMode:NSDefaultRunLoopMode];

        animating = TRUE;
    }
}

- (void)stopAnimation
{
    if (animating)
    {
      [displayLink invalidate];
      displayLink = nil;

        animating = FALSE;
    }
}

I am not making this stuff up.  Please don't put up "music instruments" in the store until you are addressing these issues.  Jordan Rudess, Leon Gruenbaum, Chris Dudley and other pro musicians used to bring these issues up constantly when talking about iPad/iPhone apps.  The situation seems to have improved somewhat, but I don't think most developers know what numbers real musicians expect.


问:
Regex to match a rather complex string
Any experts on Regex, that could potentially find a pattern on this data, im looking for one that will match exactly, down to spaces and commas and dashes. Here is the sample data of what i need to match:

word word, alphanumeric-PRT-word-number

word word, alphanumeric-PRT-number

-word: any size word

-alphanumeric: 3 letters and up to 2 numbers, so XXX# or XXX##

-number: up to 3 digits, so # or ## or ###

-PRT: is the only static value here

NOTE: no other punctuation other than the spaces, comma and dashes where they are.

So far have something close to it but rather clunky and it doesnt cover all bases, i built it here: http://buildregex.com/ using their logic and it kinda works:

```<code>/(?:[^_\ ]+)(?:\ )(?:[^_\ ]+), (?:[^_\ ]+)-PRT-(?:[^_\ ]*)/gi
</code>```

If any can assist in refining this that will be welcome

https://regex101.com/r/8cc52u/2

Thanks a lot

答:
Here's one way to do it:

```<code>/^[a-z]+\s[a-z]+,\s[a-z]{3}\d{1,2}-prt-([a-z]+-){0,1}\d{1,3}$/gi
</code>```

^: start of line

[a-z]+: one or more letters

\s: any space character

[a-z]+: one or more letters

,: ,

\s: any space character

[a-z]{3}: three letters

\d{1,2}: one or two digits

-prt-: -prt-

([a-z]+-){0,1}: one or more letters followed by -, zero or one time

\d{1,3}: one, two or three digits

$: end of line

Example: https://regex101.com/r/BhS8kM/5

Or, as suggested by revo:

```<code>/^[a-z]+ [a-z]+, [a-z]{3}\d{1,2}-prt-([a-z]+-)?\d{1,3}$/gi
</code>```

Example: https://regex101.com/r/BhS8kM/7

Title: Regex to match a rather complex string

Body:
Any experts on Regex, that could potentially find a pattern on this data, im looking for one that will match exactly, down to spaces and commas and dashes. Here is the sample data of what i need to match:

word word, alphanumeric-PRT-word-number

word word, alphanumeric-PRT-number

-word: any size word

-alphanumeric: 3 letters and up to 2 numbers, so XXX# or XXX##

-number: up to 3 digits, so # or ## or ###

-PRT: is the only static value here

NOTE: no other punctuation other than the spaces, comma and dashes where they are.

So far have something close to it but rather clunky and it doesnt cover all bases, i built it here: http://buildregex.com/ using their logic and it kinda works:

/(?:[^_\ ]+)(?:\ )(?:[^_\ ]+), (?:[^_\ ]+)-PRT-(?:[^_\ ]*)/gi

If any can assist in refining this that will be welcome

https://regex101.com/r/8cc52u/2

Thanks a lot

Body:
Here's one way to do it:

/^[a-z]+\s[a-z]+,\s[a-z]{3}\d{1,2}-prt-([a-z]+-){0,1}\d{1,3}$/gi

^: start of line

[a-z]+: one or more letters

\s: any space character

[a-z]+: one or more letters

,: ,

\s: any space character

[a-z]{3}: three letters

\d{1,2}: one or two digits

-prt-: -prt-

([a-z]+-){0,1}: one or more letters followed by -, zero or one time

\d{1,3}: one, two or three digits

$: end of line

Example: https://regex101.com/r/BhS8kM/5

Or, as suggested by revo:

/^[a-z]+ [a-z]+, [a-z]{3}\d{1,2}-prt-([a-z]+-)?\d{1,3}$/gi

Example: https://regex101.com/r/BhS8kM/7


问:
Angular2 RC5 tutorial : Can't bind to 'ngModel' since it isn't a known property of 'input'
Following the Angular 2 "Hero tour" tutorial, I encounter the following error:

```<code>Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("
    <div>
      <label>name: </label>
      <input [ERROR ->][(ngModel)]="hero.name" placeholder="name">
    </div>
    "): AppComponent@6:13 ; Zone: <root> ; Task: Promise.then ; Value:
</code>```

My package.json content is:

```<code>{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0-rc.5",
    "@angular/compiler": "2.0.0-rc.5",
    "@angular/core": "2.0.0-rc.5",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.5",
    "@angular/platform-browser": "2.0.0-rc.5",
    "@angular/platform-browser-dynamic": "2.0.0-rc.5",
    "@angular/router": "3.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.5",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2": "^2.0.0-beta.17",
    "angular2-in-memory-web-api": "0.0.15",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^1.0.4"
  }
}
</code>```

app.module.ts content:

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
})

export class AppModule { }
</code>```

And app.component content :

```<code>import { Component } from '@angular/core';
export class Hero {
    id: number;
    name: string;
}
@Component({
    selector: 'my-app',
    template: `
    <h1>{{title}}</h1>
    <h2>{{hero.name}} details!</h2>
    <div><label>id: </label>{{hero.id}}</div>
    <div>
      <label>name: </label>
      <input [(ngModel)]="hero.name" placeholder="name">
    </div>
    `
})
export class AppComponent {
    title = 'Tour of Heroes';
    hero: Hero = {
        id: 1,
        name: 'Windstorm'
    };
}
</code>```

I spent time to read and apply solutions proposed in similar question on stackoverflow with no success.

What could be wrong?

Solution :

use

```<code>//main entry point
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app';

platformBrowserDynamic().bootstrapModule(AppModule)
</code>```

instead of :

```<code>import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
bootstrap(AppComponent);
</code>```

答: The app works fine. But I had this error in tests. You should import FormsModule in app.component.spec.ts like in app.module.ts to fix this.</p>

Body:
Following the Angular 2 "Hero tour" tutorial, I encounter the following error:

Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("

      name:
      <input [ERROR ->][(ngModel)]="hero.name" placeholder="name">

    "): AppComponent@6:13 ; Zone: <root> ; Task: Promise.then ; Value:

My package.json content is:

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0-rc.5",
    "@angular/compiler": "2.0.0-rc.5",
    "@angular/core": "2.0.0-rc.5",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.5",
    "@angular/platform-browser": "2.0.0-rc.5",
    "@angular/platform-browser-dynamic": "2.0.0-rc.5",
    "@angular/router": "3.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.5",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2": "^2.0.0-beta.17",
    "angular2-in-memory-web-api": "0.0.15",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^1.0.4"
  }
}

app.module.ts content:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
})

export class AppModule { }

And app.component content :

import { Component } from '@angular/core';
export class Hero {
    id: number;
    name: string;
}
@Component({
    selector: 'my-app',
    template: `

{{title}}

{{hero.name}} details!

id: {{hero.id}}

      name:
      <input [(ngModel)]="hero.name" placeholder="name">

    `
})
export class AppComponent {
    title = 'Tour of Heroes';
    hero: Hero = {
        id: 1,
        name: 'Windstorm'
    };
}

I spent time to read and apply solutions proposed in similar question on stackoverflow with no success.

What could be wrong?

Solution :

use

//main entry point
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app';

platformBrowserDynamic().bootstrapModule(AppModule)

instead of :

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
bootstrap(AppComponent);


问:
Does tensorflow use automatic or symbolic gradients?
I haven't been able to find a clear statement of whether tensorflow uses automatic or symbolic differentiation.

I skimmed the tensorflow paper and they mention automatic gradients, but it is unclear if they just mean symbolic gradients, as they also mention that it has that capability.

答:
Afaik symbolic differentiation means working with a mathematical, symbolic equation (i.e., symbolic math equation in, derivative of the equation out). Automatic differentiation computes derivatives based on computational functions (which in turn are broken down into basic operations such as addition/subtraction and multipliation/division).

Since TensorFlow does differentiation based on a computation graph of operations, I'd intuitively say that it's automatic differentiation (I don't know of any other technique that would be appropriate here; I think the possibility that TensorFlow is converting the computation graph into a mathematical equation that is then parsed to compute the derivative of that equation is prob. out of question). The authors say "symbolic differentiation" in the TensorFlow whitepaper though -- however, I think this may be a misnomer similar to "Tensor" instead of "(multi-dimensional) data array" if you'd ask a mathematician.


问:
One form, One submission button, but TWO actions
I have a form that collects client's info and then it

saves them in the database

sends out few emails

sends the info to SalesForce (SF) department

Now, the first 2 two task was easy, but the third one is giving me trouble. For SF i don't have do anything special, just have to add their url and they will pull out all the necessary info they need from the form. To me it seems like in order to do these i need the form have 2 actions associated with one submit button (can't have 2 forms or 2 buttons).

So in my raf.php file I have this form, and after submission i have to redirect them to raf-submitted.php page that displays the success/error message and other necessary info.

The form  (got the idea from here)

```<code> <form id="referralForm" name="referralForm" autocomplete="off" enctype="multipart/form-data" method="POST">

 <input id="saveForm" name="saveForm" class="field-submit" type="button" value="Submit" style="padding-left:20px" width="100" tabindex="23" onclick="FormSubmission(); SalesForceSubmission();" />

 </form>
</code>```

The JavaScript:

```<code> $(document).ready(function()
 {
    function SalesForceSubmission()
    {
       document.referralForm.action = "https://someAddress.salesforce.com/";
       document.referralForm.submit();
       return true;
    }

    function FormSubmission()
    {
       document.referralForm.action = "raf-submitted.php";
       document.referralForm.submit();
       return true;
    }
  });
</code>```

The raf-submitted.php file take cares of the form validation, database insertion and email issues.

It's not working. I also tried these with no luck:

Two onClick actions one button

Two Form Action that opens URL in a new window in One Submit button?

Can someone please help me? Thank you!

答:
This looks a lot like something I was trying to do. You've already got an answer marked, but I don't think it's the simple answer you were looking for.

Assuming task 3 above can be done with a POST to some SalesForce .PHP location, and the first two tasks could be done in a JavaScript function, I think this will work:

```<code><form method="post" action="SubmitToSalesForce.php">
  <button type="submit" name="doThreeThings" onclick="doTheFirstTwoTasks();" >
</form

<script type="text/javascript">
  function doTheFirstTwoTasks() {
    // Task 1
    // Task 2
  }
</script>
</code>```

It first calls the doTheFirstTwoTasks() function via onclick= to do tasks 1 and 2, and then submits the form via a normal form submission to the action= location for the third task.

Nothing special, but I don't know how many people have learned that you can use onclick= and type=submit (with action=) for two different actions in a single form with a single submit button.

In the code above, it seems to call the onclick= before the action= (or perhaps it's just because the POST submission is slower than calling a JavaScript function...)

Body:
I have a form that collects client's info and then it

saves them in the database

sends out few emails

sends the info to SalesForce (SF) department

Now, the first 2 two task was easy, but the third one is giving me trouble. For SF i don't have do anything special, just have to add their url and they will pull out all the necessary info they need from the form. To me it seems like in order to do these i need the form have 2 actions associated with one submit button (can't have 2 forms or 2 buttons).

So in my raf.php file I have this form, and after submission i have to redirect them to raf-submitted.php page that displays the success/error message and other necessary info.

The form  (got the idea from here)

 <form id="referralForm" name="referralForm" autocomplete="off" enctype="multipart/form-data" method="POST">

 <input id="saveForm" name="saveForm" class="field-submit" type="button" value="Submit" style="padding-left:20px" width="100" tabindex="23" onclick="FormSubmission(); SalesForceSubmission();" />

 </form>

The JavaScript:

 $(document).ready(function()
 {
    function SalesForceSubmission()
    {
       document.referralForm.action = "https://someAddress.salesforce.com/";
       document.referralForm.submit();
       return true;
    }

    function FormSubmission()
    {
       document.referralForm.action = "raf-submitted.php";
       document.referralForm.submit();
       return true;
    }
  });

The raf-submitted.php file take cares of the form validation, database insertion and email issues.

It's not working. I also tried these with no luck:

Two onClick actions one button

Two Form Action that opens URL in a new window in One Submit button?

Can someone please help me? Thank you!

Body:
This looks a lot like something I was trying to do. You've already got an answer marked, but I don't think it's the simple answer you were looking for.

Assuming task 3 above can be done with a POST to some SalesForce .PHP location, and the first two tasks could be done in a JavaScript function, I think this will work:

<form method="post" action="SubmitToSalesForce.php">
  <button type="submit" name="doThreeThings" onclick="doTheFirstTwoTasks();" >
</form

<script type="text/javascript">
  function doTheFirstTwoTasks() {
    // Task 1
    // Task 2
  }
</script>

It first calls the doTheFirstTwoTasks() function via onclick= to do tasks 1 and 2, and then submits the form via a normal form submission to the action= location for the third task.

Nothing special, but I don't know how many people have learned that you can use onclick= and type=submit (with action=) for two different actions in a single form with a single submit button.

In the code above, it seems to call the onclick= before the action= (or perhaps it's just because the POST submission is slower than calling a JavaScript function...)


问:
FTP connection through PHP always ask for username & password
So I have an FTP server with bulk of large files (mostly satellite imagery data). I am building a system with PHP to serve users to download the files. The system can show the list of files in FTP server, so they can download the files. Typically, the list is not from the FTP server, I stored the list in the database.

For FTP connection, I have stored the details (ftp user, ftp password, and ftp server) in a config file. So here I don't want user input anything, just click the download button, and get the files.

The flow of my system is:

Check if the requested data is available.

If available, then do FTP connection with ftp_connect

If connection succeed, then login to FTP using ftp_login

Insert new record to the log table in the database.

Redirect user to the requested file using PHP header('Location:')

Close the FTP connection

It works actually!

But it always asks for FTP username and password for every user download requests.

So what is wrong? Or is there any better approach?

Edit:
Here is the code in download.php:

```<code>    <?php
    include "config.php";
    include "query_user.php";
    include "function.php";

    $data_id = $_GET['data_id'];

    $user_id = $query_user['user_id'];

    $query = mysqli_query($link, "SELECT count(*) as jumlah, data_url FROM lord_data WHERE data_id='".$data_id."'");
    $query_data = mysqli_fetch_array($query);

    if($query_data['jumlah'] > 0){
        $name= $query_data['data_url'];
        set_time_limit(20);
        $conn_id = ftp_connect($ftp_server, 21, 10);
        if($conn_id){
            $conn_login = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
            $query = mysqli_query($link, "INSERT INTO lord_download_log (user_id, data_id) VALUES ('$user_id', '$data_id')");
            header('Location: ftp://'.$ftp_server.'/foldername/'.$name.'');
            // close the connection
            ftp_close($conn_id);
        }else{
            $ftp_server = "172.xx.xx.xx";
            $change_ip = ftp_connect($ftp_server, 21, 10);
            if($change_ip){
                $conn_login = ftp_login($change_ip, $ftp_user_name,        $ftp_user_pass);
                $query = mysqli_query($link, "INSERT INTO lord_download_log (user_id, data_id) VALUES ('$user_id', '$data_id')");
                header('Location: ftp://'.$ftp_server.'/foldername/'.$name.'');
                // close the connection
                ftp_close($change_ip);
            }else{
                echo "Couldn't establish a connection.";
            }
        }

    }else{
        echo "<script>alert('Download failed! Data is not available');document.location='index.php?p=data_download';</script>";
    }
    ?>
</code>```

答:
You need to download file with ftp_get method rather than redirecting user to the file location.

Use following code to get file from FTP and force user to download it:

```<code>$server_file = "/path/to/server/file";
$conn_id = ftp_connect($ftp_server);
$local_file = tempnam(sys_get_temp_dir(), 'download_');
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
  $quoted = sprintf('"%s"', addcslashes(basename($local_file), '"\\'));
  $size   = filesize($local_file);

  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename=' . $quoted);
  header('Content-Transfer-Encoding: binary');
  header('Connection: Keep-Alive');
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
  header('Content-Length: ' . $size);
}
ftp_close($conn_id);
</code>```

Body:
So I have an FTP server with bulk of large files (mostly satellite imagery data). I am building a system with PHP to serve users to download the files. The system can show the list of files in FTP server, so they can download the files. Typically, the list is not from the FTP server, I stored the list in the database.

For FTP connection, I have stored the details (ftp user, ftp password, and ftp server) in a config file. So here I don't want user input anything, just click the download button, and get the files.

The flow of my system is:

Check if the requested data is available.

If available, then do FTP connection with ftp_connect

If connection succeed, then login to FTP using ftp_login

Insert new record to the log table in the database.

Redirect user to the requested file using PHP header('Location:')

Close the FTP connection

It works actually!

But it always asks for FTP username and password for every user download requests.

So what is wrong? Or is there any better approach?

Edit:
Here is the code in download.php:

    <?php
    include "config.php";
    include "query_user.php";
    include "function.php";

    $data_id = $_GET['data_id'];

    $user_id = $query_user['user_id'];

    $query = mysqli_query($link, "SELECT count(*) as jumlah, data_url FROM lord_data WHERE data_id='".$data_id."'");
    $query_data = mysqli_fetch_array($query);

    if($query_data['jumlah'] > 0){
        $name= $query_data['data_url'];
        set_time_limit(20);
        $conn_id = ftp_connect($ftp_server, 21, 10);
        if($conn_id){
            $conn_login = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
            $query = mysqli_query($link, "INSERT INTO lord_download_log (user_id, data_id) VALUES ('$user_id', '$data_id')");
            header('Location: ftp://'.$ftp_server.'/foldername/'.$name.'');
            // close the connection
            ftp_close($conn_id);
        }else{
            $ftp_server = "172.xx.xx.xx";
            $change_ip = ftp_connect($ftp_server, 21, 10);
            if($change_ip){
                $conn_login = ftp_login($change_ip, $ftp_user_name,        $ftp_user_pass);
                $query = mysqli_query($link, "INSERT INTO lord_download_log (user_id, data_id) VALUES ('$user_id', '$data_id')");
                header('Location: ftp://'.$ftp_server.'/foldername/'.$name.'');
                // close the connection
                ftp_close($change_ip);
            }else{
                echo "Couldn't establish a connection.";
            }
        }

    }else{
        echo "";
    }
    ?>

Body:
You need to download file with ftp_get method rather than redirecting user to the file location.

Use following code to get file from FTP and force user to download it:

$server_file = "/path/to/server/file";
$conn_id = ftp_connect($ftp_server);
$local_file = tempnam(sys_get_temp_dir(), 'download_');
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
  $quoted = sprintf('"%s"', addcslashes(basename($local_file), '"\\'));
  $size   = filesize($local_file);

  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename=' . $quoted);
  header('Content-Transfer-Encoding: binary');
  header('Connection: Keep-Alive');
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
  header('Content-Length: ' . $size);
}
ftp_close($conn_id);


问:
spring boot failed to start due to "The port may already be in use"
I tried to start my spring boot application on centos server with this command line.

```<code>SPRING_PROFILES_ACTIVE=prd java -jar ./build/libs/port_switcher-0.0.1-SNAPSHOT.jar
</code>```

But I got an error message that the port is already in used.
then looked up process list which is used in the port number using netstat
but there is no process that uses the port number

and then I rerun my spring boot application without SPRING_PROFILES_ACTIVE variable. (it was an mistake that forget that variable)
at that time spring boot application run successfully.

I really want to know what problem is in my application properties

this command occur error

```<code>SPRING_PROFILES_ACTIVE=prd java -jar ./build/libs/port_switcher-0.0.1-SNAPSHOT.jar
</code>```

this command works fine

```<code>java -jar ./build/libs/port_switcher-0.0.1-SNAPSHOT.jar
</code>```

application-prd.properties

```<code>#Server
server.address=xxx.xxx.xxx.xxx
server.port=9090

#Devtools
spring.devtools.livereload.enabled=true
spring.devtools.restart.enabled=true

# Logging
logging.level.org.springframework.web=INFO
logging.level.com.kakao.portswitcher=INFO
logging.path=logs

server.tomcat.basedir=./
server.tomcat.accesslog.enabled=true
#server.tomcat.accesslog.file-date-format=.yyyy-MM-dd
server.tomcat.accesslog.rotate=true
server.tomcat.accesslog.suffix=.log
server.tomcat.accesslog.prefix=access
server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.buffered=true

#Jackson
spring.jackson.property-naming-strategy=SNAKE_CASE

# Status check file
status.file=./port_switcher_status
</code>```

答:
Can you try this :

java -jar -Dspring.profiles.active=prd ./build/libs/port_switcher-0.0.1-SNAPSHOT.jar

Body:
I tried to start my spring boot application on centos server with this command line.

SPRING_PROFILES_ACTIVE=prd java -jar ./build/libs/port_switcher-0.0.1-SNAPSHOT.jar

But I got an error message that the port is already in used.
then looked up process list which is used in the port number using netstat
but there is no process that uses the port number

and then I rerun my spring boot application without SPRING_PROFILES_ACTIVE variable. (it was an mistake that forget that variable)
at that time spring boot application run successfully.

I really want to know what problem is in my application properties

this command occur error

SPRING_PROFILES_ACTIVE=prd java -jar ./build/libs/port_switcher-0.0.1-SNAPSHOT.jar

this command works fine

java -jar ./build/libs/port_switcher-0.0.1-SNAPSHOT.jar

application-prd.properties

#Server
server.address=xxx.xxx.xxx.xxx
server.port=9090

#Devtools
spring.devtools.livereload.enabled=true
spring.devtools.restart.enabled=true

# Logging
logging.level.org.springframework.web=INFO
logging.level.com.kakao.portswitcher=INFO
logging.path=logs

server.tomcat.basedir=./
server.tomcat.accesslog.enabled=true
#server.tomcat.accesslog.file-date-format=.yyyy-MM-dd
server.tomcat.accesslog.rotate=true
server.tomcat.accesslog.suffix=.log
server.tomcat.accesslog.prefix=access
server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.buffered=true

#Jackson
spring.jackson.property-naming-strategy=SNAKE_CASE

# Status check file
status.file=./port_switcher_status


问:
Datagrid Row Update problem
I am using WPF toolkit Datagrid. I have a rowvalidationrule defined on this. to trigger this validation rule, on each cell update i have to hit enter button. but i want to check this on each cell update without hitting Enter button. How can i do this. this is a MVVM app.
Thanks,
Rey</p>

答: i am using IDataErrorInfo and UpdateSourceTrigger=propertychanged to trigger cell level validation. </p>

Title: Datagrid Row Update problem


问:
Upload an image file to server given URL
I'm wondering if it's possible to use ajax to upload an image to a flask server in request.files by typing in the url through a form. Here is my current form setup:

```<code><form method=post enctype=multipart/form-data runat="server" id="capture_form">
<div class="form-group">
        <label for=facesURL>URL:</label>
        <input type="text" name="image_url" class="form-control" id=facesURL placeholder="URL of image">
        <input type="submit" value="Preview URL image" id="submit">
</div>
<button align="center" class="btn btn-info upload-image" id=upload-image type=submit value="Upload Image">Upload File</button>
</code>```

At the moment, the preview URL image button displays the image from the url into an , however I'm stuck at actually grabbing that src and uploading it on click of the upload image button. Any help is appreciated.

答:
If the user is specifying a URL, it may make more sense to have the server download the image from the specified URL itself (on the back-end) rather than trying to have the webpage download and send the image directly.

Here's a rough (untested) view function that shows what your code may end up looking like:

```<code>@app.route('/submit_image', methods=['GET', 'POST'])
def submit_image():
    # I'm assuming you're using the Flask-WTF module for your forms
    form = SubmitImageForm()
    if request.method == 'GET':
        return render_template('submit_image.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            path_to_save_image_to = ''  # Fill this in

            with open(path_to_save_image_to,'wb') as f:
                f.write(urllib.request.urlopen(form.image_url.data, path_to_save_to).read())

            return redirect(url_for('submission_successful'))
        else:
            return render_template('submit_image.html', form=form, error="Invalid submission")
</code>```

With help from: Downloading a picture via urllib and python

Body:
I'm wondering if it's possible to use ajax to upload an image to a flask server in request.files by typing in the url through a form. Here is my current form setup:

<form method=post enctype=multipart/form-data runat="server" id="capture_form">

        URL:
        <input type="text" name="image_url" class="form-control" id=facesURL placeholder="URL of image">
        <input type="submit" value="Preview URL image" id="submit">

<button align="center" class="btn btn-info upload-image" id=upload-image type=submit value="Upload Image">Upload File</button>

At the moment, the preview URL image button displays the image from the url into an , however I'm stuck at actually grabbing that src and uploading it on click of the upload image button. Any help is appreciated.

Body:
If the user is specifying a URL, it may make more sense to have the server download the image from the specified URL itself (on the back-end) rather than trying to have the webpage download and send the image directly.

Here's a rough (untested) view function that shows what your code may end up looking like:

@app.route('/submit_image', methods=['GET', 'POST'])
def submit_image():
    # I'm assuming you're using the Flask-WTF module for your forms
    form = SubmitImageForm()
    if request.method == 'GET':
        return render_template('submit_image.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            path_to_save_image_to = ''  # Fill this in

            with open(path_to_save_image_to,'wb') as f:
                f.write(urllib.request.urlopen(form.image_url.data, path_to_save_to).read())

            return redirect(url_for('submission_successful'))
        else:
            return render_template('submit_image.html', form=form, error="Invalid submission")

With help from: Downloading a picture via urllib and python


问:
Twitter Bootstrap - add top space between rows
How to add margin top to class="row" elements using twitter bootstrap framework?

答:
```<code>just take a new class beside every row and apply css of margin-top: 20px;
here is the code below
<style>
  .small-top
   {
     margin-top: 25px;
   }
</style>
<div class="row small-top">
   <div class="col-md-12">
   </div>
 </div>
</code>```


问:
What does the Visual Studio "Any CPU" target mean?
I have some confusion related to the .NET platform build options in Visual Studio 2008.

What is the "Any CPU" compilation target, and what sort of files does it generate? I examined the output executable of this "Any CPU" build and found that they are the x86 executables (who would not see that coming!). So, is there any difference between targeting executable to x86 vs. "Any CPU"?

Another thing that I noticed, is that managed C++ projects do not have this platform as an option. Why is that? Does that mean that my suspicion about "Any CPU" executables being plain 32-bit ones is right?

答:
I recommend reading this post.

When using AnyCPU, the semantics are the following:

If the process runs on a 32-bit Windows system, it runs as a 32-bit process. CIL is compiled to x86 machine code.

If the process runs on a 64-bit Windows system, it runs as a 32-bit process. CIL is compiled to x86 machine code.

If the process runs on an ARM Windows system, it runs as a 32-bit process. CIL is compiled to ARM machine code.

OwnerDisplayName: galets

LastEditorDisplayName: JPunyon


问:
Angucomplete-alt local-data fires server request
As per the decoumentation, I have specified the directive in my HTML as follows:

```<code><div angucomplete-alt
    id="keyword"
    input-name="keyword"
    placeholder="Job title or keywords"
    pause="100"
    selected-object="selectedJob"
    local-data="jobs"
    search-fields="name"
    title-field="name"
    minlength="2"
    input-class="form-control">
</div>
</code>```

Specifying local-data and search-fields. In my controller I have:

```<code>$scope.jobs = [
    {"name": ".Net Developer"},
    {"name": "Account Coordinator"},
    {"name": "Account Director"},
    {"name": "Account Executive"},
    {"name": "Account Executive Sales"}.
    ...
];

$scope.selectedJob = function($item) {
    $log.info('$scope.selectedJob()', $item);
};
</code>```

But when I type on the field, an XHR request goes out to /undefinedWHATEVER_I_TYPED which is of course 404. No results from my jobs array are shown...

What am I doing wrong?

答: Late answer,Still if someone encounter this issue just enable cors in browser if you are calling api from localhost.</p>

Body:
As per the decoumentation, I have specified the directive in my HTML as follows:

Specifying local-data and search-fields. In my controller I have:

$scope.jobs = [
    {"name": ".Net Developer"},
    {"name": "Account Coordinator"},
    {"name": "Account Director"},
    {"name": "Account Executive"},
    {"name": "Account Executive Sales"}.
    ...
];

$scope.selectedJob = function($item) {
    $log.info('$scope.selectedJob()', $item);
};

But when I type on the field, an XHR request goes out to /undefinedWHATEVER_I_TYPED which is of course 404. No results from my jobs array are shown...

What am I doing wrong?


问:
update a List with structs Elixir
I have an an object as

```<code>%{
  shares: []
}
</code>```

I want to add a struct %Cs{name: "Junaid1"}, %Cs{name: "Junaid2"} into the list through Enum.each or map, is that possible to do?

Okay for just more brief I am updating question again..

```<code> Enum.each(email_array, fn (email) ->
    with {:found_user, sharee} <- ensure_user(email)
    do
      case CameraShare.create_share(camera, sharee, caller, params["rights"], params["message"]) do
        {:ok, camera_share} ->
           #Add camera_share to list
        {:error, changeset} ->
          #Add error to a list
      end
    else
      {:not_found, email} ->
        case CameraShareRequest.create_share_request(camera, email, caller, params["rights"], params["message"]) do
          {:ok, camera_share_request} ->
            #Add camera_share to list
          {:error, changeset} ->
            #Add error to list
        end
    end
  end)
</code>```

and then at the end of Enum.each.. there will be a map as

```<code>%{
   shares: [all shares],
   errors: [all errors]
}
</code>```

where as each share is of type %CameraShare{__meta__: #Ecto.Schema.Metadata<:loaded, "camera_shares">}

答:
```<code>map = %{
  shares: [%{name: "Junaid0"}]
}
add_shares = [%{name: "Junaid1"}, %{name: "Junaid2"}]
</code>```

Straigt list concatenation

```<code>%{map | shares: map[:shares] ++ add_shares}
</code>```

Comprehension

```<code>%{map | shares: (for share <- add_shares, into: map[:shares], do: share)}
</code>```

Enum.reduce

```<code>Enum.reduce(add_shares, map, fn share, acc ->
  %{acc | shares: [share | acc[:shares]]}
end)
</code>```

Enum.into

```<code>%{map | shares: Enum.into(add_shares, map[:shares], & &1)}
</code>```

FWIW:

Adding an element to already existing list:

```<code>list = []
element = 42

list1 = [element | list]
#⇒ [42]
list2 = [element | list1]
#⇒ [42, 42]
</code>```

Answer to updated question (simplified):

```<code>Enum.reduce(email_array, {[], []}, fn
  email, {shares, changes} = _acc ->
    with {:found_user, sharee} <- ensure_user(email) do
      case :camera_share do
        {:ok, camera_share} ->
           {[camera_share | shares], changes}
        {:error, changeset} ->
           {shares, [changeset | changes]}
      end
    else
      # basically the same
      # make sure ALL branches return an acumulator
    end
  end)
</code>```

The above would return a tuple {shares, changes} that you might assign to anything.

Title: update a List with structs Elixir

Body:
I have an an object as

%{
  shares: []
}

I want to add a struct %Cs{name: "Junaid1"}, %Cs{name: "Junaid2"} into the list through Enum.each or map, is that possible to do?

Okay for just more brief I am updating question again..

 Enum.each(email_array, fn (email) ->
    with {:found_user, sharee} <- ensure_user(email)
    do
      case CameraShare.create_share(camera, sharee, caller, params["rights"], params["message"]) do
        {:ok, camera_share} ->
           #Add camera_share to list
        {:error, changeset} ->
          #Add error to a list
      end
    else
      {:not_found, email} ->
        case CameraShareRequest.create_share_request(camera, email, caller, params["rights"], params["message"]) do
          {:ok, camera_share_request} ->
            #Add camera_share to list
          {:error, changeset} ->
            #Add error to list
        end
    end
  end)

and then at the end of Enum.each.. there will be a map as

%{
   shares: [all shares],
   errors: [all errors]
}

where as each share is of type %CameraShare{__meta__: #Ecto.Schema.Metadata<:loaded, "camera_shares">}

Body:
map = %{
  shares: [%{name: "Junaid0"}]
}
add_shares = [%{name: "Junaid1"}, %{name: "Junaid2"}]

Straigt list concatenation

%{map | shares: map[:shares] ++ add_shares}

Comprehension

%{map | shares: (for share <- add_shares, into: map[:shares], do: share)}

Enum.reduce

Enum.reduce(add_shares, map, fn share, acc ->
  %{acc | shares: [share | acc[:shares]]}
end)

Enum.into

%{map | shares: Enum.into(add_shares, map[:shares], & &1)}

FWIW:

Adding an element to already existing list:

list = []
element = 42

list1 = [element | list]
#⇒ [42]
list2 = [element | list1]
#⇒ [42, 42]

Answer to updated question (simplified):

Enum.reduce(email_array, {[], []}, fn
  email, {shares, changes} = _acc ->
    with {:found_user, sharee} <- ensure_user(email) do
      case :camera_share do
        {:ok, camera_share} ->
           {[camera_share | shares], changes}
        {:error, changeset} ->
           {shares, [changeset | changes]}
      end
    else
      # basically the same
      # make sure ALL branches return an acumulator
    end
  end)

The above would return a tuple {shares, changes} that you might assign to anything.


问:
QT Draw Rectangle on QGraphicsitem
My work Environment: Qt 5.8 MSVC2015 64bit, QT GraphicsView, QGraphicsObject, Windows 7 64 bit.

In my application I have added multiple QGraphicsitem, into a single graphic scene & into a single graphic view.

But I need to draw empty green color rectangle on top of QGraphicsitem image, as per mouse position.
So I tried with below :

```<code>QRubberBand* _rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
_rubberBand->setGeometry(QRect(MousePos.x() -2, MousePos.y() - 2, MousePos.x() + 2, MousePos.y() + 2).normalized());
_rubberBand->setAutoFillBackground(false);
QPalette pal;
pal.setBrush(QPalette::Highlight, QBrush(Qt::green));
_rubberBand->setPalette(pal);
_rubberBand->show();
</code>```

Issue with QRubberBand, it changes size dynamically, I want draw small rectangle,   not flickery RubberBand.

QRubberBand Output:

Expected Output:

答:
@m7913d, tons of thanks for your value added suggestion.
I have Override QRubberBand class &  set QRubberBand class setGeometry, setPen & it's color.

Here is final solution code :

```<code>class roiFrame : public QRubberBand
{
public:
    roiFrame(Shape s, QWidget * p = 0):QRubberBand(s, p){}
    ~roiFrame(){}
protected:
    void paintEvent(QPaintEvent *pe)
    {
        Q_UNUSED(pe);
        QStyleOptionRubberBand opt;
        QStylePainter painter(this);
        opt.initFrom(this);
        QRect rectangle(0,0,30, 15);
        QColor color(Qt::green);
        painter.setPen(color);
        painter.drawRect(rectangle);
    }
};
</code>```

Caller code :

```<code>_rectFrame = new roiFrame(QRubberBand::Rectangle, this);
_rectFrame->setGeometry(QRect(thumbMousePos.x() -1, thumbMousePos.y() - 1, thumbMousePos.x() + 1, thumbMousePos.y() + 1).normalized());
_rectFrame->setAutoFillBackground(false);
_rectFrame->show();
</code>```

Title: QT Draw Rectangle on QGraphicsitem

Body:
My work Environment: Qt 5.8 MSVC2015 64bit, QT GraphicsView, QGraphicsObject, Windows 7 64 bit.

In my application I have added multiple QGraphicsitem, into a single graphic scene & into a single graphic view.

But I need to draw empty green color rectangle on top of QGraphicsitem image, as per mouse position.
So I tried with below :

QRubberBand* _rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
_rubberBand->setGeometry(QRect(MousePos.x() -2, MousePos.y() - 2, MousePos.x() + 2, MousePos.y() + 2).normalized());
_rubberBand->setAutoFillBackground(false);
QPalette pal;
pal.setBrush(QPalette::Highlight, QBrush(Qt::green));
_rubberBand->setPalette(pal);
_rubberBand->show();

Issue with QRubberBand, it changes size dynamically, I want draw small rectangle,   not flickery RubberBand.

QRubberBand Output:

Expected Output:

Body:
@m7913d, tons of thanks for your value added suggestion.
I have Override QRubberBand class &  set QRubberBand class setGeometry, setPen & it's color.

Here is final solution code :

class roiFrame : public QRubberBand
{
public:
    roiFrame(Shape s, QWidget * p = 0):QRubberBand(s, p){}
    ~roiFrame(){}
protected:
    void paintEvent(QPaintEvent *pe)
    {
        Q_UNUSED(pe);
        QStyleOptionRubberBand opt;
        QStylePainter painter(this);
        opt.initFrom(this);
        QRect rectangle(0,0,30, 15);
        QColor color(Qt::green);
        painter.setPen(color);
        painter.drawRect(rectangle);
    }
};

Caller code :

_rectFrame = new roiFrame(QRubberBand::Rectangle, this);
_rectFrame->setGeometry(QRect(thumbMousePos.x() -1, thumbMousePos.y() - 1, thumbMousePos.x() + 1, thumbMousePos.y() + 1).normalized());
_rectFrame->setAutoFillBackground(false);
_rectFrame->show();


问:
Convert this PHP function to get server variables to VB .Net
I am having trouble getting server variables remotely in VB .Net I need to basically mimic this PHP Function.

```

function showvar($string)
{
 if(isset($_SERVER[$string]))
 {
  echo "$string: ".rawurldecode($_SERVER[$string])."\r\n";
 }
}

/*normal vars*/
showvar("HTTP_ACCEPT");
showvar("HTTP_ACCEPT_ENCODING");
showvar("HTTP_ACCEPT_LANGUAGE");
showvar("HTTP_ACCEPT_CHARSET");
showvar("HTTP_HOST");
showvar("HTTP_KEEP_ALIVE");
showvar("HTTP_COOKIE");
showvar("HTTP_UA_CPU");
showvar("HTTP_REFERER");

/*important vars*/
showvar("HTTP_USER_AGENT");
showvar("REMOTE_ADDR");
showvar("REMOTE_HOST");
showvar("HTTP_CONNECTION");
showvar("HTTP_X_FORWARDED_FOR");
showvar("HTTP_FORWARDED");
showvar("HTTP_VIA");
showvar("KEEP_ALIVE");
showvar("HTTP_MAX_FORWARDS");
showvar("MAX_FORWARDS");
showvar("HTTP_CACHE_CONTROL");
showvar("HTTP_PROXY_CONNECTION");
showvar("HTTP_X_BLUECOAT_VIA");
showvar("HTTP_PC_REMOTE_ADDR");
showvar("HTTP_PROXY___________");
showvar("HTTP_PROXY____");
showvar("HTTP_X_FWD_IP_ADDR");
showvar("HTTP_X_HOST");
showvar("HTTP_X_REFERER");
showvar("HTTP_X_SERVER_HOSTNAME");
showvar("PROXY_HOST");
showvar("PROXY_PORT");
showvar("PROXY_REQUEST");
showvar("HTTP_CLIENT_IP");
showvar("HTTP_PRAGMA");
```

Can anybody get me pointed in the right direction? Atleast show me how to return one variable. Thanks I have searched everywhere

答:
Just use Request.ServerVariables(VariableName)

Example Request.ServerVariables("LOGON_USER")

Body:
I am having trouble getting server variables remotely in VB .Net I need to basically mimic this PHP Function.

function showvar($string)
{
 if(isset($_SERVER[$string]))
 {
  echo "$string: ".rawurldecode($_SERVER[$string])."\r\n";
 }
}

/*normal vars*/
showvar("HTTP_ACCEPT");
showvar("HTTP_ACCEPT_ENCODING");
showvar("HTTP_ACCEPT_LANGUAGE");
showvar("HTTP_ACCEPT_CHARSET");
showvar("HTTP_HOST");
showvar("HTTP_KEEP_ALIVE");
showvar("HTTP_COOKIE");
showvar("HTTP_UA_CPU");
showvar("HTTP_REFERER");

/*important vars*/
showvar("HTTP_USER_AGENT");
showvar("REMOTE_ADDR");
showvar("REMOTE_HOST");
showvar("HTTP_CONNECTION");
showvar("HTTP_X_FORWARDED_FOR");
showvar("HTTP_FORWARDED");
showvar("HTTP_VIA");
showvar("KEEP_ALIVE");
showvar("HTTP_MAX_FORWARDS");
showvar("MAX_FORWARDS");
showvar("HTTP_CACHE_CONTROL");
showvar("HTTP_PROXY_CONNECTION");
showvar("HTTP_X_BLUECOAT_VIA");
showvar("HTTP_PC_REMOTE_ADDR");
showvar("HTTP_PROXY___________");
showvar("HTTP_PROXY____");
showvar("HTTP_X_FWD_IP_ADDR");
showvar("HTTP_X_HOST");
showvar("HTTP_X_REFERER");
showvar("HTTP_X_SERVER_HOSTNAME");
showvar("PROXY_HOST");
showvar("PROXY_PORT");
showvar("PROXY_REQUEST");
showvar("HTTP_CLIENT_IP");
showvar("HTTP_PRAGMA");

Can anybody get me pointed in the right direction? Atleast show me how to return one variable. Thanks I have searched everywhere


问:
How to make an asp dropdown list item unselectable
I have written following code to display drop down list :

```<code><asp:DropDownList AutoPostBack="True" ID="ddlCities" runat="server" class="form-control input-sm" placeholder="" TabIndex="5">
       <asp:ListItem>Select City</asp:ListItem>
       <asp:ListItem value="3">Ahmedabad (All) ---------------</asp:ListItem>
       <asp:ListItem value="3_3004">    Ahmedabad East</asp:ListItem>
       <asp:ListItem value="3_3005">    Ahmedabad West</asp:ListItem>
       <asp:ListItem value="3_3006">    Ahmedabad-Bopal and Surroundings</asp:ListItem>
       <asp:ListItem value="3_3007">    Ahmedabad-Gandhinagar</asp:ListItem>
       <asp:ListItem value="3_3008">    Ahmedabad-Sabarmati and Surroundings</asp:ListItem>
       <asp:ListItem value="3_3009">    Ahmedabad-SG Highway and Surroundings</asp:ListItem>
</asp:DropDownList>
</code>```

I want to make following item inside dropdown unselectable :

```<code><asp:ListItem value="3">Ahmedabad (All) ---------------</asp:ListItem>
</code>```

Note : I CAN'T USE OPTGROUP!!!!

and i don't want to hide it. it will be shown in dropdown, but user can't select this item.

I have tried adding 'disabled' attribute, but it hides that item.

i have also tried :

```<code>ddlCities.Items[1].Attributes.Add("Style", "cursor:not-allowed");
</code>```

It doesn't allow cursor, but still user can select this item, is there any other way to make this particular item unselectable??

答:
I think you're looking for something like this. Please see if it can help you.

[Update]
just looked back to your post and understand you cannot use OPTGROUP. May i know the reason? as your requirement needs this option.

Body:
I have written following code to display drop down list :

<asp:DropDownList AutoPostBack="True" ID="ddlCities" runat="server" class="form-control input-sm" placeholder="" TabIndex="5">
       <asp:ListItem>Select City</asp:ListItem>
       <asp:ListItem value="3">Ahmedabad (All) ---------------</asp:ListItem>
       <asp:ListItem value="3_3004">    Ahmedabad East</asp:ListItem>
       <asp:ListItem value="3_3005">    Ahmedabad West</asp:ListItem>
       <asp:ListItem value="3_3006">    Ahmedabad-Bopal and Surroundings</asp:ListItem>
       <asp:ListItem value="3_3007">    Ahmedabad-Gandhinagar</asp:ListItem>
       <asp:ListItem value="3_3008">    Ahmedabad-Sabarmati and Surroundings</asp:ListItem>
       <asp:ListItem value="3_3009">    Ahmedabad-SG Highway and Surroundings</asp:ListItem>
</asp:DropDownList>

I want to make following item inside dropdown unselectable :

<asp:ListItem value="3">Ahmedabad (All) ---------------</asp:ListItem>

Note : I CAN'T USE OPTGROUP!!!!

and i don't want to hide it. it will be shown in dropdown, but user can't select this item.

I have tried adding 'disabled' attribute, but it hides that item.

i have also tried :

ddlCities.Items[1].Attributes.Add("Style", "cursor:not-allowed");

It doesn't allow cursor, but still user can select this item, is there any other way to make this particular item unselectable??


问:
Google cloud vision- get JSON error response from OCR request
I'm new at using google cloud API so please forgive me if I ask any silly question. I want to try develop android app by Xamarin c# to do OCR for Thai language, so my idea is to  and I want to get OCR result from my photo.
This's my json request

```<code>{"requests": [
{"image":{"content":"3QGzdykwB2MZPcpx...."},
"imageContext": {"languageHints":["th"]},
"features": [{"type":"DOCUMENT_TEXT_DETECTION"}]}]}
</code>```

But the result that I got is

```<code>"error": {
"code": 14,
"message": "Service temporarily unavailable. Error processing features."}
</code>```

What wrong with this? Anyone please give some suggestion. Thank you.

答:
Since you have not provided the source code,let me assume that you are using the GoogleCloudPlatform/java-docs-samples

The main reason for the above exception is that the face annotations in the below code is null. You can just update the following code as your requirement

```<code>if (response.getFaceAnnotations() == null) {
  throw new IOException(
      response.getError() != null
          ? response.getError().getMessage()
          : "Unknown error getting image annotations");
}
</code>```

Body:
I'm new at using google cloud API so please forgive me if I ask any silly question. I want to try develop android app by Xamarin c# to do OCR for Thai language, so my idea is to  and I want to get OCR result from my photo.
This's my json request

{"requests": [
{"image":{"content":"3QGzdykwB2MZPcpx...."},
"imageContext": {"languageHints":["th"]},
"features": [{"type":"DOCUMENT_TEXT_DETECTION"}]}]}

But the result that I got is

"error": {
"code": 14,
"message": "Service temporarily unavailable. Error processing features."}

What wrong with this? Anyone please give some suggestion. Thank you.

Body:
Since you have not provided the source code,let me assume that you are using the GoogleCloudPlatform/java-docs-samples

The main reason for the above exception is that the face annotations in the below code is null. You can just update the following code as your requirement

if (response.getFaceAnnotations() == null) {
  throw new IOException(
      response.getError() != null
          ? response.getError().getMessage()
          : "Unknown error getting image annotations");
}


问:
Error with OpenWeatherMap with ionic 2 Production build
I am trying to build an ionic2 app using angular 2 and TS, the build is in production mode and i get this error.

```<code>Error: Unexpected value 'OpenWeatherMapModule in E:/Stage/VLT
        APP/com.vlt.app/node_modules/ionic-
openweathermap/dist/openweathermap.module.d.ts' imported by the module
        'AppModule in E:/Stage/VLT APP/com.vlt.app/src/app/app.module.ts'.
Please add a @NgModule annotation.
Error: Unexpected value 'OpenWeatherMapModule in E:/Stage/VLT
APP/com.vlt.app/node_modules/ionic-
openweathermap/dist/openweathermap.module.d.ts' imported by the module
'AppModule in E:/
Stage/VLT APP/com.vlt.app/src/app/app.module.ts'. Please add a @NgModule
annotation.
</code>```

I am using OpenWeatherMap in my app and i don't know why i only get this Error in Production mode. Besides i don't think i need to edit any files in node modules library directory.

EDIT

this is my imports array in app.module.ts

```<code>@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    BestOffers,
    excursion,
    hotel,
    circuit,
    MapPage,
    NosExcursion,
    WeatherPage,
    NosHotel,
    NosCircuit,
    CircuitPage,
    ExcursionPage,
    ImageModal,
    SearchModal,
    ResultModal,
    PromoPage,
    HotelPage,
    GalleryPage,
    GalleryModal,
    ZoomableImage,
    PopoverPage,
    ReservationModal,
    CurrencyChange,
CircuitReservationModal,
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    IonicStorageModule.forRoot(),
    SuperTabsModule.forRoot(),
    AgmCoreModule.forRoot({
      apiKey: '**********'
    }),
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [Http]
      }
    }),
    IonicImageViewerModule,
    OpenWeatherMapModule,
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    BestOffers,
    excursion,
    hotel,
    circuit,
    MapPage,
    NosExcursion,
    WeatherPage,
    NosHotel,
    NosCircuit,
    CircuitPage,
    HotelPage,
    ExcursionPage,
    ImageModal,
    SearchModal,
    ResultModal,
    PromoPage,
    GalleryPage,
    GalleryModal,
    PopoverPage,
    ReservationModal,
    CurrencyChange,
    CircuitReservationModal,
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    SQLite,
    HotelPage,
    InAppBrowser,
  ]
})
export class AppModule {}
export function createTranslateLoader(http: Http) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
    }
</code>```

So any help ?

答:
After testing for a while, I got the same issue as yours. I think it is the problem with openweathermap Module. The file structure in this module seem not correct.

So In stead of installing this module, I download the source code and include in my ionic sample as below:

home.html

```<code><ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <openweathermap [options]="options"></openweathermap>
</ion-content>
</code>```

home.ts

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  options: any = {};

  constructor(public navCtrl: NavController) {
    this.options = {
          apikey: "6ff5deed8aaa46c2fdcb1bfddd2d4ecc",
          city: { "name": ["Phnom Penh"] },
          unitFormat: "metric",
          lang: "en"
        }
  }
}
</code>```

The source code of this example can be found here: ionic3-openweathermap

I Hope this could help you, Thanks :)

EDIT

I tested in Android production and it work fine

Body:
I am trying to build an ionic2 app using angular 2 and TS, the build is in production mode and i get this error.

Error: Unexpected value 'OpenWeatherMapModule in E:/Stage/VLT
        APP/com.vlt.app/node_modules/ionic-
openweathermap/dist/openweathermap.module.d.ts' imported by the module
        'AppModule in E:/Stage/VLT APP/com.vlt.app/src/app/app.module.ts'.
Please add a @NgModule annotation.
Error: Unexpected value 'OpenWeatherMapModule in E:/Stage/VLT
APP/com.vlt.app/node_modules/ionic-
openweathermap/dist/openweathermap.module.d.ts' imported by the module
'AppModule in E:/
Stage/VLT APP/com.vlt.app/src/app/app.module.ts'. Please add a @NgModule
annotation.

I am using OpenWeatherMap in my app and i don't know why i only get this Error in Production mode. Besides i don't think i need to edit any files in node modules library directory.

EDIT

this is my imports array in app.module.ts

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    BestOffers,
    excursion,
    hotel,
    circuit,
    MapPage,
    NosExcursion,
    WeatherPage,
    NosHotel,
    NosCircuit,
    CircuitPage,
    ExcursionPage,
    ImageModal,
    SearchModal,
    ResultModal,
    PromoPage,
    HotelPage,
    GalleryPage,
    GalleryModal,
    ZoomableImage,
    PopoverPage,
    ReservationModal,
    CurrencyChange,
CircuitReservationModal,
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    IonicStorageModule.forRoot(),
    SuperTabsModule.forRoot(),
    AgmCoreModule.forRoot({
      apiKey: '**********'
    }),
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [Http]
      }
    }),
    IonicImageViewerModule,
    OpenWeatherMapModule,
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    BestOffers,
    excursion,
    hotel,
    circuit,
    MapPage,
    NosExcursion,
    WeatherPage,
    NosHotel,
    NosCircuit,
    CircuitPage,
    HotelPage,
    ExcursionPage,
    ImageModal,
    SearchModal,
    ResultModal,
    PromoPage,
    GalleryPage,
    GalleryModal,
    PopoverPage,
    ReservationModal,
    CurrencyChange,
    CircuitReservationModal,
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    SQLite,
    HotelPage,
    InAppBrowser,
  ]
})
export class AppModule {}
export function createTranslateLoader(http: Http) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
    }

So any help ?

Body:
After testing for a while, I got the same issue as yours. I think it is the problem with openweathermap Module. The file structure in this module seem not correct.

So In stead of installing this module, I download the source code and include in my ionic sample as below:

home.html

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <openweathermap [options]="options"></openweathermap>
</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  options: any = {};

  constructor(public navCtrl: NavController) {
    this.options = {
          apikey: "6ff5deed8aaa46c2fdcb1bfddd2d4ecc",
          city: { "name": ["Phnom Penh"] },
          unitFormat: "metric",
          lang: "en"
        }
  }
}

The source code of this example can be found here: ionic3-openweathermap

I Hope this could help you, Thanks :)

EDIT

I tested in Android production and it work fine


问:
Excel - Count unique values that match ID, optimized for 100,000+ cases
in reference to the excel screen capture below, I'm looking for a formula solution that counts the number of unique values in Column B (Colour) for each ID number in Column A.

I've imputed the desired result in Column C. So, for instance, ID 1 (A2) has only one unique colour, Grey (B2), which would return a 1 in C2. ID 2 has only one unique colour, yellow (B3, B4), and returns 1 in C3 and C4. ID 3, has two unique colours, Blue and Purple, thus returning a 2 in C5 through C8. Etc.

Because this will be run for close to 100,000 rows, many of the index and/or match based solutions I've come across take way to long to compute. I have found that the ID values, which are all in ascending order, can be used to speed things up by starting the formula with =IF(A2=A1, or something like this. Thanks in advance to anyone with some ideas about how to solve this with a lean formula.

Note: I am working with files that also have close to 100 columns. A solution that doesn't require helper columns would be ideal.

EDIT/ADDITION: In my main data file, there are instances of blank cells in column B. Is there a way to ignore the blank cells when counting for column C results?

答:
Ok, I solved your problem using this array formula:

```<code>=SUM(IF(FREQUENCY(IF($A$2:$A$21=A2,MATCH($B$2:$B$21,$B$2:$B$21,0),""),MATCH($B$2:$B$21,$B$2:$B$21,0))>0,1))
</code>```

Put this formula into cell C2 and press CTRL+SHIFT+ENTER, then pull formula down. If any questions, comment below

Body:
Ok, I solved your problem using this array formula:

=SUM(IF(FREQUENCY(IF($A$2:$A$21=A2,MATCH($B$2:$B$21,$B$2:$B$21,0),""),MATCH($B$2:$B$21,$B$2:$B$21,0))>0,1))

Put this formula into cell C2 and press CTRL+SHIFT+ENTER, then pull formula down. If any questions, comment below


问:
Dexie : How to add to array in nested object
I am using Dexie IndexedDB wrapper and I am trying to add an object to an existing array which in inside a nested object. The structure looks similar to below

```<code>{
  Name : 'John',
  age : 33,
  tags : {
     skill: [{
         first: '.NET',
         second: 'JAVA',
         third: [{special1:'sleep'},{special2:'eat'}]
     }]
  }
}
</code>```

I have tried many way to push object special3:'run' to skill.third but without success. My last attempt looked something like this

```<code>    const pathObject = {};
    const fullPath = 'result.tags.skill[3].third';
    pathObject[fullPath] = {special3:'run'};
    db.inspections.update(id, pathObject);
</code>```

The object is added outside and not inside the array 'third' something like below

```<code>{
  Name : 'John',
  age : 33,
  tags : {
     skill: [{
         first: '.NET',
         second: 'JAVA',
         third: [{special1:'sleep'},{special2:'eat'}]
     }]
     skill[3]: {
         third: {special3:'run'}
     }
  }
}
</code>```

I wish to know if there a way to add to arrays in nested object using Dexie if not is there a way to achieve this using indexeddb. Help is appreciated as problem is been holding back progress

答:
The easiest is to use Collection.modify() with a callback function to mutate your model:

```<code>db.inspections.where('id').equals(id).modify(x =>
    x.tags.skill[0].third.push({special3:'run'}) );
</code>```

If you want to use a keypath containing array items, it is also possible, as arrays can be looked at as objects with numeric keys:

```<code>db.inspections.update(id, {"tags.skill.0.third.3": {special3:'run'}});
</code>```

Body:
I am using Dexie IndexedDB wrapper and I am trying to add an object to an existing array which in inside a nested object. The structure looks similar to below

{
  Name : 'John',
  age : 33,
  tags : {
     skill: [{
         first: '.NET',
         second: 'JAVA',
         third: [{special1:'sleep'},{special2:'eat'}]
     }]
  }
}

I have tried many way to push object special3:'run' to skill.third but without success. My last attempt looked something like this

    const pathObject = {};
    const fullPath = 'result.tags.skill[3].third';
    pathObject[fullPath] = {special3:'run'};
    db.inspections.update(id, pathObject);

The object is added outside and not inside the array 'third' something like below

{
  Name : 'John',
  age : 33,
  tags : {
     skill: [{
         first: '.NET',
         second: 'JAVA',
         third: [{special1:'sleep'},{special2:'eat'}]
     }]
     skill[3]: {
         third: {special3:'run'}
     }
  }
}

I wish to know if there a way to add to arrays in nested object using Dexie if not is there a way to achieve this using indexeddb. Help is appreciated as problem is been holding back progress

Body:
The easiest is to use Collection.modify() with a callback function to mutate your model:

db.inspections.where('id').equals(id).modify(x =>
    x.tags.skill[0].third.push({special3:'run'}) );

If you want to use a keypath containing array items, it is also possible, as arrays can be looked at as objects with numeric keys:

db.inspections.update(id, {"tags.skill.0.third.3": {special3:'run'}});