问:
Rails Form Input does not save, becomes blank after I submit
Rails beginner here!

I made a form to edit a user's information and I am trying to edit the user's full name, which is initially blank. However, when I press submit, the full name field becomes blank and the form tells me that my changes cannot be saved because the full name cannot be blank. I have seen people with the same problem, but they had this problem because they had the gem, "protected_attributes".

This is my server output:

```<code>    Started PATCH "/users/9b62e326-ca9f-47b9-9e91-256e42ca52fc"
    for 127.0.0.1 at 2019-05-26 21:30:22 -0400
    Processing by UsersController#update as HTML
    Parameters: {"utf8"=>"✓","authenticity_token"=>"G8zS2fWVdOBAc==", "user"=>{"full_name"=>"",
    "email"=>"email@gmail.com"}, "commit"=>"Update User",
    "id"=>"9b62e326-ca9f-47b9-9e91-256e42ca52fc"}
    User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE
    "users"."slug" = ? LIMIT ?  [["slug", "9b62e326-ca9f-47b9-
    9e91-256e42ca52fc"], ["LIMIT", 1]]
    ↳ app/controllers/users_controller.rb:57 (0.1ms)  begin transaction
    ↳ app/controllers/users_controller.rb:37
   (0.1ms)  rollback transaction
   ↳ app/controllers/users_controller.rb:37
   Rendering users/edit.html.erb within layouts/application
   Rendered users/_form.html.erb (6.6ms)
   Rendered users/edit.html.erb within layouts/application
   (12.7ms)
   Category Load (0.3ms)  SELECT "categories".* FROM "categories"
   ↳ app/views/layouts/application.html.erb:31
   User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE
   "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1],
   ["LIMIT", 1]]
   ↳ app/views/layouts/application.html.erb:38
   Completed 200 OK in 137ms (Views: 126.5ms | ActiveRecord: 1.4ms)
</code>```

Here is my form code:

```<code>    <%= form_for @user, html: { multipart: true } do |f| %>

    <% if @user.errors.any? %>
    <h2><%= pluralize(@user.errors.count, "error")%> prevented
    this post from saving:</h2>
    <ul>
    <% @user.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
    <% end %>
    </ul>
    <% end %>
    <%= f.label :full_name, "Full Name" %>
    <%= f.text_field :full_name %>

    <%= f.label "Upload profile picture" %><br><br />
    <%= f.file_field :profile %><br/><br/>
    <br>

   <%= f.label "Email (Will not be published)" %><br>
   <%= f.text_field :email %>

   <% @full = @user.full_name %>

   <%= f.hidden_field :full_name, :value => @full %>
</code>```

User controller:

```<code>    class UsersController < ApplicationController
    before_action :find_user, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, only: [:show]

      def show
        @user = User.find(params[:id])
        @user_posts = @user.posts.all.order("created_at desc")
        @posts = Post.all.order("created_at desc")
      end

     def index
        @users = User.all.order("created_at desc")
     end

     def edit
     end

     def new
        @user = User.new(:email => 'test@example.com', :password =>
        'password', :password_confirmation => 'password', :full_name
        => 'Jane Doe')
        @user.save
     end

    def create
        @user = User.new(user_params)
        @user.save

        if @user.save
            redirect_to @user, notice: "Your changes were successfully
             saved!"
        else
            render 'new', notice: "Oh no! Your changes were not able
            to be saved!"
        end
        end

        def update
          if @user.update_attributes(user_params)
          redirect_to @user, notice: "Your changes were saved!"
          else
             render 'edit'
          end
        end

        def destroy
           @user.destroy
           redirect_to users_path
        end

    private

    def user_params
       params.require(:user).permit(:email, :password,
       :password_confirmation, :full_name, :slug)

    end

    def find_user
      @user = User.friendly.find(params[:id])
    end
    end
</code>```

User.rb

```<code>    class User < ApplicationRecord
    extend FriendlyId
    friendly_id :full_name, use: :slugged

     devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :validatable
     has_many :posts

     validates :full_name, presence: true

     validates :email, presence: true

     def should_generate_new_friendly_id?
     slug.blank? || full_name_changed?
     end
     end
</code>```

I used the same form format for my post model as well, so i'm not sure why there is an issue.
Any help is appreciated, thank you!

答:
You should not have text_field and hidden_field for the same attribute in the same form

you can remove

```<code><% @full = @user.full_name %>
<%= f.hidden_field :full_name, :value => @full %>
</code>```

in your form you already have

```<code><%= f.label :full_name, "Full Name" %>
 <%= f.text_field :full_name %>
</code>```

Body:
Rails beginner here!

I made a form to edit a user's information and I am trying to edit the user's full name, which is initially blank. However, when I press submit, the full name field becomes blank and the form tells me that my changes cannot be saved because the full name cannot be blank. I have seen people with the same problem, but they had this problem because they had the gem, "protected_attributes".

This is my server output:

    Started PATCH "/users/9b62e326-ca9f-47b9-9e91-256e42ca52fc"
    for 127.0.0.1 at 2019-05-26 21:30:22 -0400
    Processing by UsersController#update as HTML
    Parameters: {"utf8"=>"✓","authenticity_token"=>"G8zS2fWVdOBAc==", "user"=>{"full_name"=>"",
    "email"=>"email@gmail.com"}, "commit"=>"Update User",
    "id"=>"9b62e326-ca9f-47b9-9e91-256e42ca52fc"}
    User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE
    "users"."slug" = ? LIMIT ?  [["slug", "9b62e326-ca9f-47b9-
    9e91-256e42ca52fc"], ["LIMIT", 1]]
    ↳ app/controllers/users_controller.rb:57 (0.1ms)  begin transaction
    ↳ app/controllers/users_controller.rb:37
   (0.1ms)  rollback transaction
   ↳ app/controllers/users_controller.rb:37
   Rendering users/edit.html.erb within layouts/application
   Rendered users/_form.html.erb (6.6ms)
   Rendered users/edit.html.erb within layouts/application
   (12.7ms)
   Category Load (0.3ms)  SELECT "categories".* FROM "categories"
   ↳ app/views/layouts/application.html.erb:31
   User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE
   "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1],
   ["LIMIT", 1]]
   ↳ app/views/layouts/application.html.erb:38
   Completed 200 OK in 137ms (Views: 126.5ms | ActiveRecord: 1.4ms)

Here is my form code:

    <%= form_for @user, html: { multipart: true } do |f| %>

    <% if @user.errors.any? %>

<%= pluralize(@user.errors.count, "error")%> prevented
    this post from saving:

    <% @user.errors.full_messages.each do |msg| %>

<%= msg %>

    <% end %>

    <% end %>
    <%= f.label :full_name, "Full Name" %>
    <%= f.text_field :full_name %>

    <%= f.label "Upload profile picture" %>

    <%= f.file_field :profile %>

   <%= f.label "Email (Will not be published)" %>

   <%= f.text_field :email %>

   <% @full = @user.full_name %>

   <%= f.hidden_field :full_name, :value => @full %>

User controller:

    class UsersController < ApplicationController
    before_action :find_user, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, only: [:show]

      def show
        @user = User.find(params[:id])
        @user_posts = @user.posts.all.order("created_at desc")
        @posts = Post.all.order("created_at desc")
      end

     def index
        @users = User.all.order("created_at desc")
     end

     def edit
     end

     def new
        @user = User.new(:email => 'test@example.com', :password =>
        'password', :password_confirmation => 'password', :full_name
        => 'Jane Doe')
        @user.save
     end

    def create
        @user = User.new(user_params)
        @user.save

        if @user.save
            redirect_to @user, notice: "Your changes were successfully
             saved!"
        else
            render 'new', notice: "Oh no! Your changes were not able
            to be saved!"
        end
        end

        def update
          if @user.update_attributes(user_params)
          redirect_to @user, notice: "Your changes were saved!"
          else
             render 'edit'
          end
        end

        def destroy
           @user.destroy
           redirect_to users_path
        end

    private

    def user_params
       params.require(:user).permit(:email, :password,
       :password_confirmation, :full_name, :slug)

    end

    def find_user
      @user = User.friendly.find(params[:id])
    end
    end

User.rb

    class User < ApplicationRecord
    extend FriendlyId
    friendly_id :full_name, use: :slugged

     devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :validatable
     has_many :posts

     validates :full_name, presence: true

     validates :email, presence: true

     def should_generate_new_friendly_id?
     slug.blank? || full_name_changed?
     end
     end

I used the same form format for my post model as well, so i'm not sure why there is an issue.
Any help is appreciated, thank you!

Body:
You should not have text_field and hidden_field for the same attribute in the same form

you can remove

<% @full = @user.full_name %>
<%= f.hidden_field :full_name, :value => @full %>

in your form you already have

<%= f.label :full_name, "Full Name" %>
 <%= f.text_field :full_name %>


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: Multi-conditional mutate

Body:
I have a data frame that requires conditional recoding of a column based on the date listed in certain rows for each subset of IDs. I am trying to figure out how to best achieve this using the mutate function in dplyr. Suggestions and alternate solutions are welcome, but I would like to avoid using for loops.

I know how to write a really verbose and inefficient for loop that would solve this problem, but would like to know how to do it more efficiently.

The sample data frame:

df<-data.frame(ID = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2),
               date = as.Date(c("2016-02-01","2016-02-01","2016-02-01","2016-03-21", "2016-03-21", "2016-03-21", "2016-10-05", "2016-10-05", "2016-10-05", "2016-10-05", "2016-03-01","2016-03-01","2016-03-01","2016-04-21", "2016-04-21", "2016-04-21", "2016-11-05", "2016-11-05", "2016-11-05", "2016-11-05")),
               trial = c(NA, NA, NA, 1, 1, 1, NA, NA, NA, NA, NA, NA, NA, 1, 1, 1, NA, NA, NA, NA)

My pseudo code - the second logical argument in the first two case_when statements is where I am stuck.

df%>%
  group_by(ID)%>%
  mutate(results = case_when(
     is.na(trial) & date < date where trial = 1 ~ 0,
     is.na(trial) & date > date where trial = 1 ~ 2,
     trial == trial
  ))

The expected result being:

data.frame(ID = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2),
               date = as.Date(c("2016-02-01","2016-02-01","2016-02-01","2016-03-21", "2016-03-21", "2016-03-21", "2016-10-05", "2016-10-05", "2016-10-05", "2016-10-05", "2016-03-01","2016-03-01","2016-03-01","2016-04-21", "2016-04-21", "2016-04-21", "2016-11-05", "2016-11-05", "2016-11-05", "2016-11-05")),
               trial = c(0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2)
)

Body:
Converting your pseudo code to code we can use which.max(trial == 1) to get first occurrence where trial = 1 for each group. This also assumes that there would be at least one entry of 1 in trial for each ID.

library(dplyr)

df %>%
  group_by(ID) %>%
  mutate(trial = case_when(is.na(trial) & date < date[which.max(trial == 1)] ~ 0,
                             is.na(trial) & date > date[which.max(trial == 1)] ~ 2,
                             TRUE ~ trial))

#      ID date       trial
#    <dbl> <date>     <dbl>
# 1     1 2016-02-01     0
# 2     1 2016-02-01     0
# 3     1 2016-02-01     0
# 4     1 2016-03-21     1
# 5     1 2016-03-21     1
# 6     1 2016-03-21     1
# 7     1 2016-10-05     2
# 8     1 2016-10-05     2
# 9     1 2016-10-05     2
#10     1 2016-10-05     2
#11     2 2016-03-01     0
#12     2 2016-03-01     0
#13     2 2016-03-01     0
#14     2 2016-04-21     1
#15     2 2016-04-21     1
#16     2 2016-04-21     1
#17     2 2016-11-05     2
#18     2 2016-11-05     2
#19     2 2016-11-05     2
#20     2 2016-11-05     2


问:
How to align 2 forms in the same line?
I'm trying to make the login view of a web page, this login view have two forms (one for register and another for login) and I want to align them and put them in the same line.

At first I've tried to use a table in order to achieve this, but this was unsuccessful, so I used some bootstrap form groups (rows and cols) but I was unsuccessful as well, in the end I managed to put them in the same line using the float attribute, but the result that I got it wasn't good enough.

            Inicio
            Nuevas Adiciones

                <button class="dropbtn">Categoría

                </button>

                    Punk
                    Rock
                    Emo

                <button class="dropbtn">Tipo de Material

                </button>

                    Vinilos
                    Discos Compactos
                    Casetes

                    Iniciar Sesión

    <form class="bord" style="float: left;">
        <legend>Crear Cuenta</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

    <form class="bord" style="float: right;">
        <legend>Registrarse</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

Contacto

Email: pedidos@vinilos.pe

Teléfono: 3291177

Vinilos.Pe © 2019 Derechos Reservados

```

<pre class="lang-css prettyprint-override"><code>
/* THIS IS MY CSS */

.bord {
    display: block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
  }
</code>```

I was trying to achieve the look of this mockup, but instead for some reason the footer comes up and it looks like this.

答:
You can try this. Hope this will help.

*{
 margin: 0px;
 padding: 0px;
}
.form{
 width: 100%;
 margin: 0 auto;
}
.bord {
    display: inline-block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
    width: 45%;
  }
  footer{;
    display:inline-block;
    width:100%;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <header>
        <img src="rsc/logo.png" class="center">

        <div class="navbar1">
            Inicio
            Nuevas Adiciones
            <div class="dropdown1">
                <button class="dropbtn">Categoría
                    <i class="fa fa-caret-down"></i>
                </button>
                <div class="dropdown1-content">
                    Punk
                    Rock
                    Emo
                </div>
            </div>
            <div class="dropdown1">
                <button class="dropbtn">Tipo de Material
                    <i class="fa fa-caret-down"></i>
                </button>
                <div class="dropdown1-content">
                    Vinilos
                    Discos Compactos
                    Casetes
                </div>
            </div>
            <div class="inlogin">
                    Iniciar Sesión <i class="fa fa-sign-in"></i>
            </div>
        </div>
    </header>

<div class="form">
    <form class="bord" style="">
        <legend>Crear Cuenta</legend>
        <div class="form-group">
            <label for="formGroupExampleInput">Example label</label>
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
        </div>
        <div class="form-group">
            <label for="formGroupExampleInput2">Another label</label>
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
        </div>
    </form>

    <form class="bord" style="">
        <legend>Registrarse</legend>
        <div class="form-group">
            <label for="formGroupExampleInput">Example label</label>
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
        </div>
        <div class="form-group">
            <label for="formGroupExampleInput2">Another label</label>
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
        </div>
    </form>
</div>
    <footer style="text-align: center;">
        <p><strong>Contacto</strong></p>
        <p>Email: pedidos@vinilos.pe</p>
        <p>Teléfono: 3291177</p>
        <p><i class="fa fa-facebook-square" style="font-size:40px;color: #3b5998;"></i></p>
        <p>Vinilos.Pe © 2019 Derechos Reservados</p>
    </footer></code>```

Title: How to align 2 forms in the same line?

Body:
I'm trying to make the login view of a web page, this login view have two forms (one for register and another for login) and I want to align them and put them in the same line.

At first I've tried to use a table in order to achieve this, but this was unsuccessful, so I used some bootstrap form groups (rows and cols) but I was unsuccessful as well, in the end I managed to put them in the same line using the float attribute, but the result that I got it wasn't good enough.

            Inicio
            Nuevas Adiciones

                <button class="dropbtn">Categoría

                </button>

                    Punk
                    Rock
                    Emo

                <button class="dropbtn">Tipo de Material

                </button>

                    Vinilos
                    Discos Compactos
                    Casetes

                    Iniciar Sesión

    <form class="bord" style="float: left;">
        <legend>Crear Cuenta</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

    <form class="bord" style="float: right;">
        <legend>Registrarse</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

Contacto

Email: pedidos@vinilos.pe

Teléfono: 3291177

Vinilos.Pe © 2019 Derechos Reservados

/* THIS IS MY CSS */

.bord {
    display: block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
  }

I was trying to achieve the look of this mockup, but instead for some reason the footer comes up and it looks like this.

Body:
You can try this. Hope this will help.

*{
 margin: 0px;
 padding: 0px;
}
.form{
 width: 100%;
 margin: 0 auto;
}
.bord {
    display: inline-block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
    width: 45%;
  }
  footer{;
    display:inline-block;
    width:100%;
  }

    <header>
        <a href="Index.html"><img src="rsc/logo.png" class="center"></a>

        <div class="navbar1">
            <a href="#inicio">Inicio</a>
            <a href="#nuevasAdiciones">Nuevas Adiciones</a>
            <div class="dropdown1">
                <button class="dropbtn">Categoría
                    <i class="fa fa-caret-down"></i>
                </button>
                <div class="dropdown1-content">
                    <a href="#">Punk</a>
                    <a href="#">Rock</a>
                    <a href="#">Emo</a>
                </div>
            </div>
            <div class="dropdown1">
                <button class="dropbtn">Tipo de Material
                    <i class="fa fa-caret-down"></i>
                </button>
                <div class="dropdown1-content">
                    <a href="#">Vinilos</a>
                    <a href="#">Discos Compactos</a>
                    <a href="#">Casetes</a>
                </div>
            </div>
            <div class="inlogin">
                    <a href="#login">Iniciar Sesión <i class="fa fa-sign-in"></i></a>
            </div>
        </div>
    </header>

<div class="form">
    <form class="bord" style="">
        <legend>Crear Cuenta</legend>
        <div class="form-group">
            <label for="formGroupExampleInput">Example label</label>
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
        </div>
        <div class="form-group">
            <label for="formGroupExampleInput2">Another label</label>
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
        </div>
    </form>

    <form class="bord" style="">
        <legend>Registrarse</legend>
        <div class="form-group">
            <label for="formGroupExampleInput">Example label</label>
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
        </div>
        <div class="form-group">
            <label for="formGroupExampleInput2">Another label</label>
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
        </div>
    </form>
</div>
    <footer style="text-align: center;">
        <p><strong>Contacto</strong></p>
        <p>Email: <a href="mailto:pedidos@vinilos.pe">pedidos@vinilos.pe</a></p>
        <p>Teléfono: 3291177</p>
        <p><a href="https://www.facebook.com/vinilos.pe/" target="_blank"><i class="fa fa-facebook-square" style="font-size:40px;color: #3b5998;"></i></a></p>
        <p>Vinilos.Pe &copy; 2019 Derechos Reservados</p>
    </footer>


问:
EF Code First Parent-Child insertions with identity columns
i have the following model.

```<code>class Parent
{
    int ParentId (identity column) { get; set; }
    string ParentName { get; set; }
    virtual ICollection<Child> Children { get; set; }
}

class Child
{
    int ChildId (identity column) { get; set; }
    string ChildName { get; set; }
    int ParentID { get ; set; } //foreign key to Parent(ParentID)
}
</code>```

How do i insert few rows to my parent and child in single transaction? Basically i want to get the identity generated on the parent(say i insert a row in parent) and insert child rows with that value?
How this can be achieved using Code First?

答:
You shouldn't worry about what value the Id of Parent will get in order to insert Child rows. This should be enough:

```<code>var parent = new Parent
{
    // fill other properties

    Children = new List<Child>()
}

parent.Children.add(new Child { /*fill values */);

dbContext.Parents.Add(parent); // whatever your context is named
dbContext.SaveChanges();
</code>```

For the record, the ID's will be assigned after calling SaveChanges(), so if you really need the ID before inserting a Child entity you can always call SaveChanges() twice.

Again, this shouldn't be necessary though.

By the way, I would recommend making the Foreign Key property from Child to Parent a navigation property, so the Child class would look like:

```<code>class Child
{
    public int ChildId { get; set; } // identity column
    public string ChildName { get; set; }
    public virtual Parent Parent { get ; set; } //foreign key to Parent
}
</code>```

That way you can always access the Child's parent directly without having to retrieve it explicitly from the database yourself (it will be lazy loaded).

ContentLicense: CC BY-SA 3.0

Body:
i have the following model.

class Parent
{
    int ParentId (identity column) { get; set; }
    string ParentName { get; set; }
    virtual ICollection<Child> Children { get; set; }
}

class Child
{
    int ChildId (identity column) { get; set; }
    string ChildName { get; set; }
    int ParentID { get ; set; } //foreign key to Parent(ParentID)
}

How do i insert few rows to my parent and child in single transaction? Basically i want to get the identity generated on the parent(say i insert a row in parent) and insert child rows with that value?
How this can be achieved using Code First?

Body:
You shouldn't worry about what value the Id of Parent will get in order to insert Child rows. This should be enough:

var parent = new Parent
{
    // fill other properties

    Children = new List<Child>()
}

parent.Children.add(new Child { /*fill values */);

dbContext.Parents.Add(parent); // whatever your context is named
dbContext.SaveChanges();

For the record, the ID's will be assigned after calling SaveChanges(), so if you really need the ID before inserting a Child entity you can always call SaveChanges() twice.

Again, this shouldn't be necessary though.

By the way, I would recommend making the Foreign Key property from Child to Parent a navigation property, so the Child class would look like:

class Child
{
    public int ChildId { get; set; } // identity column
    public string ChildName { get; set; }
    public virtual Parent Parent { get ; set; } //foreign key to Parent
}

That way you can always access the Child's parent directly without having to retrieve it explicitly from the database yourself (it will be lazy loaded).


问:
Keras Multi-layer Neural Network Accuracy
I've built a simplistic multi-layer NN using Keras with precipitation data in Australia.  The code takes 4 input columns: ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed'] and trains against the RainTomorrow output.

I've partitioned the data into training/test buckets, transformed all values into 0 <= n <= 1.  When I trying to run model.fit, my loss values steady at ~13.2, but my accuracy is always 0.0.  An example of logged fitting intervals are:

```<code>...
Epoch 37/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1274 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 38/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1457 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 39/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1315 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 40/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1797 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 41/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1844 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 42/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.2205 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 43/200
...
</code>```

How can I amend the following script, so my accuracy grows, and my predication output returns a value between 0 and 1 (0: no rain, 1: rain)?

```<code>import keras
import sklearn.model_selection
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler

labelencoder = LabelEncoder()

# read data, replace NaN with 0.0
csv_data = pd.read_csv('weatherAUS.csv', header=0)
csv_data = csv_data.replace(np.nan, 0.0, regex=True)

# Input/output columns scaled to 0<=n<=1
x = csv_data.loc[:, ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed']]
y = labelencoder.fit_transform(csv_data['RainTomorrow'])
scaler_x = MinMaxScaler(feature_range =(-1, 1))
x = scaler_x.fit_transform(x)
scaler_y = MinMaxScaler(feature_range =(-1, 1))
y = scaler_y.fit_transform([y])[0]

# Partitioned data for training/testing
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2)

# model
model = keras.models.Sequential()
model.add( keras.layers.normalization.BatchNormalization(input_shape=tuple([x_train.shape[1]])))
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.core.Dense(1,   activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=["accuracy"])

callback_early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto')

model.fit(x_train, y_train, batch_size=1024, epochs=200, validation_data=(x_test, y_test), verbose=1, callbacks=[callback_early_stopping])

y_test = model.predict(x_test.values)
</code>```

答:
Both the other answers can be used to address the fact that your network ouput is not in the same range as your y vector values. Either adjust your final layer to a tanh activation, or change the y-vector range to [0,1].

However, your network loss function and metric is defined for classification purposes, where as you are attempting regression (continuous values between [-1, 1]). The most common loss function and accuracy metric to use is the mean sqaured error, or mean absolute errtr. So I suggest you change the following:

```<code>model.compile(loss='mse', optimizer='rmsprop', metrics=['mse, 'mae'])
</code>```

Body:
I've built a simplistic multi-layer NN using Keras with precipitation data in Australia.  The code takes 4 input columns: ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed'] and trains against the RainTomorrow output.

I've partitioned the data into training/test buckets, transformed all values into 0 <= n <= 1.  When I trying to run model.fit, my loss values steady at ~13.2, but my accuracy is always 0.0.  An example of logged fitting intervals are:

...
Epoch 37/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1274 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 38/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1457 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 39/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1315 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 40/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1797 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 41/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1844 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 42/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.2205 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 43/200
...

How can I amend the following script, so my accuracy grows, and my predication output returns a value between 0 and 1 (0: no rain, 1: rain)?

import keras
import sklearn.model_selection
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler

labelencoder = LabelEncoder()

# read data, replace NaN with 0.0
csv_data = pd.read_csv('weatherAUS.csv', header=0)
csv_data = csv_data.replace(np.nan, 0.0, regex=True)

# Input/output columns scaled to 0<=n<=1
x = csv_data.loc[:, ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed']]
y = labelencoder.fit_transform(csv_data['RainTomorrow'])
scaler_x = MinMaxScaler(feature_range =(-1, 1))
x = scaler_x.fit_transform(x)
scaler_y = MinMaxScaler(feature_range =(-1, 1))
y = scaler_y.fit_transform([y])[0]

# Partitioned data for training/testing
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2)

# model
model = keras.models.Sequential()
model.add( keras.layers.normalization.BatchNormalization(input_shape=tuple([x_train.shape[1]])))
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.core.Dense(1,   activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=["accuracy"])

callback_early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto')

model.fit(x_train, y_train, batch_size=1024, epochs=200, validation_data=(x_test, y_test), verbose=1, callbacks=[callback_early_stopping])

y_test = model.predict(x_test.values)

Body:
Both the other answers can be used to address the fact that your network ouput is not in the same range as your y vector values. Either adjust your final layer to a tanh activation, or change the y-vector range to [0,1].

However, your network loss function and metric is defined for classification purposes, where as you are attempting regression (continuous values between [-1, 1]). The most common loss function and accuracy metric to use is the mean sqaured error, or mean absolute errtr. So I suggest you change the following:

model.compile(loss='mse', optimizer='rmsprop', metrics=['mse, 'mae'])


问:
Getting image path from MongoDB using handlebars
I stored the image path in MongoDB but when I'm trying to get the image path into the src attribute of the img tag, it keeps inserting apostrophes at the beginning and the end of the image path.

```<code><img src=“{{ this.img }}” alt="Alt text">
</code>```

Viewed from Chrome Dev Tools:

```<code><img src="'/img/thisisanimage.jpg'" alt="Alt text">
</code>```

Any reason why this might be happening?

答: you should use it like this:

Body:
I stored the image path in MongoDB but when I'm trying to get the image path into the src attribute of the img tag, it keeps inserting apostrophes at the beginning and the end of the image path.

Viewed from Chrome Dev Tools:

Any reason why this might be happening?

Body:
you should use it like this:
<img src="{{ img.src }}" alt="Image is broken" />


问:
Showing the intersection between two strings
I am trying to find the intersection between two strings. For example, if string one was my car is bad, and string two was my horse is good, it would return my is.
This is my code:

```<code>  public static string intersection2(string x1, string x2)
{
  string[] string1 = x1.Split(' ');
string[] string2 = x2.Split(' ');
string[] m = string1.Distinct();
 string[] n = string2.Distinct();
  string Test;
 var results = m.Intersect(n,StringComparer.OrdinalIgnoreCase);
 Test = results.ToString();
   return Test;

}
</code>```

But I get the error System.Linq.Enumerable+d__921[System.String]`. Could someone explain what's going on, and how I can fix it?

答:
This program gets intersection of 2 strings (assuming duplication is allowed)</p>

```<code>public String getIntersection(String s1, String s2) {
    String common = "";
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s2.length(); j++) {
            if (s1.length() == 0 || s1.length() == 0)
                return common;
            if (s1.charAt(i) == s2.charAt(j)) {
                common = common + s1.charAt(i);
                // delete character from each if there is a match
                s1 = s1.substring(0, i) + s1.substring(i + 1);
                s2 = s2.substring(0, j) + s2.substring(j + 1);
                i = -1;
                break;
            }
        }
    }
    return common;
}
</code>```

Body:
I am trying to find the intersection between two strings. For example, if string one was my car is bad, and string two was my horse is good, it would return my is.
This is my code:

  public static string intersection2(string x1, string x2)
{
  string[] string1 = x1.Split(' ');
string[] string2 = x2.Split(' ');
string[] m = string1.Distinct();
 string[] n = string2.Distinct();
  string Test;
 var results = m.Intersect(n,StringComparer.OrdinalIgnoreCase);
 Test = results.ToString();
   return Test;

}

But I get the error System.Linq.Enumerable+d__921[System.String]`. Could someone explain what's going on, and how I can fix it?

Body:
This program gets intersection of 2 strings (assuming duplication is allowed)

public String getIntersection(String s1, String s2) {
    String common = "";
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s2.length(); j++) {
            if (s1.length() == 0 || s1.length() == 0)
                return common;
            if (s1.charAt(i) == s2.charAt(j)) {
                common = common + s1.charAt(i);
                // delete character from each if there is a match
                s1 = s1.substring(0, i) + s1.substring(i + 1);
                s2 = s2.substring(0, j) + s2.substring(j + 1);
                i = -1;
                break;
            }
        }
    }
    return common;
}


答:
In your form code, there is two field for full_name one text field and another hidden field. Event if you enter value the hidden value will set it null. so if you remove it, it will work.</p>

```<code>    <% if @user.errors.any? %>
    <h2><%= pluralize(@user.errors.count, "error")%> prevented
    this post from saving:</h2>
    <ul>
    <% @user.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
    <% end %>
    </ul>
    <% end %>
    <%= f.label :full_name, "Full Name" %>
    <%= f.text_field :full_name %>

    <%= f.label "Upload profile picture" %><br><br />
    <%= f.file_field :profile %><br/><br/>
    <br>

   <%= f.label "Email (Will not be published)" %><br>
   <%= f.text_field :email %>
</code>```

Title: Rails Form Input does not save, becomes blank after I submit

Body:
In your form code, there is two field for full_name one text field and another hidden field. Event if you enter value the hidden value will set it null. so if you remove it, it will work.

    <% if @user.errors.any? %>
    <h2><%= pluralize(@user.errors.count, "error")%> prevented
    this post from saving:</h2>
    <ul>
    <% @user.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
    <% end %>
    </ul>
    <% end %>
    <%= f.label :full_name, "Full Name" %>
    <%= f.text_field :full_name %>

    <%= f.label "Upload profile picture" %><br><br />
    <%= f.file_field :profile %><br/><br/>
    <br>

   <%= f.label "Email (Will not be published)" %><br>
   <%= f.text_field :email %>


问:
Detecting a smaller image (.png) within a larger image retrieved with ImageGrab?
I've spent the past hour researching this simple topic, but all of the answers I've come across have been very complex and, as a noob to Python, I've been unable to incorporate any of them into my program.

I am trying to make an AI play a browser version of the Piano Tiles Game. As of now, I'm simply trying to take a capture of the games window (a small portion of my computer screen), and then check that games window with a .png of the game's start button. From there I will go on to CLICK that start button, but that's a problem for another time.

How can I check to see if a Image contains a .png file?

Here is my current code:

```<code>from PIL import ImageGrab as ig, ImageOps as io, Image
import pyautogui
import bbox

def grabStart(window):
    #The start button
    start = Image.open("res/StartButton.PNG")
    start = io.grayscale(start)

    #This is the part I need to figure out. The following is just pseudocode
    if window.contains(start): #I know that this doesn't actually work. Just pseudocode
        #I'd like to return the location of 'start' in one of the following forms
        return either: (x1, y1, x2, y2), (x1, y1, width, height), (a coordinate within 'start'))

def grabGame():
    #The coordinates of the entire game window
    x1 = 2222
    y1 = 320
    x2 = 2850
    y2 = 1105

    #The entire screen of the game
    window = ig.grab(bbox = (x1, y1, x2, y2))
    window = io.grayscale(window)

    return window

grabStart(grabGame())
</code>```

答: Try using pyautogui.locate(). Function takes in input two parameter's, the first is the image which needs to be found, the second one is the image in which the smaller image needs to be found. This method only works for images, so if you want to run this for a live window, you might consider another option. Secondly pyautogui is just a wrapper over PIL so if you run into efficiency issues, you might wanna translate the locate() into its PIL equivalent for performance.

Body:
I've spent the past hour researching this simple topic, but all of the answers I've come across have been very complex and, as a noob to Python, I've been unable to incorporate any of them into my program.

I am trying to make an AI play a browser version of the Piano Tiles Game. As of now, I'm simply trying to take a capture of the games window (a small portion of my computer screen), and then check that games window with a .png of the game's start button. From there I will go on to CLICK that start button, but that's a problem for another time.

How can I check to see if a Image contains a .png file?

Here is my current code:

from PIL import ImageGrab as ig, ImageOps as io, Image
import pyautogui
import bbox

def grabStart(window):
    #The start button
    start = Image.open("res/StartButton.PNG")
    start = io.grayscale(start)

    #This is the part I need to figure out. The following is just pseudocode
    if window.contains(start): #I know that this doesn't actually work. Just pseudocode
        #I'd like to return the location of 'start' in one of the following forms
        return either: (x1, y1, x2, y2), (x1, y1, width, height), (a coordinate within 'start'))

def grabGame():
    #The coordinates of the entire game window
    x1 = 2222
    y1 = 320
    x2 = 2850
    y2 = 1105

    #The entire screen of the game
    window = ig.grab(bbox = (x1, y1, x2, y2))
    window = io.grayscale(window)

    return window

grabStart(grabGame())


问:
How to typehint redux dispatcher with different return type than dispatch type?
I want to typehint an action creator with a different type than the dispatch type.

I've tried to typehint the ThunkResult with both types but this is not ideal.

// types.ts
interface AppListAction extends FetchAction {
  type: typeof APP_LIST,
  [FETCH]: {},
}

interface AppListSuccessAction extends FetchResponseAction {
  type: typeof APP_LIST_SUCCESS,
  response: Array<ListModel>
}

export type AppResponseActions =
  AppListSuccessAction

export type AppActions =
  AppListAction
  | AppResponseActions

// actions.ts
export const loadListCreator = (): AppActions => ({
  type: C_LIST,
  [FETCH]: {},
})

export const loadList = (): ThunkResult<AppResponseActions> => (dispatch: ThunkDispatcher) => dispatch(loadListCreator())
```

I expect no errors but instead I receive:

TypeScript error: Type 'AppActions' is not assignable to type 'AppResponseActions'.
  Type 'AppListAction' is not assignable to type 'AppResponseActions'.
    Property 'response' is missing in type 'AppListAction' but required in type 'AppListSuccessAction'.  TS2322

答:
To make your code compilable I made following assumptions

```<code>import { ThunkAction, ThunkDispatch } from 'redux-thunk';

const FETCH = 'fetch';

interface FetchAction {
    [FETCH]: object;
}

interface FetchResponseAction {
    prop2: string;
}

const APP_LIST = 'APP_LIST';
const APP_LIST_SUCCESS = 'APP_LIST_SUCCESS';

interface ListModel {
    prop3: string;
}
</code>```

And after your code

```<code>type ThunkResult<R> = ThunkAction<R, State, undefined, AppActions>;
type ThunkDispatcher = ThunkDispatch<State, undefined, AppActions>;
</code>```

Given assumptions above your code become compilable with following modification

```<code>export const loadList = (): ThunkResult<AppActions> => (dispatch: ThunkDispatcher) => dispatch(loadListCreator());
</code>```

ThunkResult<AppActions> should have type for R = AppActions. R is return value from function of type ThunkResult. In Redux-Thunk source code ThunkAction is defined as follows

```<code>export type ThunkAction<
    TReturnType,
    TState,
    TExtraThunkArg,
    TBasicAction extends Action
> = (
    dispatch: ThunkDispatch<TState, TExtraThunkArg, TBasicAction>,
    getState: () => TState,
    extraArgument: TExtraThunkArg
) => TReturnType;
</code>```

So ThunkAction (on which ThunkResult is based) is a function which return value of type TReturnType.

Then you try to make loadlist of type ThunkResult<> equal to (dispatch: ThunkDispatcher) => dispatch(loadListCreator()). Essentially it is also function but returning result of dispatch call. dispatch is of type ThunkDispatcher and from source it has type

```<code>export interface ThunkDispatch<
    TState,
    TExtraThunkArg,
    TBasicAction extends Action
> {
    <TReturnType>(
        thunkAction: ThunkAction<TReturnType, TState, TExtraThunkArg, TBasicAction>
    ): TReturnType;
    <A extends TBasicAction>(action: A): A;
}
</code>```

So it is overloaded function taking function with one agrument of type A and returning result of type A. As dispatch is called with result of loadListCreator() call which returns result of type AppActions, A is inferred to be AppActions.

Original code is correctly not compiled as you want to assign fucntion returning AppActions to function returning AppResponseActions. AppActions is union type and can be either AppResponseActions or AppListAction. In case it is AppListAction it cannot be assigned to AppResponseActions.

I think I've described clearly :-)

From practice point of view your code is a bit overcomplicated.

Consider simplifing it this way.

Inherit all actions from Action type

```<code>import { Action } from 'redux';

interface AppListAction extends Action {
    type: typeof APP_LIST,
    [FETCH]: {},
}
</code>```

Set type ThunkResult to following

```<code>type ThunkResult = ThunkAction<void, State, undefined, AppActions>;
</code>```

Most probably you don't need TReturnType. Thunk actions just dispatch everything needed inside code and return nothing (void).

Action creators for sync actions may look like

```<code>interface SyncAction1 extends Action {
    type: 'SYNC_ACTION',
    argument: string
}

const SomeSyncAction = (argument: string) => <SyncAction1>{ type: 'SYNC_ACTION', argument }
</code>```

Action creators for async action may look like

```<code>export const loadList = (): ThunkResult => (dispatch: ThunkDispatcher) => {
     dispatch(/* start loading */);
     const result = await // load api call
     dispatch(loadListCreator(result));
}
</code>```

Reducer will look like

```<code>export function loadReducer (state = initalState, action: AppActions)
// reducer code
</code>```

Body:
I want to typehint an action creator with a different type than the dispatch type.

I've tried to typehint the ThunkResult with both types but this is not ideal.

// types.ts
interface AppListAction extends FetchAction {
  type: typeof APP_LIST,
  [FETCH]: {},
}

interface AppListSuccessAction extends FetchResponseAction {
  type: typeof APP_LIST_SUCCESS,
  response: Array<ListModel>
}

export type AppResponseActions =
  AppListSuccessAction

export type AppActions =
  AppListAction
  | AppResponseActions

// actions.ts
export const loadListCreator = (): AppActions => ({
  type: C_LIST,
  [FETCH]: {},
})

export const loadList = (): ThunkResult<AppResponseActions> => (dispatch: ThunkDispatcher) => dispatch(loadListCreator())

I expect no errors but instead I receive:

TypeScript error: Type 'AppActions' is not assignable to type 'AppResponseActions'.
  Type 'AppListAction' is not assignable to type 'AppResponseActions'.
    Property 'response' is missing in type 'AppListAction' but required in type 'AppListSuccessAction'.  TS2322

Body:
To make your code compilable I made following assumptions

import { ThunkAction, ThunkDispatch } from 'redux-thunk';

const FETCH = 'fetch';

interface FetchAction {
    [FETCH]: object;
}

interface FetchResponseAction {
    prop2: string;
}

const APP_LIST = 'APP_LIST';
const APP_LIST_SUCCESS = 'APP_LIST_SUCCESS';

interface ListModel {
    prop3: string;
}

And after your code

type ThunkResult<R> = ThunkAction<R, State, undefined, AppActions>;
type ThunkDispatcher = ThunkDispatch<State, undefined, AppActions>;

Given assumptions above your code become compilable with following modification

export const loadList = (): ThunkResult<AppActions> => (dispatch: ThunkDispatcher) => dispatch(loadListCreator());

ThunkResult<AppActions> should have type for R = AppActions. R is return value from function of type ThunkResult. In Redux-Thunk source code ThunkAction is defined as follows

export type ThunkAction<
    TReturnType,
    TState,
    TExtraThunkArg,
    TBasicAction extends Action
> = (
    dispatch: ThunkDispatch<TState, TExtraThunkArg, TBasicAction>,
    getState: () => TState,
    extraArgument: TExtraThunkArg
) => TReturnType;

So ThunkAction (on which ThunkResult is based) is a function which return value of type TReturnType.

Then you try to make loadlist of type ThunkResult<> equal to (dispatch: ThunkDispatcher) => dispatch(loadListCreator()). Essentially it is also function but returning result of dispatch call. dispatch is of type ThunkDispatcher and from source it has type

export interface ThunkDispatch<
    TState,
    TExtraThunkArg,
    TBasicAction extends Action
> {
    <TReturnType>(
        thunkAction: ThunkAction<TReturnType, TState, TExtraThunkArg, TBasicAction>
    ): TReturnType;
    <A extends TBasicAction>(action: A): A;
}

So it is overloaded function taking function with one agrument of type A and returning result of type A. As dispatch is called with result of loadListCreator() call which returns result of type AppActions, A is inferred to be AppActions.

Original code is correctly not compiled as you want to assign fucntion returning AppActions to function returning AppResponseActions. AppActions is union type and can be either AppResponseActions or AppListAction. In case it is AppListAction it cannot be assigned to AppResponseActions.

I think I've described clearly :-)

From practice point of view your code is a bit overcomplicated.

Consider simplifing it this way.

Inherit all actions from Action type

import { Action } from 'redux';

interface AppListAction extends Action {
    type: typeof APP_LIST,
    [FETCH]: {},
}

Set type ThunkResult to following

type ThunkResult = ThunkAction<void, State, undefined, AppActions>;

Most probably you don't need TReturnType. Thunk actions just dispatch everything needed inside code and return nothing (void).

Action creators for sync actions may look like

interface SyncAction1 extends Action {
    type: 'SYNC_ACTION',
    argument: string
}

const SomeSyncAction = (argument: string) => <SyncAction1>{ type: 'SYNC_ACTION', argument }

Action creators for async action may look like

export const loadList = (): ThunkResult => (dispatch: ThunkDispatcher) => {
     dispatch(/* start loading */);
     const result = await // load api call
     dispatch(loadListCreator(result));
}

Reducer will look like

export function loadReducer (state = initalState, action: AppActions)
// reducer code


问:
C# logic question
I have those boolean values:

```<code>bool test = false && true || true; // true
bool test1 = false && (true || true); // false
</code>```

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)

答:
in test you have false && true, which is false and then you have false || true which is true.
In the second case you evaluate (true || true) at first => true and then false && true which is false.

Title: C# logic question

Body:
I have those boolean values:

bool test = false && true || true; // true
bool test1 = false && (true || true); // false

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)


问:
Use channel to limit the number of active go routines
I'm reading the "The Go Programming Language"
One way to limit the number of running go routines is to use a "counting semaphore".

The other way is Limiting number of go routines running

I am allowing 2 more go routines in the case. I'm getting deadlock error.
What causes the deadlock in my code?

```<code>package main

import (
    "bytes"
    //"context"
    "fmt"
    "runtime"
    "strconv"
    "sync"
    "time"
)

func main() {
    max := 2
    var wg sync.WaitGroup
    squares := make(chan int)
    tokens := make(chan struct{}, max)
    for i := 20; i >= 1; i-- {
        tokens <- struct{}{}
        wg.Add(1)
        go func(n int) {
            defer func() { <-tokens }()
            defer wg.Done()
            fmt.Println("run go routine ", getGID())
            squares <- Square(n)

        }(i)
    }

    go func() {
        wg.Wait()
        close(squares)
    }()

    for s := range squares {
        fmt.Println("Get square: ", s)

    }
}

func Square(num int) int {
    time.Sleep(time.Second * time.Duration(num))
    fmt.Println(num * num)
    return num * num
}

func getGID() uint64 {
    b := make([]byte, 64)
    b = b[:runtime.Stack(b, false)]
    b = bytes.TrimPrefix(b, []byte("goroutine "))
    b = b[:bytes.IndexByte(b, ' ')]
    n, _ := strconv.ParseUint(string(b), 10, 64)
    return n
}
</code>```

答:
The goroutines block on sending to squares.  Main is not receiving on squares because it blocks on starting the the goroutines.

Fix by moving the code that starts the goroutines to a goroutine.  This allows main to continue executing to the receive on squares.

```<code>squares := make(chan int)
go func() {
    max := 2
    var wg sync.WaitGroup
    tokens := make(chan struct{}, max)
    for i := 20; i >= 1; i-- {
        tokens <- struct{}{}
        wg.Add(1)
        go func(n int) {
            defer func() { <-tokens }()
            defer wg.Done()
            fmt.Println("run go routine ", getGID())
            squares <- Square(n)

        }(i)
    }

    wg.Wait()
    close(squares)
}()

fmt.Println("About to receive")
for s := range squares {
    fmt.Println("Get square: ", s)

}
</code>```

Run it on the playground.

Body:
I'm reading the "The Go Programming Language"
One way to limit the number of running go routines is to use a "counting semaphore".

The other way is Limiting number of go routines running

I am allowing 2 more go routines in the case. I'm getting deadlock error.
What causes the deadlock in my code?

package main

import (
    "bytes"
    //"context"
    "fmt"
    "runtime"
    "strconv"
    "sync"
    "time"
)

func main() {
    max := 2
    var wg sync.WaitGroup
    squares := make(chan int)
    tokens := make(chan struct{}, max)
    for i := 20; i >= 1; i-- {
        tokens <- struct{}{}
        wg.Add(1)
        go func(n int) {
            defer func() { <-tokens }()
            defer wg.Done()
            fmt.Println("run go routine ", getGID())
            squares <- Square(n)

        }(i)
    }

    go func() {
        wg.Wait()
        close(squares)
    }()

    for s := range squares {
        fmt.Println("Get square: ", s)

    }
}

func Square(num int) int {
    time.Sleep(time.Second * time.Duration(num))
    fmt.Println(num * num)
    return num * num
}

func getGID() uint64 {
    b := make([]byte, 64)
    b = b[:runtime.Stack(b, false)]
    b = bytes.TrimPrefix(b, []byte("goroutine "))
    b = b[:bytes.IndexByte(b, ' ')]
    n, _ := strconv.ParseUint(string(b), 10, 64)
    return n
}

Body:
The goroutines block on sending to squares.  Main is not receiving on squares because it blocks on starting the the goroutines.

Fix by moving the code that starts the goroutines to a goroutine.  This allows main to continue executing to the receive on squares.

squares := make(chan int)
go func() {
    max := 2
    var wg sync.WaitGroup
    tokens := make(chan struct{}, max)
    for i := 20; i >= 1; i-- {
        tokens <- struct{}{}
        wg.Add(1)
        go func(n int) {
            defer func() { <-tokens }()
            defer wg.Done()
            fmt.Println("run go routine ", getGID())
            squares <- Square(n)

        }(i)
    }

    wg.Wait()
    close(squares)
}()

fmt.Println("About to receive")
for s := range squares {
    fmt.Println("Get square: ", s)

}

Run it on the playground.


问:
Is there a way to skip over existing _id's for insert_many in Pymongo 3.0?
I'm updating a DB that has several million documents with less than 10 _id collisions.

I'm currently using the PyMongo module to do batch inserts using insert_many by:

Querying the db to see if the _id exists

Then adding the document to an array if _id doesn't exist

Insert to the database using insert_many, 1000 documents at a time.

There are only about 10 collisions out of several million documents and I'm currently querying the database for each _id. I think that I could cut down on overall insert time by a day or two if I could cut out the query process.

Is there something similar to upsert perhaps that only inserts a document if it doesn't exist?

答:
While Blakes' answer is great, for most of cases it's fine to use ordered=False argument and catch BulkWriteError in case of duplicates.

try:
    collection.insert_many(data, ordered=False)
except BulkWriteError:
    logger.info('Duplicates were found.')
```


Title: Multi-conditional mutate

Body:
I have a data frame that requires conditional recoding of a column based on the date listed in certain rows for each subset of IDs. I am trying to figure out how to best achieve this using the mutate function in dplyr. Suggestions and alternate solutions are welcome, but I would like to avoid using for loops.

I know how to write a really verbose and inefficient for loop that would solve this problem, but would like to know how to do it more efficiently.

The sample data frame:

df<-data.frame(ID = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2),
               date = as.Date(c("2016-02-01","2016-02-01","2016-02-01","2016-03-21", "2016-03-21", "2016-03-21", "2016-10-05", "2016-10-05", "2016-10-05", "2016-10-05", "2016-03-01","2016-03-01","2016-03-01","2016-04-21", "2016-04-21", "2016-04-21", "2016-11-05", "2016-11-05", "2016-11-05", "2016-11-05")),
               trial = c(NA, NA, NA, 1, 1, 1, NA, NA, NA, NA, NA, NA, NA, 1, 1, 1, NA, NA, NA, NA)

My pseudo code - the second logical argument in the first two case_when statements is where I am stuck.

df%>%
  group_by(ID)%>%
  mutate(results = case_when(
     is.na(trial) & date < date where trial = 1 ~ 0,
     is.na(trial) & date > date where trial = 1 ~ 2,
     trial == trial
  ))

The expected result being:

data.frame(ID = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2),
               date = as.Date(c("2016-02-01","2016-02-01","2016-02-01","2016-03-21", "2016-03-21", "2016-03-21", "2016-10-05", "2016-10-05", "2016-10-05", "2016-10-05", "2016-03-01","2016-03-01","2016-03-01","2016-04-21", "2016-04-21", "2016-04-21", "2016-11-05", "2016-11-05", "2016-11-05", "2016-11-05")),
               trial = c(0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2)
)

Body:
An option would be to group by 'ID' and transform the 'trial' by applying the run-length-id on (rleid) on the 'trial' column

library(dplyr)
library(data.table)
df %>%
   group_by(ID) %>%
   mutate(trial = rleid(trial)-1)
# A tibble: 20 x 3
# Groups:   ID [2]
#      ID date       trial
#   <dbl> <date>     <dbl>
# 1     1 2016-02-01     0
# 2     1 2016-02-01     0
# 3     1 2016-02-01     0
# 4     1 2016-03-21     1
# 5     1 2016-03-21     1
# 6     1 2016-03-21     1
# 7     1 2016-10-05     2
# 8     1 2016-10-05     2
# 9     1 2016-10-05     2
#10     1 2016-10-05     2
#11     2 2016-03-01     0
#12     2 2016-03-01     0
#13     2 2016-03-01     0
#14     2 2016-04-21     1
#15     2 2016-04-21     1
#16     2 2016-04-21     1
#17     2 2016-11-05     2
#18     2 2016-11-05     2
#19     2 2016-11-05     2
#20     2 2016-11-05     2

Or using rle

df %>%
  group_by(ID) %>%
  mutate(trial = with(rle(is.na(trial)),
             rep(seq_along(values), lengths))-1)


问:
limiting a search (python)
```<code>from shodan import WebAPI

SHODAN_API_KEY = "MY API KEY"
api = WebAPI(SHODAN_API_KEY)

results = api.exploitdb.search('PHP')

print 'Results found: %s' % results['total']
for exploit in results['matches']:
        print '%s:' % (exploit['description'])
</code>```

How can I limit the search to only print the first 5 results?

答:
Take your time and learn the Python basics about lists and "slicing" in particular:

http://diveintopython.ep.io/native-datatypes.html

Title: limiting a search (python)

Body:
from shodan import WebAPI

SHODAN_API_KEY = "MY API KEY"
api = WebAPI(SHODAN_API_KEY)

results = api.exploitdb.search('PHP')

print 'Results found: %s' % results['total']
for exploit in results['matches']:
        print '%s:' % (exploit['description'])

How can I limit the search to only print the first 5 results?


问:
Android emulator gives error "Resetting for cold boot: emulation engine failed" and exits
After updating AS now emulator quits every time I start it. Below is the screenshot I managed to capture before it disappeared.

In the logs the following are printed

14:49 Emulator: WARNING: change of renderer detected.

14:49 Emulator: C:\Users\Nux\AppData\Local\Android\Sdk\emulator\qemu\windows-x86_64\qemu-system-x86_64.exe:
  error while loading state for instance 0x0 of device 'goldfish_pipe'

14:49 Emulator: deleteSnapshot: for default_boot

14:49 Emulator: qemu: unsupported keyboard cmd=0x84

14:49 Emulator: qemu: unsupported keyboard cmd=0x84

14:49 Emulator: Process finished with exit code 0

I already tried the following:

Delete all my virtual devices and created new ones.

Wipe Emulator data.

Tried to lunch emulator manually in AVD.

Launch emulator with the option "Cold boot now".

And none of them worked. Any help will be appreciated!

答:
I had the same problem. What worked for me:

Editing the AVD configuration and on Graphics I selected "Software".

Lower uncheck "Device Frame".(without this step it was keeping crashing).

Wipe data

Cold boot.

And now it works fine. Hope my advice will help to anyone.


问:
Eaten by the net? Crawler survival under this website using python
I am making web-crawler to get information from http://www.caam.org.cn/hyzc, but it showed me HTTP Error 302, and I cannot fix it.
https://imgur.com/a/W0cykim
The picture gives you a rough idea about the special layout of this website in that when you are browsing it, it will pop out a window, telling you that the website is accelerating, for the reason that there are so many people online, and then direct you to that website. As a result, when I use web-crawler, all I get is the information on this window, but nothing on this website. I think this is a good way for the website keeper to get rid of our web crawlers. So I want to ask for your help to get useful information from this website

At first, I used requests of python for my web crawler, and I only got information on that window, the results are shown here: https://imgur.com/a/GLcpdZn
And then I forbad website redirect, I got HTTP Error 303, shown:
https://imgur.com/a/6YtaVOt

This is the latest code I used:

python

```<code>import requests
def getpage(url):
    try:
        r= requests.get(url, headers={'User-Agent':'Mozilla/5.0'}, timeout=10)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "try again"
url = "http://www.caam.org.cn/hyzc"
print(getpage(url))
</code>```

The expected outcome of this question is to get useful information from the website http://www.caam.org.cn/hyzc. We may need to deal with the window popped out.

答:
Looks like this website have some kind of protection against crawlers using requests, the page is not entirely loaded when you send a get request.

You can try to emulate a browser using selenium:

```<code>from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://www.caam.org.cn/hyzc')
print(driver.page_source)
driver.close()
</code>```

driver.page_source will contain the page source.

You can learn how to setup selenium webdriver here.

Body:
I am making web-crawler to get information from http://www.caam.org.cn/hyzc, but it showed me HTTP Error 302, and I cannot fix it.
https://imgur.com/a/W0cykim
The picture gives you a rough idea about the special layout of this website in that when you are browsing it, it will pop out a window, telling you that the website is accelerating, for the reason that there are so many people online, and then direct you to that website. As a result, when I use web-crawler, all I get is the information on this window, but nothing on this website. I think this is a good way for the website keeper to get rid of our web crawlers. So I want to ask for your help to get useful information from this website

At first, I used requests of python for my web crawler, and I only got information on that window, the results are shown here: https://imgur.com/a/GLcpdZn
And then I forbad website redirect, I got HTTP Error 303, shown:
https://imgur.com/a/6YtaVOt

This is the latest code I used:

python

import requests
def getpage(url):
    try:
        r= requests.get(url, headers={'User-Agent':'Mozilla/5.0'}, timeout=10)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "try again"
url = "http://www.caam.org.cn/hyzc"
print(getpage(url))

The expected outcome of this question is to get useful information from the website http://www.caam.org.cn/hyzc. We may need to deal with the window popped out.

Body:
Looks like this website have some kind of protection against crawlers using requests, the page is not entirely loaded when you send a get request.

You can try to emulate a browser using selenium:

from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://www.caam.org.cn/hyzc')
print(driver.page_source)
driver.close()

driver.page_source will contain the page source.

You can learn how to setup selenium webdriver here.


问:
Join two dataframes with inner join
Say I have these two datasets:

```<code>Data frame 1:
X |  date
a |  1/1/2018
a |  1/2/2018
...
b |  1/1/2018
</code>```

And df 2:

```<code>Holiday
1/1/2018
5/1/2018
</code>```

What would be a elegant way to add a new column in the first dataset, with a 1 when the date has a match with second dataset?

Thank you very much!

答:
The words “merge” and “join” are used relatively interchangeably in Pandas and other languages, namely SQL and R. In Pandas, there are separate “merge” and “join” functions, both of which do similar things.

```<code>result = pd.merge(df1, df2, on = 'id_column')
result.head()
</code>```

In your particular case, this is probably not totally necessary since you really want to conditionally add a column to an existing data frame. As @Mike suggested, you should use isin(). The only difference here is that I opted to use the bool data type instead of int.

```<code>df1['is_holiday'] = df1.date.isin(df2.Holiday).astype(bool)
</code>```

Title: Join two dataframes with inner join

Body:
Say I have these two datasets:

Data frame 1:
X |  date
a |  1/1/2018
a |  1/2/2018
...
b |  1/1/2018

And df 2:

Holiday
1/1/2018
5/1/2018

What would be a elegant way to add a new column in the first dataset, with a 1 when the date has a match with second dataset?

Thank you very much!

Body:
The words “merge” and “join” are used relatively interchangeably in Pandas and other languages, namely SQL and R. In Pandas, there are separate “merge” and “join” functions, both of which do similar things.

result = pd.merge(df1, df2, on = 'id_column')
result.head()

In your particular case, this is probably not totally necessary since you really want to conditionally add a column to an existing data frame. As @Mike suggested, you should use isin(). The only difference here is that I opted to use the bool data type instead of int.

df1['is_holiday'] = df1.date.isin(df2.Holiday).astype(bool)


问:
403: Not authorized while creating a container
So I am facing a 403: Not authorized error while trying to use containers (kubernetes and container registry) anyone faced this issue or knows the answer for this problem?

here is a screenshot for a better explanation:
https://ibb.co/McxWQRW

答:
As per the documentation,

As a cluster administrator, you can define access policies for your
  IBM® Cloud Kubernetes Service cluster to create different levels of
  access for different users. For example, you can authorize certain
  users to work with cluster infrastructure resources and others to
  deploy only containers.

You should reach out to your administrator (the person who created the account) and ask them to assign you required IAM(Identity & Access Management) permissions to access the resources.

To find out how an administrator can provide you access, refer to the documentation here

For more information about setting up your account and resources, try out this tutorial about the best practices for organizing users, teams, and applications


问:
Codeigniter select_sum generate wrong query
I worked on a Codeigniter 2 project, there I have an active record like:

```<code>$query = $this->db->select_sum('Cardit * GPA', 'sum')
                  ->get('marks_info');
</code>```

It generates query like:

```<code>SELECT SUM(`Cardit` * `GPA`) AS `sum` FROM `marks_info`
</code>```

Recently I migrated my project to Codeigniter 3, but the same active record generated little different query like:

```<code>SELECT SUM(`Cardit *` `GPA`) AS `sum` FROM `marks_info`
</code>```

that is wrong, it includes * with Cardit ('Cardit *') in SUM section.

Difference:

Can anybody tell me, how can I solve this issue in CodeIgniter 3 ?

答:
Try this, It will give you your expected output</p>

```<code>$query = $this->db->select('sum(Cardit * GPA) sum')->get('marks_info');
</code>```

Body:
I worked on a Codeigniter 2 project, there I have an active record like:

$query = $this->db->select_sum('Cardit * GPA', 'sum')
                  ->get('marks_info');

It generates query like:

SELECT SUM(`Cardit` * `GPA`) AS `sum` FROM `marks_info`

Recently I migrated my project to Codeigniter 3, but the same active record generated little different query like:

SELECT SUM(`Cardit *` `GPA`) AS `sum` FROM `marks_info`

that is wrong, it includes * with Cardit ('Cardit *') in SUM section.

Difference:

Can anybody tell me, how can I solve this issue in CodeIgniter 3 ?

Body:
Try this, It will give you your expected output

$query = $this->db->select('sum(Cardit * GPA) sum')->get('marks_info');


问:
How can I pass the isConnect state to the other class
Now I have App.js is my init page.
I want listen internet status from net_provide.js.
If isConnected is true then APP.js show renderLoadingView()
If not then APP.js show renderDisconnectView() like below code
But I don't know how to pass the isConnected from net_provide.js to APP.js

Can anyone help me? Thank you!

App.js

```<code>renderLoadingView() {
    _aesDecryptWithMode(_aesEncryptWithMode('test'))
    getFcmToken()
    return (
      <View style={ styles.container }>
        <NetworkNotifier
          offlineText="無網路連線"
          onlineText="網路已連線"
          position="top" />
        <Network_provider/>
        <Text>
          Loading Events....
          { '\n' }
        </Text>
      </View>
    )
  }

  renderDisconnectView() {
    return (
      <View style={ styles.container }>
        <Network_provider/>
        <Text>
          diss
          { '\n' }
        </Text>
      </View>
    )

  }
</code>```

The problem is here
this.props.Connected

```<code>  render() {
    return (
   if (this.props.isConnected) {
     return this.renderLoadingView();
   }
   if (!this.props.isConnected) {
     return this.renderDisconnectView();
   }

  }
</code>```

And below is network_provider.js

```<code>export class Network_provider extends React.PureComponent {
  state = {
    isConnected: true
  };

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = isConnected => {
    if (isConnected) {
      this.setState({
        isConnected
      });
    } else {
      this.setState({
        isConnected
      });
    }
  };

  render() {
    return <App Connected={ this.state.isConnected } />;
  }
}
</code>```

答:
Change this.props.isConnected to this.props.Connected, since you are passing a prop called Connected to App component in Network_provider

```<code> render() {
   return (
       if (this.props.Connected) {
         return this.renderLoadingView();
       }
       if (!this.props.Connected) {
         return this.renderDisconnectView();
       }
     );
  }
</code>```

what is the value passed to handleConnectivityChange if its a Boolean then you can shorten it like this.

```<code>  handleConnectivityChange = isConnected => {
    this.setState({
        isConnected:isConnected
      });
  };
</code>```

Update
Try this in you child component. first set an initial state and use componentDidUpdate to check is props changed. like this

```<code>this.state={
 Connected:true //default value
}

componentDidUpdate(prevProps, prevState) {
    if (this.props.Connected!== prevProps.Connected) {
      this.setState({Connected:this.props.Connected})
    }
  }

 render() {
    return (
        if (this.state.Connected) {
           return this.renderLoadingView();
         }
        if (!this.state.Connected) {
           return this.renderDisconnectView();
         }
      );
 }
</code>```

Body:
Now I have App.js is my init page.
I want listen internet status from net_provide.js.
If isConnected is true then APP.js show renderLoadingView()
If not then APP.js show renderDisconnectView() like below code
But I don't know how to pass the isConnected from net_provide.js to APP.js

Can anyone help me? Thank you!

App.js

renderLoadingView() {
    _aesDecryptWithMode(_aesEncryptWithMode('test'))
    getFcmToken()
    return (
      <View style={ styles.container }>
        <NetworkNotifier
          offlineText="無網路連線"
          onlineText="網路已連線"
          position="top" />
        <Network_provider/>
        <Text>
          Loading Events....
          { '\n' }
        </Text>
      </View>
    )
  }

  renderDisconnectView() {
    return (
      <View style={ styles.container }>
        <Network_provider/>
        <Text>
          diss
          { '\n' }
        </Text>
      </View>
    )

  }

The problem is here
this.props.Connected

  render() {
    return (
   if (this.props.isConnected) {
     return this.renderLoadingView();
   }
   if (!this.props.isConnected) {
     return this.renderDisconnectView();
   }

  }

And below is network_provider.js

export class Network_provider extends React.PureComponent {
  state = {
    isConnected: true
  };

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = isConnected => {
    if (isConnected) {
      this.setState({
        isConnected
      });
    } else {
      this.setState({
        isConnected
      });
    }
  };

  render() {
    return <App Connected={ this.state.isConnected } />;
  }
}

Body:
Change this.props.isConnected to this.props.Connected, since you are passing a prop called Connected to App component in Network_provider

 render() {
   return (
       if (this.props.Connected) {
         return this.renderLoadingView();
       }
       if (!this.props.Connected) {
         return this.renderDisconnectView();
       }
     );
  }

what is the value passed to handleConnectivityChange if its a Boolean then you can shorten it like this.

  handleConnectivityChange = isConnected => {
    this.setState({
        isConnected:isConnected
      });
  };

Update
Try this in you child component. first set an initial state and use componentDidUpdate to check is props changed. like this

this.state={
 Connected:true //default value
}

componentDidUpdate(prevProps, prevState) {
    if (this.props.Connected!== prevProps.Connected) {
      this.setState({Connected:this.props.Connected})
    }
  }

 render() {
    return (
        if (this.state.Connected) {
           return this.renderLoadingView();
         }
        if (!this.state.Connected) {
           return this.renderDisconnectView();
         }
      );
 }


问:
How to play video on image target vuforia and unity?
I want to autoplay video on image target.

I am working with vuforia and unity..

P.S. I tried to do this with vuforia video playback but its not working

答:
Create a plane inside image target and add VideoPlayer on top of Plane.
Select VideoPlayer. Go to Render mode, select Material Override. In Renderer drag and drop plane.


答:
In your first example false && true is evaluated first and it evaluated as false. Then false OR true is of course evaluated to true.

In your second, because of the () true OR true is evaluated first to true, then true && false is evaluated to false.

So it makes perfectly sense.

Title: C# logic question


问:
Using React.memo with hooks for controlled inputs
I'm providing some form functionality from a custom React hook. This hook has some functionality similar to Formik (but this is really basic stuff).

```<code>function useFormValidation(initialState, validate) {
  const [values, setValues] = React.useState(initialState);
  const [errors, setErrors] = React.useState({});
  const [isSubmitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (isSubmitting) {
      const noErrors = Object.keys(errors).length === 0;
      if (noErrors) {
        console.log("authenticated!", values.email, values.password);
        setSubmitting(false);
      } else {
        setSubmitting(false);
      }
    }
  }, [errors]);

  function handleChange(event) {
    setValues({
      ...values,
      [event.target.name]: event.target.value
    });
  }

  function handleBlur() {
    const validationErrors = validate(values);
    setErrors(validationErrors);
  }

  function handleSubmit(event) {
    event.preventDefault();
    const validationErrors = validate(values);
    setErrors(validationErrors);
    setSubmitting(true);
  }

  return {
    handleSubmit,
    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  };
}

</code>```

The form is the following:

```<code>function Register() {
  const {
    handleSubmit,

    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  } = useFormValidation(INITIAL_STATE, validateAuth);
  // const [email, setEmail] = React.useState("");
  // const [password, setPassword] = React.useState("");

  return (
    <div className="container">
      <h1>Register Here</h1>
      <form onSubmit={handleSubmit}>
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          name="email"
          value={values.email}
          className={errors.email && "error-input"}
          autoComplete="off"
          placeholder="Your email address"
        />
        {errors.email && <p className="error-text">{errors.email}</p>}
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          value={values.password}
          className={errors.password && "error-input"}
          name="password"
          // type="password"
          placeholder="Choose a safe password"
        />
        {errors.password && <p className="error-text">{errors.password}</p>}
        <div>
          <button disabled={isSubmitting} type="submit">
            Submit
          </button>
        </div>
      </form>
    </div>
  );
}
</code>```

And the memoized component is the next:

```<code>function Input({
  handleChange,
  handleBlur,
  name,
  value,
  className,
  autoComplete,
  placeholder,
  type
}) {

  return (
    <input
      onChange={handleChange}
      onBlur={handleBlur}
      name={name}
      value={value}
      className={className}
      autoComplete={autoComplete}
      placeholder={placeholder}
      type={type}
    />
  );
}

function areEqual(prevProps, nextProps) {
  console.log(`
    prevProps: ${JSON.stringify(prevProps.value)}
    nextProps: ${JSON.stringify(nextProps.value)}
  `);
  return prevProps.value === nextProps.value;
}
const useMemo = (component, propsAreEqual) => {
  return memo(component, propsAreEqual);
};
export default useMemo(Input, areEqual);
</code>```

I enter some text into the first input. Then, when I switch to the second Input and start typing, the first input loses the value. It's like the form is not rendering the LAST MEMOIZED input, but prior versions instead.
I'm a React beginner and can't figure out the solution. Any help please?

答:
Try using the updater form of setState which takes a function:

```<code>function handleChange(event) {
  // event.target wont be available when fn is run in setState
  // so we save them in our own local variables here
  const { name, value } = event.target;

  setValues(prev => ({
    ...prev,
    [name]: value
  }));
}
</code>```

Body:
I'm providing some form functionality from a custom React hook. This hook has some functionality similar to Formik (but this is really basic stuff).

function useFormValidation(initialState, validate) {
  const [values, setValues] = React.useState(initialState);
  const [errors, setErrors] = React.useState({});
  const [isSubmitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (isSubmitting) {
      const noErrors = Object.keys(errors).length === 0;
      if (noErrors) {
        console.log("authenticated!", values.email, values.password);
        setSubmitting(false);
      } else {
        setSubmitting(false);
      }
    }
  }, [errors]);

  function handleChange(event) {
    setValues({
      ...values,
      [event.target.name]: event.target.value
    });
  }

  function handleBlur() {
    const validationErrors = validate(values);
    setErrors(validationErrors);
  }

  function handleSubmit(event) {
    event.preventDefault();
    const validationErrors = validate(values);
    setErrors(validationErrors);
    setSubmitting(true);
  }

  return {
    handleSubmit,
    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  };
}

The form is the following:

function Register() {
  const {
    handleSubmit,

    handleChange,
    handleBlur,
    values,
    errors,
    isSubmitting
  } = useFormValidation(INITIAL_STATE, validateAuth);
  // const [email, setEmail] = React.useState("");
  // const [password, setPassword] = React.useState("");

  return (

Register Here

      <form onSubmit={handleSubmit}>
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          name="email"
          value={values.email}
          className={errors.email && "error-input"}
          autoComplete="off"
          placeholder="Your email address"
        />
        {errors.email &&
{errors.email}
}
        <Input
          handleChange={handleChange}
          handleBlur={handleBlur}
          value={values.password}
          className={errors.password && "error-input"}
          name="password"
          // type="password"
          placeholder="Choose a safe password"
        />
        {errors.password &&
{errors.password}
}

          <button disabled={isSubmitting} type="submit">
            Submit
          </button>

      </form>

  );
}

And the memoized component is the next:

function Input({
  handleChange,
  handleBlur,
  name,
  value,
  className,
  autoComplete,
  placeholder,
  type
}) {

  return (
    <input
      onChange={handleChange}
      onBlur={handleBlur}
      name={name}
      value={value}
      className={className}
      autoComplete={autoComplete}
      placeholder={placeholder}
      type={type}
    />
  );
}

function areEqual(prevProps, nextProps) {
  console.log(`
    prevProps: ${JSON.stringify(prevProps.value)}
    nextProps: ${JSON.stringify(nextProps.value)}
  `);
  return prevProps.value === nextProps.value;
}
const useMemo = (component, propsAreEqual) => {
  return memo(component, propsAreEqual);
};
export default useMemo(Input, areEqual);

I enter some text into the first input. Then, when I switch to the second Input and start typing, the first input loses the value. It's like the form is not rendering the LAST MEMOIZED input, but prior versions instead.
I'm a React beginner and can't figure out the solution. Any help please?

Body:
Try using the updater form of setState which takes a function:

function handleChange(event) {
  // event.target wont be available when fn is run in setState
  // so we save them in our own local variables here
  const { name, value } = event.target;

  setValues(prev => ({
    ...prev,
    [name]: value
  }));
}


问:
How to change field name in collection result on Laravel
I'm working Laravel collection. I would like to change some eloquent output field name. Below is my query code.

```<code>$labdetails =LabDetailCustom::where('labcode',$request->labcode)->get(['id','name']);
</code>```

And resulted as below.

```<code>[
{
id: 65,
name: "Color"
},
{
id: 66,
name: "Apearance"
},
{
id: 67,
name: "Urobilinogen"
}
]
</code>```

But my need is to change 'id' to 'codename' instead. So result should be.

```<code>[
{
codename: 65,
name: "Color"
},
{
codename: 66,
name: "Apearance"
},
{
codename: 67,
name: "Urobilinogen"
}
]
</code>```

It may need to use 'map function' that I'm not familiar. Any advise or guidance would be greatly appreciated, Thanks.

答:
This should work as you expect:</p>

```<code>$labdetails =LabDetailCustom::where('labcode',$request->labcode)
    ->get(['id as codename','name']);
</code>```

Body:
I'm working Laravel collection. I would like to change some eloquent output field name. Below is my query code.

$labdetails =LabDetailCustom::where('labcode',$request->labcode)->get(['id','name']);

And resulted as below.

[
{
id: 65,
name: "Color"
},
{
id: 66,
name: "Apearance"
},
{
id: 67,
name: "Urobilinogen"
}
]

But my need is to change 'id' to 'codename' instead. So result should be.

[
{
codename: 65,
name: "Color"
},
{
codename: 66,
name: "Apearance"
},
{
codename: 67,
name: "Urobilinogen"
}
]

It may need to use 'map function' that I'm not familiar. Any advise or guidance would be greatly appreciated, Thanks.

Body:
This should work as you expect:

$labdetails =LabDetailCustom::where('labcode',$request->labcode)
    ->get(['id as codename','name']);


答:
you can use something like this .</p>

```<code>foreach( $labdetails as $index => $labdetail) {
        $labdetails [$index]['codename'] = $labdetail['id'];
        unset($labdetails[$index]['id']);
    }
</code>```

Title: How to change field name in collection result on Laravel

Body:
you can use something like this .

foreach( $labdetails as $index => $labdetail) {
        $labdetails [$index]['codename'] = $labdetail['id'];
        unset($labdetails[$index]['id']);
    }


问:
What's the correct way to pause the entire script execution contingent on an asynchronous function in JavaScript?
A lot of my script is contingent on information first read from a .JSON file using fetch() and .json() so it's asynchronous. I need to delay the execution of the rest of my script until those functions finish, without sticking the rest of my code in a huge .then() or function block or something. I've done some searching around but I can't really find what I'm looking for.

```<code>let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json);

console.log(config);
// REST OF SCRIPT
</code>```

It should log the config JSON object or the promise but, obviously, it only returns undefined. Any help would be greatly appreciated!

答:
Your config is being read before the request comes back. You can add another then clause:

```<code>let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json)
  .then(() => {
     console.log(config);
   });
</code>```

Body:
A lot of my script is contingent on information first read from a .JSON file using fetch() and .json() so it's asynchronous. I need to delay the execution of the rest of my script until those functions finish, without sticking the rest of my code in a huge .then() or function block or something. I've done some searching around but I can't really find what I'm looking for.

let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json);

console.log(config);
// REST OF SCRIPT

It should log the config JSON object or the promise but, obviously, it only returns undefined. Any help would be greatly appreciated!

Body:
Your config is being read before the request comes back. You can add another then clause:

let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json)
  .then(() => {
     console.log(config);
   });


问:
Caching architecture advise for a specific scenario

SETUP:

We have a .Net application that is distributed over 6 local servers each with a local database(ORACLE), 1 main server and 1 load balance machine. Requests come to the load balancer which redirects the incoming requests to one of the 6 local servers. In certain time intervals data is gathered in the main server and redistributed to the 6 local servers to be able to make decisions with the complete data.

Each local server has a cache component that caches the incoming requests based on different parameters (Location, incoming parameters, etc). With each request a local server decides whether to go to the database (ORACLE) or get the response from the cache. However in both cases the local server has to goto the database to do 1 insert and 1 update per request.

PROBLEM:

On a peak day each local server receives 2000 requests per second and system starts slowing down (CPU: 90% ). I am trying to increase the capacity before adding another local server to the mix. After running some benchmarks the bottleneck as it always is, seems to be the inevitable 1 insert and 1 update per request to database.

TRIED METHODS

To be able decrease the frequency I have created a Windows service that sits between the DB and .NET application. It contains a pipe server and receives each insert and update from the main .NET application and saves them in a Hashtable. The new service then at certain time intervals goes to the database once to do batch inserts and updates. The point was to go to the database less frequently. Although this had a positive effect it didn't benefit to the system load as much as I expected. The most of the cpu load comes from oracle.exe as requests per second increase.

I am trying to avoid going to the database as much as I can and the only way to avoid DB seems to be increasing the cache hit ratio other than the above mentioned solution I tried. My cache hit ratio is around 81 % percent currently. Because each local machine has its own cache I am actually missing lots of cacheable requests. When two similar requests redirects to different servers the second request cannot benefit from the cached result of the first one.

I don't have a lot of experience in system architecture so I would appreciate any help to this problem. Any suggestions on different caching architectures or setup, or any tools are welcome.

Thank you in advance, hopefully I made my question clear.

答:
2000 requests per second per server, about 24000 rps to database. It's a HUGE load for DB.
Try to optimize, scaleup or clusterize database.

May be NoSQL DB (Redis\Raven\Mongo) as middleware will be suitable for you. Local server will read\write sharded NoSQL DB, aggregated data will by synchronized with Oracle off-peak times.


问:
Can I split a large HAProxy config file into multiple smaller files?
I'm building an haproxy config file that has multiple front and backends. It's going to be several hundred lines long and I'd rather split it up into separate files for each of the different websites that I want to loadbalance.

Does HAProxy offer the ability to link to partial config files from the main haproxy.cfg file?

答:
answer of @Bapstie memtioned that, a directory can be passed to haproxy as config file, and files inside will be loaded in alphabet order. It's correct.

But problem is, the package haproxy in CentOS 'base/7/x86_64' repository is so old that it does not support that.

So either do you need to write a wrapper to append -f <individual config file>to the command, or you need to install latest version of haproxy:

for package in centos-release-scl-rh rh-haproxy18-haproxy; do
    yum install -y $package
done
```

<p>and create a drop-in config for haproxy service:</p>

```[Service]
ExecStart=
ExecStart=/opt/rh/rh-haproxy18/root/sbin/haproxy -f /etc/haproxy-nutstore/ -p /run/haproxy.pid $OPTIONS
```

Body:
answer of @Bapstie memtioned that, a directory can be passed to haproxy as config file, and files inside will be loaded in alphabet order. It's correct.

But problem is, the package haproxy in CentOS 'base/7/x86_64' repository is so old that it does not support that.

So either do you need to write a wrapper to append -f <individual config file>to the command, or you need to install latest version of haproxy:

for package in centos-release-scl-rh rh-haproxy18-haproxy; do
    yum install -y $package
done

and create a drop-in config for haproxy service:

[Service]
ExecStart=
ExecStart=/opt/rh/rh-haproxy18/root/sbin/haproxy -f /etc/haproxy-nutstore/ -p /run/haproxy.pid $OPTIONS


问:
Java Selenium findelement is not acknowledging an element that is on the page
If I use developer tools in Chrome, and paste my By.name statement, the page highlights exactly what I'm trying to view.

Here are two java statements sitting right next to each other:

```<code>driver.findElement(By.xpath("//input[@name='firstName']")).clear();
driver.findElement(By.xpath("//input[@name='shippingCost']")).click();
</code>```

I put these two next to each other to rule out that the driver was broken somehow at the point in the code that these come from. The first statement does clear the text box referenced, but the second is returning NoSuchElementError. I have also tried using By.name as mentioned above, I'm just chasing down why the second throws an error every time.

The page I'm working with is an EXTJS single page website, so the control is always there.  I want to use the .getText().length() to validate that there is now text in this box.

Any help on why I'm unable to click, or even just reference this control, on a page where I'm able to use my xpath or name selectors to see the control on the page.

---Edit to add these pics of the code relevent to the above xpaths

Sorry, this is another place that doesnt work, [name='shippingTypeGroundDate']

This is the shippingcost location

And this is the working firstName location

答:
Add explicit wait for the input textbox to be loaded. Then try to click the textbox with Javascript executor. Sometimes webdriver click may not work.</p>

```<code>WebElement element = driver.findElement(By.xpath("//input[@name='shippingCost']"));
try {
        if (element.isEnabled() && element.isDisplayed()) {

                ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
            } else {
                System.out.println("Unable to click on element");
            }
        } catch (StaleElementReferenceException e) {
            System.out.println("Element is not attached to the page document "+ e.getStackTrace());
        } catch (NoSuchElementException e) {
            System.out.println("Element was not found in DOM "+ e.getStackTrace());
        } catch (Exception e) {
            System.out.println("Unable to click on element "+ e.getStackTrace());
        }
</code>```

OwnerDisplayName: Dan Pearman

Body:
If I use developer tools in Chrome, and paste my By.name statement, the page highlights exactly what I'm trying to view.

Here are two java statements sitting right next to each other:

driver.findElement(By.xpath("//input[@name='firstName']")).clear();
driver.findElement(By.xpath("//input[@name='shippingCost']")).click();

I put these two next to each other to rule out that the driver was broken somehow at the point in the code that these come from. The first statement does clear the text box referenced, but the second is returning NoSuchElementError. I have also tried using By.name as mentioned above, I'm just chasing down why the second throws an error every time.

The page I'm working with is an EXTJS single page website, so the control is always there.  I want to use the .getText().length() to validate that there is now text in this box.

Any help on why I'm unable to click, or even just reference this control, on a page where I'm able to use my xpath or name selectors to see the control on the page.

---Edit to add these pics of the code relevent to the above xpaths

Sorry, this is another place that doesnt work, [name='shippingTypeGroundDate']

This is the shippingcost location

And this is the working firstName location

Body:
Add explicit wait for the input textbox to be loaded. Then try to click the textbox with Javascript executor. Sometimes webdriver click may not work.

WebElement element = driver.findElement(By.xpath("//input[@name='shippingCost']"));
try {
        if (element.isEnabled() && element.isDisplayed()) {

                ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
            } else {
                System.out.println("Unable to click on element");
            }
        } catch (StaleElementReferenceException e) {
            System.out.println("Element is not attached to the page document "+ e.getStackTrace());
        } catch (NoSuchElementException e) {
            System.out.println("Element was not found in DOM "+ e.getStackTrace());
        } catch (Exception e) {
            System.out.println("Unable to click on element "+ e.getStackTrace());
        }