问:
Rails 4.x relationships migration from Ruby 1.x
We are migrating some applications from Ruby 1.x to Ruby 4.x, not by choice.

I am finding that some of the relationships are no longer working.  Can someone please tell me if they can see anything in here that looks invalid to them based on rails 4.2.9?

In particular, here is what happens when I try to access the F5Device.nodes:

```<code>irb(main):003:0* f = F5Device.first
  SQL (7.8ms)  USE [Networks]
  F5Device Load (2.8ms)  EXEC sp_executesql N'SELECT  [dbo].[f5_devices].* FROM [dbo].[f5_devices]  ORDER BY [dbo].[f5_devices].[id] ASC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY'
=> #<F5Device id: 5422, name: "myDevice", environment: "UAT", feed_type_id: 1, scm_device_id: 121764, created_at: "2012-08-23 20:02:52", updated_at: "2017-01-19 10:08:08", gonefishing: 0>
irb(main):004:0>
irb(main):005:0* f.nodes
/usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/xsd/charset.rb:13: warning: variable $KCODE is no longer effective
/usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/soap/property.rb:68: warning: encoding option is ignored - u
/usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/soap/property.rb:69: warning: encoding option is ignored - u
/usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/soap/property.rb:70: warning: encoding option is ignored - u
ArgumentError: wrong number of arguments (0 for 1)
        from /usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/soap/property.rb:325:in `inject'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:269:in `block in constantize'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:259:in `each'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:259:in `inject'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:259:in `constantize'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:304:in `safe_constantize'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:572:in `safe_get'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:603:in `safe_constantize'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/inheritance.rb:154:in `block in compute_type'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/inheritance.rb:153:in `each'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/inheritance.rb:153:in `compute_type'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/reflection.rb:295:in `compute_class'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/reflection.rb:291:in `klass'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/associations/association.rb:118:in `klass'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/associations/collection_association.rb:41:in `reader'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/associations/builder/association.rb:115:in `nodes'
        from (irb):5
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands/console.rb:110:in `start'
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands/console.rb:9:in `start'
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands/commands_tasks.rb:68:in `console'
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands.rb:17:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'
</code>```

app/models/f5_device.rb

```<code>class F5Device < F5Base
      has_many :nodes, :class_name => "F5Node", :foreign_key => "device_id"
      has_many :members, :through => :nodes
      has_many :group_items , :foreign_key => :device_id
      has_many :groups, :through => :group_items
      has_many :dependencies, :class_name => "Dependency", :foreign_key => :device_id
      has_many :device_applications, :class_name => "F5DeviceApplication", :foreign_key => :device_id
      has_many :applications, :through => :device_applications
      has_many :websphere_servers, :class_name => "IisDependency", :foreign_key => :f5_device_id
</code>```

app/models/f5_node.rb

```<code>require 'f5'
class F5Node < F5Base
      has_many :bigips, :class_name => "F5Bigip", :foreign_key => :group_id, :primary_key => :group_id
      belongs_to :device, :class_name => "F5Device", :foreign_key => :device_id
      has_many :members, :class_name => "F5Member", :foreign_key => "node_id", :dependent => :destroy
      has_many :pools, :through => :members
      attr_accessor :ws, :bigip, :session_status, :monitor_status, :enabled_status, :status_description, :availability_status, :state
      after_initialize :set_ws
</code>```

答:
Assuming that you really are migrating your application from Rails 1.x to Rails 4.2:

This may not be the answer you're looking for, but the official upgrade guide says

If your application is currently on any version of Rails older than 3.2.x, you should upgrade to Rails 3.2 before attempting one to Rails 4.0.

Likewise,

If your application is currently on any version of Rails older than 3.1.x, you should upgrade to Rails 3.1 before attempting an update to Rails 3.2.

Etc.

It seems like the official upgrade path is:

1 to 3.0 ... I couldn't find instructions in the upgrade guide or any hints in the complete release notes blog since the very start of rails. I'm guessing the official path would be at most one major release at a time, but if you're gutsy you could jump right to 3.0 and see what happens.

3.0 to 3.1

3.1 to 3.2

3.2 to 4.0

4.0 to 4.1

4.1 to 4.2

Body:
We are migrating some applications from Ruby 1.x to Ruby 4.x, not by choice.

I am finding that some of the relationships are no longer working.  Can someone please tell me if they can see anything in here that looks invalid to them based on rails 4.2.9?

In particular, here is what happens when I try to access the F5Device.nodes:

irb(main):003:0* f = F5Device.first
  SQL (7.8ms)  USE [Networks]
  F5Device Load (2.8ms)  EXEC sp_executesql N'SELECT  [dbo].[f5_devices].* FROM [dbo].[f5_devices]  ORDER BY [dbo].[f5_devices].[id] ASC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY'
=> #<F5Device id: 5422, name: "myDevice", environment: "UAT", feed_type_id: 1, scm_device_id: 121764, created_at: "2012-08-23 20:02:52", updated_at: "2017-01-19 10:08:08", gonefishing: 0>
irb(main):004:0>
irb(main):005:0* f.nodes
/usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/xsd/charset.rb:13: warning: variable $KCODE is no longer effective
/usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/soap/property.rb:68: warning: encoding option is ignored - u
/usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/soap/property.rb:69: warning: encoding option is ignored - u
/usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/soap/property.rb:70: warning: encoding option is ignored - u
ArgumentError: wrong number of arguments (0 for 1)
        from /usr/local/lib/ruby/gems/2.2.0/gems/soap4r-1.5.8/lib/soap/property.rb:325:in `inject'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:269:in `block in constantize'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:259:in `each'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:259:in `inject'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:259:in `constantize'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/inflector/methods.rb:304:in `safe_constantize'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:572:in `safe_get'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activesupport-4.2.9/lib/active_support/dependencies.rb:603:in `safe_constantize'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/inheritance.rb:154:in `block in compute_type'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/inheritance.rb:153:in `each'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/inheritance.rb:153:in `compute_type'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/reflection.rb:295:in `compute_class'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/reflection.rb:291:in `klass'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/associations/association.rb:118:in `klass'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/associations/collection_association.rb:41:in `reader'
        from /usr/local/lib/ruby/gems/2.2.0/gems/activerecord-4.2.9/lib/active_record/associations/builder/association.rb:115:in `nodes'
        from (irb):5
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands/console.rb:110:in `start'
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands/console.rb:9:in `start'
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands/commands_tasks.rb:68:in `console'
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
        from /usr/local/lib/ruby/gems/2.2.0/gems/railties-4.2.9/lib/rails/commands.rb:17:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `'

app/models/f5_device.rb

class F5Device < F5Base
      has_many :nodes, :class_name => "F5Node", :foreign_key => "device_id"
      has_many :members, :through => :nodes
      has_many :group_items , :foreign_key => :device_id
      has_many :groups, :through => :group_items
      has_many :dependencies, :class_name => "Dependency", :foreign_key => :device_id
      has_many :device_applications, :class_name => "F5DeviceApplication", :foreign_key => :device_id
      has_many :applications, :through => :device_applications
      has_many :websphere_servers, :class_name => "IisDependency", :foreign_key => :f5_device_id

app/models/f5_node.rb

require 'f5'
class F5Node < F5Base
      has_many :bigips, :class_name => "F5Bigip", :foreign_key => :group_id, :primary_key => :group_id
      belongs_to :device, :class_name => "F5Device", :foreign_key => :device_id
      has_many :members, :class_name => "F5Member", :foreign_key => "node_id", :dependent => :destroy
      has_many :pools, :through => :members
      attr_accessor :ws, :bigip, :session_status, :monitor_status, :enabled_status, :status_description, :availability_status, :state
      after_initialize :set_ws


来源: stackexchange

问:
Compatible actionpack missing for a Rails 5.1.0rc1 to 5.1.0 migration
I've been trying to migrate my Rails app from 5.1.0rc1 to 5.1.0.

This is my gemfile:

```<code>gem 'rails', '~> 5.1.0'
gem 'mysql2', '>= 0.3.18', '< 0.5'
gem 'puma', '~> 3.0'
gem 'sass-rails', '~> 5.0'
gem 'turbolinks', '~> 5'
gem 'uglifier', '>= 1.3.0'
gem 'redis', '~> 3.3.3'
gem 'redis-rails', '~> 5.0.1'
gem 'jbuilder', '~> 2.5'
gem 'sidekiq', '~> 4.2.10'
gem 'active_model_serializers', '~> 0.10.5'
gem 'jwt', '~> 1.5.6'
gem "mini_magick", '~> 4.7.0'
gem 'rack-cors', "~> 0.4.1"
gem 'mandrill-api', "~> 1.0.53"
gem 'curb', "~> 0.9.3"
gem 'inherited_resources', '~> 1.7'
gem 'activeadmin', '~> 1.0.0'
gem 'coffee-rails', '~> 4.2.1'
gem 'therubyracer', git: 'https://github.com/cowboyd/therubyracer.git'
gem 'meta-tags', '~> 2.4.0'
gem 'slim', '~> 3.0.7'
</code>```

This is what I get from a bundle install:

```<code>Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    active_model_serializers (~> 0.10.5) was resolved to 0.10.5, which depends on
      actionpack (< 6, >= 4.1)

    activeadmin (~> 1.0.0) was resolved to 1.0.0, which depends on
      formtastic (~> 3.1) was resolved to 3.1.5, which depends on
        actionpack (>= 3.2.13)

    activeadmin (~> 1.0.0) was resolved to 1.0.0, which depends on
      inherited_resources (~> 1.7) was resolved to 1.7.0, which depends on
        actionpack (< 5.1, >= 3.2)

    rails (~> 5.1.0) was resolved to 5.1.0, which depends on
      actionpack (= 5.1.0)

    rails (~> 5.1.0) was resolved to 5.1.0, which depends on
      actionpack (= 5.1.0)

    rails (~> 5.1.0) was resolved to 5.1.0, which depends on
      actionpack (= 5.1.0)

    activeadmin (~> 1.0.0) was resolved to 1.0.0, which depends on
      ransack (~> 1.3) was resolved to 1.8.2, which depends on
        actionpack (>= 3.0)
</code>```

What could be wrong?

If it helps (but I doubt it), I work on a Docker container. I have deleted the Gemfile.lock to avoid conflicts.

答:
The problematic gem here is activeadmin's inherited_resources, the latest version of which specified actionpack (< 5.1, >= 3.2) when you asked your question.

Perhaps surprisingly, your previous release candidate version of actionpack, 5.1.0.rc1, satisfies the < 5.1 constraint, so you weren't blocked from upgrading to the release candidate, but were blocked from the final version.

A new version of inherited_resources was cut on May 3rd, which will have fixed things, but note that the current gemspec means you'll have the same issue when Rails goes to 5.2.

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to migrate my Rails app from 5.1.0rc1 to 5.1.0.

This is my gemfile:

gem 'rails', '~> 5.1.0'
gem 'mysql2', '>= 0.3.18', '< 0.5'
gem 'puma', '~> 3.0'
gem 'sass-rails', '~> 5.0'
gem 'turbolinks', '~> 5'
gem 'uglifier', '>= 1.3.0'
gem 'redis', '~> 3.3.3'
gem 'redis-rails', '~> 5.0.1'
gem 'jbuilder', '~> 2.5'
gem 'sidekiq', '~> 4.2.10'
gem 'active_model_serializers', '~> 0.10.5'
gem 'jwt', '~> 1.5.6'
gem "mini_magick", '~> 4.7.0'
gem 'rack-cors', "~> 0.4.1"
gem 'mandrill-api', "~> 1.0.53"
gem 'curb', "~> 0.9.3"
gem 'inherited_resources', '~> 1.7'
gem 'activeadmin', '~> 1.0.0'
gem 'coffee-rails', '~> 4.2.1'
gem 'therubyracer', git: 'https://github.com/cowboyd/therubyracer.git'
gem 'meta-tags', '~> 2.4.0'
gem 'slim', '~> 3.0.7'

This is what I get from a bundle install:

Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    active_model_serializers (~> 0.10.5) was resolved to 0.10.5, which depends on
      actionpack (< 6, >= 4.1)

    activeadmin (~> 1.0.0) was resolved to 1.0.0, which depends on
      formtastic (~> 3.1) was resolved to 3.1.5, which depends on
        actionpack (>= 3.2.13)

    activeadmin (~> 1.0.0) was resolved to 1.0.0, which depends on
      inherited_resources (~> 1.7) was resolved to 1.7.0, which depends on
        actionpack (< 5.1, >= 3.2)

    rails (~> 5.1.0) was resolved to 5.1.0, which depends on
      actionpack (= 5.1.0)

    rails (~> 5.1.0) was resolved to 5.1.0, which depends on
      actionpack (= 5.1.0)

    rails (~> 5.1.0) was resolved to 5.1.0, which depends on
      actionpack (= 5.1.0)

    activeadmin (~> 1.0.0) was resolved to 1.0.0, which depends on
      ransack (~> 1.3) was resolved to 1.8.2, which depends on
        actionpack (>= 3.0)

What could be wrong?

If it helps (but I doubt it), I work on a Docker container. I have deleted the Gemfile.lock to avoid conflicts.


问:
How to connect two differents nodes types (structures) using pointers?
I've been trying to figure out how to connect two different struct nodes using pointers. But I'm was not able to do that. See my draw bellow. At left I
have a "treeNode" with two pointers (below and right). The r-pointer connect to a different node called "branchNode" and for each "treeNode" I have five linked  "branchNodes".

Here is my problem: For example, if the "branchNode" 1
doesn't exist, I wound like to create a temporary node
to insert it. But I don't know how to make this temporary node
receive the memory address of the "branchNode" 2.

see image here
\nSee my code bellow:

main.cpp

```<code>#include "table.h"
#include <iostream>

int main(){

    Table xxx;

    xxx.addTreeNodes(2,100);
    xxx.addTreeNodes(3,100);
    xxx.addTreeNodes(1,100);

    return 0;
</code>```

table.h

```<code>#ifndef TABLE_H_
#define TABLE_H_

class Table{
public:
    Table();
    int treeAddress(int newAddress, int dim);
    void addTreeNodes(int pos, int value);

private:
    struct treeNode {
    public: class branchNode;
        int address;
        treeNode* right;
        treeNode* below;
    };

    struct branchNode : public treeNode{
        int address;
        int data;
        branchNode* next;
    };

    treeNode* treeCurr;
    treeNode* treeTemp;
    treeNode* head;
    branchNode* branchHead;

    int branchDim;

};

#endif
</code>```

table.cpp

```<code>#include "table.h"
#include <iostream>
#include <stddef.h>

Table::Table(){
    branchDim = 5;
    head = NULL;
    treeTemp = NULL;
    treeCurr = NULL;

    branchHead = NULL;

}

int Table::treeAddress(int Address, int dim){
    // This function is used to calculate the address
    // of treeNodes.
    float val = 1 + (int)((float)Address/(float)dim);
    if (Address % dim == 0){
        val--;
    }

    return val;
}

void Table::addTreeNodes(int pos, int value){
    // This part will create one treeNode in order, if
    // needed. Works fine, just skip this part.
    treeNode* tn = new treeNode;
    tn -> address = treeAddress(pos, branchDim);

    // if the table doesn't exist. Create one treeNode
    if (head == NULL){
        tn -> below = NULL;
        tn -> right = NULL;
        head = tn;
    }
    else{
        // insert treeNode before.
        if(tn -> address < head -> address){
            tn -> below = head;
            tn -> right = NULL;
            head = tn;
        }
        else{
            treeCurr = head;
            treeTemp = head;
            while(treeCurr != NULL && treeCurr -> address < tn -> address){
                treeTemp = treeCurr;
                treeCurr = treeCurr -> below;
            }

            // insert treeNode on tail.
            if (treeCurr == NULL && tn -> address > treeTemp -> address){
                treeTemp -> below = tn;
                tn -> below = treeCurr;
                tn -> right = NULL;
            }
            else{
            // insert treeNode between two others nodes.
                if (tn -> address < treeCurr -> address){
                    treeTemp -> below = tn;
                    tn -> below = treeCurr;
                    tn -> right = NULL;
                }
                else{
                    delete[] tn;
                }
            }
        }
    }

    // This part will create one branchNode. Here is the big problem...

    branchNode* bn = new branchNode;
    bn -> address = pos;

    treeCurr = head;
    int tPos = treeAddress(pos, branchDim);
    while(treeCurr != NULL && tPos != treeCurr -> address){
        treeCurr = treeCurr -> below;
    }
    //If the branch is empty.
    if (treeCurr -> right == NULL){
        treeCurr -> right = bn;
        bn -> next = NULL;
        bn -> address = pos;
    }

    else{
        //Here I wanna put the branchNode before the first branchNode.
        if (pos < (treeCurr -> right) -> address){
            branchHead = treeCurr -> right; // for some reason, I don't know why,
            bn -> next = branchHead;        // I can't do that!!!!!!!!!!.
            treeCurr -> right = bn;
            bn -> data = value;
        }
    }
}
</code>```

答:
Assuming there exist only one "treeNode" and some "branchNode" for simplicity. I was able to point correctly to another type of node, following the hint of @Rabbid76 (thanks!). Maybe there's another way, but I'm already happy.

main.cpp

```<code>#include "table.h"
#include <iostream>

int main(){

    Table xxx;

    xxx.addTreeNodes(5,100);
    xxx.addTreeNodes(3,140);
    xxx.addTreeNodes(2,20);

    xxx.print();

    return 0;
}
</code>```

table.h

```<code>#ifndef TABLE_H_
#define TABLE_H_

class Table{
public:
    Table();
    void addTreeNodes(int pos, int value);
    void print();

private:
    struct treeNode {
    public: class branchNode;
        treeNode* right;
        treeNode* below;
    };

    struct branchNode : public treeNode{
        int address;
        int data;
        branchNode* next;
    };

    branchNode* branchCurr;
    treeNode* head;
    treeNode* tn;
};

#endif
</code>```

table.cpp

```<code>#include "table.h"
#include <iostream>
#include <stddef.h>

Table::Table(){
    head = NULL;
    branchCurr = NULL;
    tn = new treeNode;
}

void Table::addTreeNodes(int pos, int value){

    branchNode* bn = new branchNode;
    bn -> address = pos;
    bn -> data = value;

    tn -> below = NULL;

    if (head == NULL){
        head = tn;
        bn -> next = NULL;
        tn -> right = bn;
    }
    else{
        if (pos < ((branchNode*)head -> right) -> address){
            branchCurr = (branchNode*)head -> right;
            bn -> address = pos;
            bn -> data = value;
            tn -> right = bn;
            bn -> next = branchCurr;
        }
        else{
            delete[] bn;
        }
    }
}

void Table::print(){
    branchCurr = (branchNode*)head -> right;
    while(branchCurr != NULL){
        std::cout << "address: " << branchCurr -> address
                  << ", stored value: " << branchCurr -> data <<  std::endl;
        branchCurr = branchCurr -> next;
    }
}
</code>```

Body:
I've been trying to figure out how to connect two different struct nodes using pointers. But I'm was not able to do that. See my draw bellow. At left I
have a "treeNode" with two pointers (below and right). The r-pointer connect to a different node called "branchNode" and for each "treeNode" I have five linked  "branchNodes".

Here is my problem: For example, if the "branchNode" 1
doesn't exist, I wound like to create a temporary node
to insert it. But I don't know how to make this temporary node
receive the memory address of the "branchNode" 2.

see image here
\nSee my code bellow:

main.cpp

#include "table.h"
#include <iostream>

int main(){

    Table xxx;

    xxx.addTreeNodes(2,100);
    xxx.addTreeNodes(3,100);
    xxx.addTreeNodes(1,100);

    return 0;

table.h

#ifndef TABLE_H_
#define TABLE_H_

class Table{
public:
    Table();
    int treeAddress(int newAddress, int dim);
    void addTreeNodes(int pos, int value);

private:
    struct treeNode {
    public: class branchNode;
        int address;
        treeNode* right;
        treeNode* below;
    };

    struct branchNode : public treeNode{
        int address;
        int data;
        branchNode* next;
    };

    treeNode* treeCurr;
    treeNode* treeTemp;
    treeNode* head;
    branchNode* branchHead;

    int branchDim;

};

#endif

table.cpp

#include "table.h"
#include <iostream>
#include <stddef.h>

Table::Table(){
    branchDim = 5;
    head = NULL;
    treeTemp = NULL;
    treeCurr = NULL;

    branchHead = NULL;

}

int Table::treeAddress(int Address, int dim){
    // This function is used to calculate the address
    // of treeNodes.
    float val = 1 + (int)((float)Address/(float)dim);
    if (Address % dim == 0){
        val--;
    }

    return val;
}

void Table::addTreeNodes(int pos, int value){
    // This part will create one treeNode in order, if
    // needed. Works fine, just skip this part.
    treeNode* tn = new treeNode;
    tn -> address = treeAddress(pos, branchDim);

    // if the table doesn't exist. Create one treeNode
    if (head == NULL){
        tn -> below = NULL;
        tn -> right = NULL;
        head = tn;
    }
    else{
        // insert treeNode before.
        if(tn -> address  address){
            tn -> below = head;
            tn -> right = NULL;
            head = tn;
        }
        else{
            treeCurr = head;
            treeTemp = head;
            while(treeCurr != NULL && treeCurr -> address < tn -> address){
                treeTemp = treeCurr;
                treeCurr = treeCurr -> below;
            }

            // insert treeNode on tail.
            if (treeCurr == NULL && tn -> address > treeTemp -> address){
                treeTemp -> below = tn;
                tn -> below = treeCurr;
                tn -> right = NULL;
            }
            else{
            // insert treeNode between two others nodes.
                if (tn -> address < treeCurr -> address){
                    treeTemp -> below = tn;
                    tn -> below = treeCurr;
                    tn -> right = NULL;
                }
                else{
                    delete[] tn;
                }
            }
        }
    }

    // This part will create one branchNode. Here is the big problem...

    branchNode* bn = new branchNode;
    bn -> address = pos;

    treeCurr = head;
    int tPos = treeAddress(pos, branchDim);
    while(treeCurr != NULL && tPos != treeCurr -> address){
        treeCurr = treeCurr -> below;
    }
    //If the branch is empty.
    if (treeCurr -> right == NULL){
        treeCurr -> right = bn;
        bn -> next = NULL;
        bn -> address = pos;
    }

    else{
        //Here I wanna put the branchNode before the first branchNode.
        if (pos < (treeCurr -> right) -> address){
            branchHead = treeCurr -> right; // for some reason, I don't know why,
            bn -> next = branchHead;        // I can't do that!!!!!!!!!!.
            treeCurr -> right = bn;
            bn -> data = value;
        }
    }
}

Body:
Assuming there exist only one "treeNode" and some "branchNode" for simplicity. I was able to point correctly to another type of node, following the hint of @Rabbid76 (thanks!). Maybe there's another way, but I'm already happy.

main.cpp

#include "table.h"
#include <iostream>

int main(){

    Table xxx;

    xxx.addTreeNodes(5,100);
    xxx.addTreeNodes(3,140);
    xxx.addTreeNodes(2,20);

    xxx.print();

    return 0;
}

table.h

#ifndef TABLE_H_
#define TABLE_H_

class Table{
public:
    Table();
    void addTreeNodes(int pos, int value);
    void print();

private:
    struct treeNode {
    public: class branchNode;
        treeNode* right;
        treeNode* below;
    };

    struct branchNode : public treeNode{
        int address;
        int data;
        branchNode* next;
    };

    branchNode* branchCurr;
    treeNode* head;
    treeNode* tn;
};

#endif

table.cpp

#include "table.h"
#include <iostream>
#include <stddef.h>

Table::Table(){
    head = NULL;
    branchCurr = NULL;
    tn = new treeNode;
}

void Table::addTreeNodes(int pos, int value){

    branchNode* bn = new branchNode;
    bn -> address = pos;
    bn -> data = value;

    tn -> below = NULL;

    if (head == NULL){
        head = tn;
        bn -> next = NULL;
        tn -> right = bn;
    }
    else{
        if (pos < ((branchNode*)head -> right) -> address){
            branchCurr = (branchNode*)head -> right;
            bn -> address = pos;
            bn -> data = value;
            tn -> right = bn;
            bn -> next = branchCurr;
        }
        else{
            delete[] bn;
        }
    }
}

void Table::print(){
    branchCurr = (branchNode*)head -> right;
    while(branchCurr != NULL){
        std::cout << "address: " << branchCurr -> address
                  << ", stored value: " << branchCurr -> data <<  std::endl;
        branchCurr = branchCurr -> next;
    }
}


问:
HTTP authentication logout via PHP
What is the correct way to log out of HTTP authentication protected folder?

There are workarounds that can achieve this, but they are potentially dangerous because they can be buggy or don't work in certain situations / browsers. That is why I am looking for correct and clean solution.

答:
AFAIK, there's no clean way to implement a "logout" function when using htaccess (i.e. HTTP-based) authentication.

This is because such authentication uses the HTTP error code '401' to tell the browser that credentials are required, at which point the browser prompts the user for the details.  From then on, until the browser is closed, it will always send the credentials without further prompting.

OwnerDisplayName: JS

ContentLicense: CC BY-SA 2.5

Title: HTTP authentication logout via PHP

LastEditorDisplayName: JS

OwnerDisplayName: Alnitak


问:
Should you correct compiler warnings about type conversions using explicit typecasts?
In my current project, the compiler shows hundreds of warnings about type conversions.

There is a lot of code like this

```<code>iVar = fVar1*fVar2/fVar3;
// or even
iVar = fVar1*fVar2/fVar3+.5f;
</code>```

which intentionally assign float values to int.

Of course, I could fix these warnings using

```<code>iVar = (int)(...);
</code>```

but that looks kind of ugly.

Would you rather live with the ugliness or live with the warnings?

Or is there even a clean solution?

答:
Yes.

You should always fix the compiler warnings. Several reasons:

*) It may be the cause of an error and need an actual fix rather than just a cast. You won't know until you look.

*) Actual coding errors that manifest as warnings can get lost in the noise generated by hundreds of warnings

*) It makes it clear to other coders that you really did mean to use that variable of the wrong type/sign there. That it is deliberate.

*) It makes it clear and explicit that the type and/or signedness is being changed. If your variable names do not contain an indication of the type and signedness it may not be obvious that this is occurring.

Body:
In my current project, the compiler shows hundreds of warnings about type conversions.

There is a lot of code like this

iVar = fVar1*fVar2/fVar3;
// or even
iVar = fVar1*fVar2/fVar3+.5f;

which intentionally assign float values to int.

Of course, I could fix these warnings using

iVar = (int)(...);

but that looks kind of ugly.

Would you rather live with the ugliness or live with the warnings?

Or is there even a clean solution?


问:
Classic ASP Page that uses JavaScript crashing on new ActiveXObject
I have a asp classic page but the language is set on javascript. like this

<%@ Language=JavaScript %>

if I try to create a http request like this

```<code>   var xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.4.0");
</code>```

or

```<code>   var xmlhttp = new XMLHttpRequest();
</code>```

the page just crashes with a generic error saying like an internal server error occurred. Does anyone know how I can investigate and fix this?

Thanks

答:
First, you need to enable detailed error pages in IIS to get rid of generic error pages.

I'd bet it was a ActiveX component can't create object error but see How To Configure IIS7 To Show ASP Errors? it's a hepful guide with screenshots.

MSXML 4.0 is no longer supported by Microsoft.

Using MSXML 6.0 instead is recommended. It's compatible with 4.0, so replacing 4.0 with 6.0 is sufficient.

See MSXML Roadmap for more information.

So, use var xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.6.0"); or if you too picky, instantiate the object like below for the sake of backward compatibility.

```<code>var xmlhttp;
try {
    xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.4.0");
}
catch(e) {
    try
    {
        xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.6.0");
    }
    catch(e)
    {
        throw "object can't created";
    }
}
</code>```

Body:
I have a asp classic page but the language is set on javascript. like this

<%@ Language=JavaScript %>

if I try to create a http request like this

   var xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.4.0");

or

   var xmlhttp = new XMLHttpRequest();

the page just crashes with a generic error saying like an internal server error occurred. Does anyone know how I can investigate and fix this?

Thanks

Body:
First, you need to enable detailed error pages in IIS to get rid of generic error pages.

I'd bet it was a ActiveX component can't create object error but see How To Configure IIS7 To Show ASP Errors? it's a hepful guide with screenshots.

MSXML 4.0 is no longer supported by Microsoft.

Using MSXML 6.0 instead is recommended. It's compatible with 4.0, so replacing 4.0 with 6.0 is sufficient.

See MSXML Roadmap for more information.

So, use var xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.6.0"); or if you too picky, instantiate the object like below for the sake of backward compatibility.

var xmlhttp;
try {
    xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.4.0");
}
catch(e) {
    try
    {
        xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.6.0");
    }
    catch(e)
    {
        throw "object can't created";
    }
}


问:
R sapply/lapply with multiple ifelse statements
I'm trying to simplify the following multiple ifelse code using sapply or lapply (still can't distinguish them).

My goal is to allocate points based on placement like shown below.

```<code>df$Point <- ifelse(df$Placement_v2 <= 1, 10,
ifelse(df$Placement_v2 <= 10, 9,
ifelse(df$Placement_v2 <= 25, 8,
ifelse(df$Placement_v2 <= 50, 7, 1) )))
</code>```

This code works okay, but I want to make a dataframe and simply my code above using sapply or lapply (or anyother function).

I've tried this code but is not working as expected. Only the rows with placement 1 get 10 points and other rows end up with 1.

<2nd code>

```<code>df$Point <- sapply(df2$Placement, function(x) ifelse(df$Placement_v2 <= x, df2$Point[df2$Placement == x], 1 ) )
</code>```

How can I solve this problem?

答:
You could create a dataframe with values and replacements. Then you can use cut to lookup the appropriate value

```<code>dict = data.frame(replacement = c(10, 9, 8, 7, 1, 1),
    values = c(0, 1, 10, 25, 50, 1e5))

#DATA
set.seed(42)
placement = sample(1:100, 15)

cbind(placement,
    new_placement = dict$replacement[as.integer(cut(placement, breaks = dict$values))])
#     placement new_placement
# [1,]        92             1
# [2,]        93             1
# [3,]        29             7
# [4,]        81             1
# [5,]        62             1
# [6,]        50             7
# [7,]        70             1
# [8,]        13             8
# [9,]        61             1
#[10,]        65             1
#[11,]        42             7
#[12,]        91             1
#[13,]        83             1
#[14,]        23             8
#[15,]        40             7
</code>```

Body:
I'm trying to simplify the following multiple ifelse code using sapply or lapply (still can't distinguish them).

My goal is to allocate points based on placement like shown below.

df$Point <- ifelse(df$Placement_v2 <= 1, 10,
ifelse(df$Placement_v2 <= 10, 9,
ifelse(df$Placement_v2 <= 25, 8,
ifelse(df$Placement_v2 <= 50, 7, 1) )))

This code works okay, but I want to make a dataframe and simply my code above using sapply or lapply (or anyother function).

I've tried this code but is not working as expected. Only the rows with placement 1 get 10 points and other rows end up with 1.

<2nd code>

df$Point <- sapply(df2$Placement, function(x) ifelse(df$Placement_v2 <= x, df2$Point[df2$Placement == x], 1 ) )

How can I solve this problem?

Body:
You could create a dataframe with values and replacements. Then you can use cut to lookup the appropriate value

dict = data.frame(replacement = c(10, 9, 8, 7, 1, 1),
    values = c(0, 1, 10, 25, 50, 1e5))

#DATA
set.seed(42)
placement = sample(1:100, 15)

cbind(placement,
    new_placement = dict$replacement[as.integer(cut(placement, breaks = dict$values))])
#     placement new_placement
# [1,]        92             1
# [2,]        93             1
# [3,]        29             7
# [4,]        81             1
# [5,]        62             1
# [6,]        50             7
# [7,]        70             1
# [8,]        13             8
# [9,]        61             1
#[10,]        65             1
#[11,]        42             7
#[12,]        91             1
#[13,]        83             1
#[14,]        23             8
#[15,]        40             7


问:
Control Width Of Div Elements Inside Jumbotron
I have some text inside a jumbotron that has a complex background image.  To make the text stand out, I added a background color to the containing div to make it more readable.  However, the div width is the same size as the columns.  Is there any way to set the width so that the div is the same width as the text?  I don't want extra space to either side of the centered text.</p>

```<code><div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-lg-10 col-lg-push-1 text-center" style="background-color: rgba(0,0,0,0.5); border-radius: 25px;">
                <h1>Some text, more text,<br>and more text</h1>
                <p><a href="" class="btn btn-primary btn-lg">Learn more <i class="fa fa-angle-double-right"></i></a></p>
            </div>
        </div>
    </div>
</div>
</code>```

答:
You can do it like that

add text-center in row div

give display: inline-block to your custom div. and remove another classes

Hope it will helps you

.customdiv {
background-color: rgba(0,0,0,0.5); border-radius: 25px; text-align:center; display:inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="jumbotron">
    <div class="container">
        <div class="row text-center">
            <div class="customdiv">
                <h1>Some text, more text,<br>and more text</h1>
                <p>Learn more <i class="fa fa-angle-double-right"></i></p>
            </div>
        </div>
    </div>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></code>```

Body:
I have some text inside a jumbotron that has a complex background image.  To make the text stand out, I added a background color to the containing div to make it more readable.  However, the div width is the same size as the columns.  Is there any way to set the width so that the div is the same width as the text?  I don't want extra space to either side of the centered text.

Some text, more text,
and more text

Learn more

Body:
You can do it like that

add text-center in row div

give display: inline-block to your custom div. and remove another classes

Hope it will helps you

.customdiv {
background-color: rgba(0,0,0,0.5); border-radius: 25px; text-align:center; display:inline-block;
}

<div class="jumbotron">
    <div class="container">
        <div class="row text-center">
            <div class="customdiv">
                <h1>Some text, more text,<br>and more text</h1>
                <p><a href="" class="btn btn-primary btn-lg">Learn more <i class="fa fa-angle-double-right"></i></a></p>
            </div>
        </div>
    </div>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">


问:
efilogin-helper running continuously at high cpu on MacBook Pro
There is a process launched by launchd called efilogin-helper running as root, which is continuously running at high CPU load (60% to 120%)

Do you know what this process is and how I can get it under control?

There is surprisingly little information on Google.

Also, what would be a good debug method to go about solving these sorts of issues myself?

答:
Go to system preferences => Desktop & Screen Saver

Select Apple->Desktop Pictures and choose the first option.

efilogin-helper will eventually quit after about a minute and no longer be a problem.

Bizarre but true!

(Once you have confirmed that you have indeed resolved the issue you can then probably reselect your preferred wallpaper without a problem.)


问:
iPhone App Icons - Exact Radius?
I'm trying to create the icon for my iPhone app, but don't know how to get the exact radius that the iPhone's icons use. I've searched and searched for a tutorial or a template but can't find one.

I'm sure that I'm just a moron, but how do you get the rounded corners exactly right with your icon from Illustrator or Photoshop?

Edit:

What's the radius for the Retina iPad?

答:
If not considering stroke, the exact radius is actually 10px for 57x57 icon.

I get this info from iconreference.

Title: iPhone App Icons - Exact Radius?


问:
bing map v7 to v8 migration - script importing issue
Ok so I have looked around for a solution for this and I am sure someone will say that is a duplicate topic but I am very confused as to why this doesn't work.

This is a basic example of the code I have right now

main.html

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="main.js"></script>
</head>

<body>
    <div id="myMap" style="position:relative;width:600px;height:400px;"></div>
</body>
<script>
    var url =
    //'http://www.bing.com/api/maps/mapcontrol?branch=experimental&callback=GetMap';
    'https://www.bing.com/mapspreview/sdk/mapcontrol';
    loadScript(url, test_function);
    function test_function() {
        console.log('inside test_function before map');
        map = new Microsoft.Maps.Map('#myMap', {
            credentials: 'My Bing Maps Key'});
        console.log('inside test_function after map');
    };
</script>

</html>
</code>```

main.js

```<code>function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";
    script.async = true;
    script.defer = true;

    if (script.readyState){  //IE
        console.log('inside IE block');
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        console.log('inside Other block');
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
</code>```

Console output

```<code>main.js:18 inside Other block
main.html:17 inside test_function before map
mapcontrol:11 Uncaught TypeError: Cannot read property 'prototype' of null
    at k (mapcontrol:11)
    at n.h [as create] (mapcontrol:11)
    at e (mapcontrol:11)
    at t.l [as instance] (mapcontrol:11)
    at n.h [as create] (mapcontrol:11)
    at e (mapcontrol:11)
    at t.l [as instance] (mapcontrol:11)
    at new Microsoft.Maps.Map (mapcontrol:13)
    at test_function (main.html:18)
    at HTMLScriptElement.script.onload (main.js:20)
</code>```

I can get a basic example working but when I try to do this method of creating the script element and appending it I get nothing. Since this is the way it was implemented in the larger application that this came from in v7 I am not trying to re-architect it.

I have tried things like jQuery getScript and what not.

Please let me know what you think!!! Thanks.

答:
First thing I can think to say is that you should probably remove your credentials from your publicly posted question. Just a thought.

Secondly, the error is due to attempting to interact with the map before the map is loaded.

I've personally never seen a script loaded in that manner before, but I guess it works - at least in some cases, but probably not this one. I assume you have a reason for doing it in such a way.

Anyway, with my lack of knowledge about it, I can only assume that what is happening is that the script is being loaded and your callback (test_function) is being called as the code appears to suggest it does.

However, the script being loaded and Bing Maps being loaded are, I suspect, two different things in this case.

Your initially commented out url with the &callback=GetMap is the documented way of async loading Bing Maps. Your GetMap function will be called by Bing Maps once it has finished loading. With this particular code, callback=test_function would be what you want.

So test_function should be initiated by Bing Maps itself, not being passed through your script loading function (again, making assumptions about how it works). The loading function, I guess, doesn't actually want to do anything other than get that script in place, so no callback method; Bing Maps will handle that for you.

Here's a Plunker for you of it working.

Body:
Ok so I have looked around for a solution for this and I am sure someone will say that is a duplicate topic but I am very confused as to why this doesn't work.

This is a basic example of the code I have right now

main.html

<!DOCTYPE html>

    <meta charset="UTF-8">

main.js

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";
    script.async = true;
    script.defer = true;

    if (script.readyState){  //IE
        console.log('inside IE block');
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        console.log('inside Other block');
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

Console output

main.js:18 inside Other block
main.html:17 inside test_function before map
mapcontrol:11 Uncaught TypeError: Cannot read property 'prototype' of null
    at k (mapcontrol:11)
    at n.h [as create] (mapcontrol:11)
    at e (mapcontrol:11)
    at t.l [as instance] (mapcontrol:11)
    at n.h [as create] (mapcontrol:11)
    at e (mapcontrol:11)
    at t.l [as instance] (mapcontrol:11)
    at new Microsoft.Maps.Map (mapcontrol:13)
    at test_function (main.html:18)
    at HTMLScriptElement.script.onload (main.js:20)

I can get a basic example working but when I try to do this method of creating the script element and appending it I get nothing. Since this is the way it was implemented in the larger application that this came from in v7 I am not trying to re-architect it.

I have tried things like jQuery getScript and what not.

Please let me know what you think!!! Thanks.


问:
Is use of `auto` for a function argument against the C++ standard?
Does code like this:

```<code>auto add(auto a, auto b) { return a + b; }
</code>```

violate the ISO c++14 standard? Will future versions of the standard allow code to be written like that?

答:
If you want that to mean that you can pass any type to the function, make it a template:

```<code>template <typename T1, typename T2> int add(T1 a, T2 b);
</code>```

Alternatively, you could use a lambda:

```<code>auto add = [](const auto& a, auto& b){ return a + b; };
</code>```

is Proposal for Generic (Polymorphic) Lambda Expressions. However, generic lambdas are a C++14 feature.

Body:
Does code like this:

auto add(auto a, auto b) { return a + b; }

violate the ISO c++14 standard? Will future versions of the standard allow code to be written like that?

Body:
If you want that to mean that you can pass any type to the function, make it a template:

template <typename T1, typename T2> int add(T1 a, T2 b);

Alternatively, you could use a lambda:

auto add = [](const auto& a, auto& b){ return a + b; };

is Proposal for Generic (Polymorphic) Lambda Expressions. However, generic lambdas are a C++14 feature.


问:
split a string on newlines in .NET
I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?</p>

答:
Very easy, actually.

VB.NET:

```<code>Private Function SplitOnNewLine(input as String) As String
    Return input.Split(Environment.NewLine)
End Function
</code>```

C#:

```<code>string splitOnNewLine(string input)
{
    return input.split(environment.newline);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: split a string on newlines in .NET

Body:
Very easy, actually.

VB.NET:

Private Function SplitOnNewLine(input as String) As String
    Return input.Split(Environment.NewLine)
End Function

C#:

string splitOnNewLine(string input)
{
    return input.split(environment.newline);
}


问:
(Mysql) What is the most efficient way to store table changes?
I am developing a web application with mysql, and I have several tables including user and article.

As I would like to record the user that has updated the selected article, I thought about three possibilities:

Add two columns to the table article: ART_USE_ID (to know who has changed) and ART_date (to save the datetime).

Create a third table changes with CHA_USE_ID, CHA_ART_ID and CHA_date, which would have an entry every time a user changes the table.

Make a combination of both: create a table changes but keep a ART_date to retrieve more quickly the date of the last change.

In my opinion, the third one is redundant, and the first one badly conceptualised (and only the last change is kept). Even though the second one appears to be good for only one table (article), I am afraid it gets more complicated and very slow if changes must be saved for more than 30 tables -- that means the changes table would have 30 foreign key(?!)

What is the best way? What is your opinion about it?

答: Do you really want to know each person who modified the article?, if the answer is yes, you must use the second one, i think the best option is the first (taking in count speed, time) and i think you only need to know the last one who modified the article.</p>


问:
How to make a responsive two color background?
So this is what I'm trying to accomplish:

Desktop image:

Mobile image:

I already have the boxes but I don't know how to add a 2 color background. I'm using bootstrap.

This is my code so far

body {
  background-color: #F9F9F9;
}

#container {
  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

<div class="container">
  <div class="row">
    <div class="col-md-12">
      BOX 1
    </div>
  </div>

  <div class="row">
    <div class="col-sm-4 col-md-6" style="margin-bottom:20px">
      BOX 2
    </div>
  </div>

  <div clas="row">
    <div class="col-sm-4 col-md-6" style="margin-bottom:20px">
      BOX 3
    </div>
  </div>
</div></code>```

答:
You can achieve this via linear-gradient:

body {
  background: linear-gradient(to bottom, #007cc1 100px, #fff 100px);
  margin: 0;
  min-height: 100vh;
}```

Body:
So this is what I'm trying to accomplish:

Desktop image:

Mobile image:

I already have the boxes but I don't know how to add a 2 color background. I'm using bootstrap.

This is my code so far

body {
  background-color: #F9F9F9;
}

#container {
  margin: auto;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

      BOX 1

      BOX 2

      BOX 3


答:
MySQL has a feature called the Audit Log for this purpose. The idea is that the "audit" which is a series of events for data changes, is written to a log file outside the database. That way you can inspect the log for changes, you can see multiple changes to the same data, you can expire the logs, and so on.

The audit log requires a plugin implementation to do its job. MySQL makes an enterprise audit plugin, but it's not free—you have to be a paying customer to get MySQL Enterprise.

There are a few free alternatives for audit log plugin implementations, too.

You might like to try the Percona Audit Log Plugin. This is an optional plugin that is shipped with Percona Server (a branch of MySQL Community Edition). You just have to enable the plugin.

Documentation for installation and configuration: https://www.percona.com/doc/percona-server/5.7/management/audit_log_plugin.html

Title: (Mysql) What is the most efficient way to store table changes?

Body:
I am developing a web application with mysql, and I have several tables including user and article.

As I would like to record the user that has updated the selected article, I thought about three possibilities:

Add two columns to the table article: ART_USE_ID (to know who has changed) and ART_date (to save the datetime).

Create a third table changes with CHA_USE_ID, CHA_ART_ID and CHA_date, which would have an entry every time a user changes the table.

Make a combination of both: create a table changes but keep a ART_date to retrieve more quickly the date of the last change.

In my opinion, the third one is redundant, and the first one badly conceptualised (and only the last change is kept). Even though the second one appears to be good for only one table (article), I am afraid it gets more complicated and very slow if changes must be saved for more than 30 tables -- that means the changes table would have 30 foreign key(?!)

What is the best way? What is your opinion about it?


问:
How to schedule events with msql
I'm trying to make an event that will execute every 1 hour.

Here is the code.

```<code>mysql> DROP EVENT IF EXISTS `clean`;

CREATE EVENT IF NOT EXISTS `clean`
       ON SCHEDULE
         EVERY 1 HOUR
         STARTS '2017-07-07 16:00.00'
         DO
           SET @isTime = IF(table_name.programed_time = NOW(), 'y', 'n');
           IF @isTime = 'y' THEN DELETE FROM `cell_name`
             WHERE `cell_name` = 'value'
</code>```

I want the event to run only on Mondays at 16:00. So in my app I have the code to save the date of each 1st Monday of each month at 16:00 in a table.

But I'm having this error when I run this query.

```<code>Unknown type of declaration near to IF.
Something is wrong in its syntax near 'IF @isTime ='y'
THEN DELETE FROM `cell_name` WHERE `cell_name 'in the line
</code>```

Someone could tell me what I doing wrong.

答:
Scheduling of events in mysql involves you understanding how triggers work. Just check out this detailed tutorial and I believe it would go a long way. https://www.sitepoint.com/how-to-create-mysql-events/

Alternatively

Based on your question I really believe that cronjob will be best suited for your need. Check out this article. https://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428

Title: How to schedule events with msql

Body:
I'm trying to make an event that will execute every 1 hour.

Here is the code.

mysql> DROP EVENT IF EXISTS `clean`;

CREATE EVENT IF NOT EXISTS `clean`
       ON SCHEDULE
         EVERY 1 HOUR
         STARTS '2017-07-07 16:00.00'
         DO
           SET @isTime = IF(table_name.programed_time = NOW(), 'y', 'n');
           IF @isTime = 'y' THEN DELETE FROM `cell_name`
             WHERE `cell_name` = 'value'

I want the event to run only on Mondays at 16:00. So in my app I have the code to save the date of each 1st Monday of each month at 16:00 in a table.

But I'm having this error when I run this query.

Unknown type of declaration near to IF.
Something is wrong in its syntax near 'IF @isTime ='y'
THEN DELETE FROM `cell_name` WHERE `cell_name 'in the line

Someone could tell me what I doing wrong.


问:
Getting css output using webpack ExtractTextPlugin
I am trying to get css requires to work in webpack using the ExtractTextPlugin but with no success

I want a separate css file rather than inlining any css.

Here is my webpack config:

```<code>var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  devtool: 'eval',
  entry: [
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server',
    './scripts/index'
  ],
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js',
    publicPath: '/scripts/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new ExtractTextPlugin('styles/styles.css', {
      allChunks: true
    })
  ],
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loaders: ['react-hot', 'babel'],
      include: path.join(__dirname, 'scripts')
    },
    {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
    }]
  }
};
</code>```

index.js:

```<code>import React from 'react';
import App from './App';

React.render(<App />, document.getElementById('root'));
</code>```

App.js:

```<code>import React from 'react';

require('../styles/app.css');

export default class App extends React.Component {
  render() {
    return (
      <h1>Hello, world.</h1>
    );
  }
}
</code>```

index.html:

```<code><html>
  <head>
    <link rel="stylesheet" href="/styles/styles.css">
  </head>
  <body>
    <div id='root'></div>
  </body>
  <script src="/scripts/bundle.js"></script>
</html>
</code>```

styles.css is returning 404

Any idea what could be going wrong here. If I don't use the ExtractTextPlugin and just do this in config:

```<code>module: {
        loaders: [
            { test: /\.css$/, loader: "style-loader!css-loader" }
        ]
    }
</code>```

then I get the css applied to the page correctly but obviously this is not coming from a css file

This is my first attempt at using webpack so probably doing some noob mistake

Any ideas?

答:
Using css-loader and style-loader together first parse your CSS, then turn it into style nodes, which can be imported in Webpack just like code. I don't understand why you'd want this artificial relationship built between your JavaScript and your CSS.

The above approach emits CSS again in the end. Why put your code through a round trip like that? Use raw-loader and add your main CSS file to your entry points. You lose any error-checking that css-loader performs, but your compilation happens much faster. But if you're using something like sass-loader, you'll still get all the error checking.

Body:
I am trying to get css requires to work in webpack using the ExtractTextPlugin but with no success

I want a separate css file rather than inlining any css.

Here is my webpack config:

var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  devtool: 'eval',
  entry: [
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server',
    './scripts/index'
  ],
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js',
    publicPath: '/scripts/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new ExtractTextPlugin('styles/styles.css', {
      allChunks: true
    })
  ],
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loaders: ['react-hot', 'babel'],
      include: path.join(__dirname, 'scripts')
    },
    {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
    }]
  }
};

index.js:

import React from 'react';
import App from './App';

React.render(<App />, document.getElementById('root'));

App.js:

import React from 'react';

require('../styles/app.css');

export default class App extends React.Component {
  render() {
    return (

Hello, world.

    );
  }
}

index.html:

    <link rel="stylesheet" href="/styles/styles.css">

styles.css is returning 404

Any idea what could be going wrong here. If I don't use the ExtractTextPlugin and just do this in config:

module: {
        loaders: [
            { test: /\.css$/, loader: "style-loader!css-loader" }
        ]
    }

then I get the css applied to the page correctly but obviously this is not coming from a css file

This is my first attempt at using webpack so probably doing some noob mistake

Any ideas?


问:
IQueryable with Linq expression resulting in NullReferenceException
The following function results in a NullReferenceException because it is referencing m.tags, which has not been declared in the JSON object. This is intentional. I need to query for all JSON objects that have no existing tags object.

SelectNext

```<code>TweetModel tweet = client
    .CreateDocumentQuery<TweetModel>( UriFactory.CreateDocumentCollectionUri( databaseName, collectionName), queryOptions )
    .Where( m => m.tags == null )
    .ToList()
    .FirstOrDefault();
</code>```

Example Document

```<code>{
  "timestamp": "2017-07-05T19:31:18.918Z",
  "topic": "Trump",
  "score": "1",
  "sentiment": "positive",
  "text": "@gjacquette @travi44 @WSJ Where did I say trump shouldn't hire a lawyer? I said the fact his lawyers are hiring law… ",
  "id": "882683325495816192",
  "retweet_count": 0,
  "time_zone": null,
  "lang": "en",
  "screen_name": "bernielove1969"
}
</code>```

Declaring empty values for the tags object solves the exception, so I am certain that this is the problem, I'm just not sure how to fix it.

I have tried modifying m => m.tags == null to !(m => m.tags != null) with no luck as well as a variety of other solutions throughout the last couple of hours. Suggestions are welcomed.

答:
This is a bit of a shot in the dark, but I figured I'd throw it out in case it helps.  It sounds like it's not an issue of m.tag being null, but that m is a dynamically created object that may not have a tag property at all.  It's not that it's null/not-null, it's that it may not even be there in the object as a property or as a field.

Have you tried looking at something like:

```<code>m.GetType().GetField("tag") == null  // or...
m.GetType().GetProperty("tag") == null
</code>```

... just something to try.

Body:
The following function results in a NullReferenceException because it is referencing m.tags, which has not been declared in the JSON object. This is intentional. I need to query for all JSON objects that have no existing tags object.

SelectNext

TweetModel tweet = client
    .CreateDocumentQuery<TweetModel>( UriFactory.CreateDocumentCollectionUri( databaseName, collectionName), queryOptions )
    .Where( m => m.tags == null )
    .ToList()
    .FirstOrDefault();

Example Document

{
  "timestamp": "2017-07-05T19:31:18.918Z",
  "topic": "Trump",
  "score": "1",
  "sentiment": "positive",
  "text": "@gjacquette @travi44 @WSJ Where did I say trump shouldn't hire a lawyer? I said the fact his lawyers are hiring law… ",
  "id": "882683325495816192",
  "retweet_count": 0,
  "time_zone": null,
  "lang": "en",
  "screen_name": "bernielove1969"
}

Declaring empty values for the tags object solves the exception, so I am certain that this is the problem, I'm just not sure how to fix it.

I have tried modifying m => m.tags == null to !(m => m.tags != null) with no luck as well as a variety of other solutions throughout the last couple of hours. Suggestions are welcomed.

Body:
This is a bit of a shot in the dark, but I figured I'd throw it out in case it helps.  It sounds like it's not an issue of m.tag being null, but that m is a dynamically created object that may not have a tag property at all.  It's not that it's null/not-null, it's that it may not even be there in the object as a property or as a field.

Have you tried looking at something like:

m.GetType().GetField("tag") == null  // or...
m.GetType().GetProperty("tag") == null

... just something to try.


问:
Wpf Animation Best Practices
I am looking for any best practices or guidelines regarding animation in WPF. Especially information regarding performance considerations.</p>

答:
After I have gained a bit more experience in this field since I have asked the question, I will answer this myself. My experience comes from working on the WPF mind mapping application NovaMind - We have done lots of animations lately for our Presenter feature in NovaMind Platinum :-)

The MSDN section on Optimizing WPF Application Performance has some useful information about general considerations when writing WPF apps:

http://msdn.microsoft.com/en-us/library/aa970683.aspx

Here are some bits which I have found especially useful and are related to animation:

The CompositionTarget.Rendering event causes WPF to continuously animate. If you use this event, detach it at every opportunity.

When you use a Brush to set the Fill or Stroke of an element, it is better to set the Brush.Opacity value rather than the setting the element's Opacity property. Modifying an element's Opacity property can cause WPF to create a temporary surface.

You may be able to update a Transform rather than replacing it as the value of a RenderTransform property. This is particularly true in scenarios that involve animation. By updating an existing Transform, you avoid initiating an unnecessary layout calculation.

Here is what I have learned through trial and error:

Say, you have a couple of elements with a Effect such as the BlurEffect applied. It is way faster to apply the effect to the container of these elements rather than the elements themselves. Even though the effect is hardware accelerated, WPF doesn't seem to be good at handling a number of small items with effects. - If you don't want the same blur radius and cannot group them in a container with the effect applied, it is actually faster to render the element to a bitmap (in software) and then animate the bitmap around (if that is possible). Having effects (or opacity for that matter) on objects quickly kills performance when animating.

Setting the opacity on the brush rather than the element (as mentioned further above) makes a huge performance difference when animating objects.

Keep the number of visuals down. Animating a large number of particles is difficult, even with the above tips. In this case you may need to revert to WriteableBitmap instead.

I have also heard that it is faster to render many little objects by overriding OnRender in the container and then rendering them using the drawingContext rather than adding them to the visual tree directly. In practice this didn't make any difference in my scenario (when rendering around 300 ellipse geometries) but it might be helpful in some scenarios. The theory sounds solid.

Finally, I have found the animation classes built into WPF way too cumbersome and had much more fun and success using the underdog of animation libraries: Artefact Animator. Seriously, give it a try. (it is also available for Silverlight) It is what animating (in code) should have been like.

All is not rainbows and unicorns though. I still find it impossible to create truly fluid animations when running full screen in higher resolutions. More on that in my question How to know why an animation stutters? - I would appreciate any input on that.

cheers, good luck and if you have something cool to show, let me know :)

Title: Wpf Animation Best Practices


答:
Since your event has more than one statement, your issue is probably that you need to convert the definition to something like this:

```<code>DELIMITER $$
CREATE EVENT IF NOT EXISTS `clean` ON SCHEDULE EVERY 1 HOUR STARTS '2017-07-07 16:00.00'
DO
BEGIN
   DECLARE isTime CHAR(1);
   SET isTime := IF(table_name.programed_time = NOW(), 'y', 'n');
   IF isTime = 'y' THEN
      DELETE FROM `cell_name` WHERE `cell_name` = 'value';
   END IF;
END$$

DELIMITER ;
</code>```

Basically, enclose the body in BEGIN... END

Title: How to schedule events with msql

Body:
Since your event has more than one statement, your issue is probably that you need to convert the definition to something like this:

DELIMITER $$
CREATE EVENT IF NOT EXISTS `clean` ON SCHEDULE EVERY 1 HOUR STARTS '2017-07-07 16:00.00'
DO
BEGIN
   DECLARE isTime CHAR(1);
   SET isTime := IF(table_name.programed_time = NOW(), 'y', 'n');
   IF isTime = 'y' THEN
      DELETE FROM `cell_name` WHERE `cell_name` = 'value';
   END IF;
END$$

DELIMITER ;

Basically, enclose the body in BEGIN... END


问:
JS: dynamically populate/combine object with nested objects/properties > do we have a simpler way?
The problem: I've a JS global var that I've to check if it as an object with "menus configurations" and populate with the missing configurations.

So this work is based on this AS2:

```<code>        var result_array = re.result.items;

        _global.menu_array = new Array();
        var menu_type_num:Number = -1;
        var menu_group_num:Number = -1;
        var menu_id_num:Number = -1;
        for (var i=0; i<result_array.length; i++){
            if (menu_type_num != result_array[i].menu_type){
                menu_type_num = result_array[i].menu_type;
                menu_group_num = -1;
                var type_array:Array = new Array();
                _global.menu_array[menu_type_num] = type_array;
            }
            if (menu_group_num != result_array[i].menu_group){
                menu_group_num = result_array[i].menu_group;
                var group_array:Array = new Array();
                _global.menu_array[menu_type_num][menu_group_num] = group_array;
            }
            var menu_obj:Object = new Object();
            menu_id_num = menu_obj.menu_id = Number(result_array[i].menu_id);
            menu_obj.menu_text = result_array[i].menu_text;
            _global.menu_array[menu_type_num][menu_group_num][menu_id_num] = menu_obj;
        }
</code>```

I've reached to this solution in JS:

```<code>result.then(function(res)
    {
        if(!_MEV2_GLOBAL.hasOwnProperty("menu_array"))
        {
            _MEV2_GLOBAL.menu_array = {};
        }

        res.forEach(r =>
        {
            if(!_MEV2_GLOBAL.menu_array.hasOwnProperty(r.menu_type))
            {
                _MEV2_GLOBAL.menu_array[r.menu_type] = {};
            }

      if(!_MEV2_GLOBAL.menu_array[r.menu_type].hasOwnProperty(r.menu_group))
            {
                _MEV2_GLOBAL.menu_array[r.menu_type][r.menu_group] = {};
            }

            if(!_MEV2_GLOBAL.menu_array[r.menu_type][r.menu_group].hasOwnProperty(r.menu_id))
            {
                _MEV2_GLOBAL.menu_array[r.menu_type][r.menu_group][r.menu_id] = {
                    menu_id:   r.menu_id,
                    menu_text: r.menu_text
                };
            }
        }
    }
</code>```

This works but doing an if for every sublevel... Do I have another way, something with reduce or whatever, more effective and concise?

I know a little about JS but I'm afraid my solution isn't the best aproach. Or am I falling to the "root of all evil" :P

EDIT:
The input comes from an IndexedDB "table", so the result is made of objects ("lines") similar to the one on the picture:
for example, "t_menus_gre" select is the input

This resultSet must be inserted on a GlobalVar, that should follow this structure:
this object is my GlobalVar and should include a subObject['menu_array'] with menus configs by type/group/id

答:
Okay... I honestly don't think I understood the logic behind that menu configuration, but based solely on your code I could make the following improvements:

```<code>result.then(res => {

    _MEV2_GLOBAL.menu_array = _MEV2_GLOBAL.menu_array || {};
    const array = _MEV2_GLOBAL.menu_array;

    res.forEach(r => {
        array[r.menu_type] = array[r.menu_type] || {};
        array[r.menu_type][r.menu_group] = array[r.menu_type][r.menu_group] || {};
        array[r.menu_type][r.menu_group][r.menu_id] = array[r.menu_type][r.menu_group][r.menu_id] || { menu_id: r.menu_id, menu_text: r.menu_text };
    });

});
</code>```

If you just want to verify if a value is defined, javascript always evaluates null, undefined, false, "" and 0 as false.

That way, when you execute array[r.menu_type] = array[r.menu_type] || {};, if array[r.menu_type] is undefined, it receives {}.

Hope  that helps you in some way.

Body:
The problem: I've a JS global var that I've to check if it as an object with "menus configurations" and populate with the missing configurations.

So this work is based on this AS2:

        var result_array = re.result.items;

        _global.menu_array = new Array();
        var menu_type_num:Number = -1;
        var menu_group_num:Number = -1;
        var menu_id_num:Number = -1;
        for (var i=0; i<result_array.length; i++){
            if (menu_type_num != result_array[i].menu_type){
                menu_type_num = result_array[i].menu_type;
                menu_group_num = -1;
                var type_array:Array = new Array();
                _global.menu_array[menu_type_num] = type_array;
            }
            if (menu_group_num != result_array[i].menu_group){
                menu_group_num = result_array[i].menu_group;
                var group_array:Array = new Array();
                _global.menu_array[menu_type_num][menu_group_num] = group_array;
            }
            var menu_obj:Object = new Object();
            menu_id_num = menu_obj.menu_id = Number(result_array[i].menu_id);
            menu_obj.menu_text = result_array[i].menu_text;
            _global.menu_array[menu_type_num][menu_group_num][menu_id_num] = menu_obj;
        }

I've reached to this solution in JS:

result.then(function(res)
    {
        if(!_MEV2_GLOBAL.hasOwnProperty("menu_array"))
        {
            _MEV2_GLOBAL.menu_array = {};
        }

        res.forEach(r =>
        {
            if(!_MEV2_GLOBAL.menu_array.hasOwnProperty(r.menu_type))
            {
                _MEV2_GLOBAL.menu_array[r.menu_type] = {};
            }

      if(!_MEV2_GLOBAL.menu_array[r.menu_type].hasOwnProperty(r.menu_group))
            {
                _MEV2_GLOBAL.menu_array[r.menu_type][r.menu_group] = {};
            }

            if(!_MEV2_GLOBAL.menu_array[r.menu_type][r.menu_group].hasOwnProperty(r.menu_id))
            {
                _MEV2_GLOBAL.menu_array[r.menu_type][r.menu_group][r.menu_id] = {
                    menu_id:   r.menu_id,
                    menu_text: r.menu_text
                };
            }
        }
    }

This works but doing an if for every sublevel... Do I have another way, something with reduce or whatever, more effective and concise?

I know a little about JS but I'm afraid my solution isn't the best aproach. Or am I falling to the "root of all evil" :P

EDIT:
The input comes from an IndexedDB "table", so the result is made of objects ("lines") similar to the one on the picture:
for example, "t_menus_gre" select is the input

This resultSet must be inserted on a GlobalVar, that should follow this structure:
this object is my GlobalVar and should include a subObject['menu_array'] with menus configs by type/group/id

Body:
Okay... I honestly don't think I understood the logic behind that menu configuration, but based solely on your code I could make the following improvements:

result.then(res => {

    _MEV2_GLOBAL.menu_array = _MEV2_GLOBAL.menu_array || {};
    const array = _MEV2_GLOBAL.menu_array;

    res.forEach(r => {
        array[r.menu_type] = array[r.menu_type] || {};
        array[r.menu_type][r.menu_group] = array[r.menu_type][r.menu_group] || {};
        array[r.menu_type][r.menu_group][r.menu_id] = array[r.menu_type][r.menu_group][r.menu_id] || { menu_id: r.menu_id, menu_text: r.menu_text };
    });

});

If you just want to verify if a value is defined, javascript always evaluates null, undefined, false, "" and 0 as false.

That way, when you execute array[r.menu_type] = array[r.menu_type] || {};, if array[r.menu_type] is undefined, it receives {}.

Hope  that helps you in some way.


问:
Laravel 5.5 request()->all() doesn't get all the inputs
I am using Laravel 5.5. I am trying to create a post, but when I request for all() data to die dump from request instance I don't get all the fields printed out.

Here is my code to create the post:

```<code>   /**

    * Persist new post.

    */
public function store()
{
    $this->validate(request(),[

        'title'=>'required'
    ]);

        dd(request()->all());

        $path = CreatePhotoThumbnail(request()->file('photo'));

        auth()->user()->addPost(new Posts( [
        'title'=>request('title'),
        'body'=>request('body'),
        'photo'=> $path

    ]));
}
</code>```

All i get in print_R is the title only:

```<code>Array ( [_token] => MhOTEGkR1oDMc50q0FiJmI8JCAeuCRrFCfRHcKkq  [title] => test )
</code>```

Edited:

The form:

```<code>  <!-- Main (left side) -->

  <section style="margin-top:20px;">

    <div class="row">
        <div class="col-sm-12">

          <!-- post -->
          <article class="blog-post">

          <div class="post-entry">

          <h2>Create a Blog Post</h2>

          <p>Be as specific as u can:</p>

          <form name="" action="/posts/create" method="post" class="comment-form" enctype="multipart/form-data">
          {{csrf_field()}}
          <div style="display: none;">
          <input type="hidden" name="_wpcf7" value="79" />
          <input type="hidden" name="_wpcf7_version" value="4.1" />
          <input type="hidden" name="_wpcf7_locale" value="en_US" />
          <input type="hidden" name="_wpcf7_unit_tag" value="wpcf7-f79-p64-o1" />
          <input type="hidden" name="_wpnonce" value="ebcdc94d2e" />
          </div>
          <div class="row">

          <div class="col-md-12">
            <label for="title">Post Title</label>
            <input id="title" type="text" placeholder="Post Title" name="title">
          </div>

          <div class="col-md-12">
            <label for="body">Body:</label>
            <textarea name="body" id="body" placeholder="Post body" rows="10"></textarea>
          </div>

          <div class="col-md-12" id="drop">
              <label for="photo">Upload a post picture</label>
              <input type="file" id="photo"  name="photo" >
          </div>

          <div class="col-md-12"><input type="submit" value="Create Post" class="submit-button" /></div>
          </div>
          </form>

          </div>
          <div class="col-md-12" style="padding: 0px; margin:0px;">
              @include('layouts.errors')
          </div>
          </article>
          <!-- contact end -->

        </div><!-- end col-md-12 -->
    </div><!-- end row -->

   </section>
   <!-- END Main (left side) -->
</code>```

答:
Laravel 5.5 changed the validate() method to return validated fields so that you could easily pass valid data to model creation without using request->only() for example.

It is possible that it is unintentionally modifying $request->all() and as such you're not getting the results you intended.

If you want to get everything, try adding your fields to your validator, even if you don't want to validate them, i.e. without actual rules.

For example

```<code>$validData = $this->validate(request(),[
    'title'=>'required',
    'body' => ''
]);
</code>```

$validData should contain your fields.

You might also try

```<code>$this->validate(request()->all() ...
</code>```

Which might then not modify the request object meaning $request->all() might work as expected

Body:
I am using Laravel 5.5. I am trying to create a post, but when I request for all() data to die dump from request instance I don't get all the fields printed out.

Here is my code to create the post:

   /**

    * Persist new post.

    */
public function store()
{
    $this->validate(request(),[

        'title'=>'required'
    ]);

        dd(request()->all());

        $path = CreatePhotoThumbnail(request()->file('photo'));

        auth()->user()->addPost(new Posts( [
        'title'=>request('title'),
        'body'=>request('body'),
        'photo'=> $path

    ]));
}

All i get in print_R is the title only:

Array ( [_token] => MhOTEGkR1oDMc50q0FiJmI8JCAeuCRrFCfRHcKkq  [title] => test )

Edited:

The form:

Create a Blog Post

Be as specific as u can:

          <form name="" action="/posts/create" method="post" class="comment-form" enctype="multipart/form-data">
          {{csrf_field()}}

          <input type="hidden" name="_wpcf7" value="79" />
          <input type="hidden" name="_wpcf7_version" value="4.1" />
          <input type="hidden" name="_wpcf7_locale" value="en_US" />
          <input type="hidden" name="_wpcf7_unit_tag" value="wpcf7-f79-p64-o1" />
          <input type="hidden" name="_wpnonce" value="ebcdc94d2e" />

            Post Title
            <input id="title" type="text" placeholder="Post Title" name="title">

            Body:
            <textarea name="body" id="body" placeholder="Post body" rows="10"></textarea>

              Upload a post picture
              <input type="file" id="photo"  name="photo" >

<input type="submit" value="Create Post" class="submit-button" />

          </form>

              @include('layouts.errors')

Body:
Laravel 5.5 changed the validate() method to return validated fields so that you could easily pass valid data to model creation without using request->only() for example.

It is possible that it is unintentionally modifying $request->all() and as such you're not getting the results you intended.

If you want to get everything, try adding your fields to your validator, even if you don't want to validate them, i.e. without actual rules.

For example

$validData = $this->validate(request(),[
    'title'=>'required',
    'body' => ''
]);

$validData should contain your fields.

You might also try

$this->validate(request()->all() ...

Which might then not modify the request object meaning $request->all() might work as expected


问:
Python 2.7: Generate JSON file with multiple query results in nested dict
What started as my personal initiative, ended up being a quiet interesting ( may I say, challenging to some degree) project. My company decided to phase out one product and replace it with new one, which instead of storing data in mdb files, uses JSON files. So I took the initiative to create a converter that will read already created mdb files and convert them into the new format JSON.
However, now  I'm at wits-ends with this one:

I can read mdb files, run query to extract specific data.
By placing the targetobj  inside the FOR LOOP, I managed to extract data for each row and fed into a dict(targetobj)

```<code>for val in rows:
   targetobj={"connection_props": {"port": 7800, "service": "", "host": val.Hostname, "pwd": "", "username": ""},
                        "group_list": val.Groups, "cpu_core_cnt": 2, "target_name": "somename", "target_type": "somethingsamething",
                        "os": val.OS, "rule_list": [], "user_list": val.Users}
</code>```

if I print targetobj to console, I can clearly get all extracted values for each row.

Now, my quest is to have the obtained results ( for each row), inserted into the main_dict under the key targets:[]. ( Please see sample of JSON file for illustration)

main_dict = {"changed_time": 0, "year": 0, "description": 'blahblahblah', 'targets':[RESULTS FROM TARGETOBJ SHOULD BE ADDED HERE],"enabled": False}

so for example my Json file should have structure such as:

```<code>    {"changed_time":1234556,
"year":0,
"description":"blahblahblah",
    "targets":[
                {"group_list":["QA"],
                "cpu_core_cnt":1,
                "target_name":"NewTarget",
                "os":"unix",
                "target_type":"",
                "rule_list":[],
                "user_list":[""],"connection_props":"port":someport,"service":"","host":"host1","pwd":"","username":""}
                },
                {"group_list":[],
                "cpu_core_cnt":2,
                "target_name":"",
                "os":"unix",
                "target_type":"",
                "rule_list":[],
                "user_list":["Web2user"],
                "connection_props":{"port":anotherport,"service":"","host":"host2","pwd":"","username":""}}
                ],
"enabled":false}
</code>```

So far I've been tweaking here and there, to have the results written as intended, however each time,I'm getting only the last row values written.
ie.: putting the targetobj as a variable inside the targets:[]

```<code>{"changed_time": 0, "year": 0, "description": 'ConvertedConfigFile', 'targets':[targetobj],
</code>```

I know I'm missing something, I just need to find what and where.
Any help would be highly appreciated.
thank you

答:
Just create your main_dict first and append to it in your loop, i.e.:

```<code>main_dict = {"changed_time": 0,
             "year": 0,
             "description": "blahblahblah",
             "targets": [],  # a new list for the target objects
             "enabled": False}

for val in rows:
    main_dict["targets"].append({  # append this dict to the targets list of main_dict
        "connection_props": {
            "port": 7800,
            "service": "",
            "host": val.Hostname,
            "pwd": "",
            "username": ""},
        "group_list": val.Groups,
        "cpu_core_cnt": 2,
        "target_name": "somename",
        "target_type": "somethingsamething",
        "os": val.OS,
        "rule_list": [],
        "user_list": val.Users
    })
</code>```

Body:
What started as my personal initiative, ended up being a quiet interesting ( may I say, challenging to some degree) project. My company decided to phase out one product and replace it with new one, which instead of storing data in mdb files, uses JSON files. So I took the initiative to create a converter that will read already created mdb files and convert them into the new format JSON.
However, now  I'm at wits-ends with this one:

I can read mdb files, run query to extract specific data.
By placing the targetobj  inside the FOR LOOP, I managed to extract data for each row and fed into a dict(targetobj)

for val in rows:
   targetobj={"connection_props": {"port": 7800, "service": "", "host": val.Hostname, "pwd": "", "username": ""},
                        "group_list": val.Groups, "cpu_core_cnt": 2, "target_name": "somename", "target_type": "somethingsamething",
                        "os": val.OS, "rule_list": [], "user_list": val.Users}

if I print targetobj to console, I can clearly get all extracted values for each row.

Now, my quest is to have the obtained results ( for each row), inserted into the main_dict under the key targets:[]. ( Please see sample of JSON file for illustration)

main_dict = {"changed_time": 0, "year": 0, "description": 'blahblahblah', 'targets':[RESULTS FROM TARGETOBJ SHOULD BE ADDED HERE],"enabled": False}

so for example my Json file should have structure such as:

    {"changed_time":1234556,
"year":0,
"description":"blahblahblah",
    "targets":[
                {"group_list":["QA"],
                "cpu_core_cnt":1,
                "target_name":"NewTarget",
                "os":"unix",
                "target_type":"",
                "rule_list":[],
                "user_list":[""],"connection_props":"port":someport,"service":"","host":"host1","pwd":"","username":""}
                },
                {"group_list":[],
                "cpu_core_cnt":2,
                "target_name":"",
                "os":"unix",
                "target_type":"",
                "rule_list":[],
                "user_list":["Web2user"],
                "connection_props":{"port":anotherport,"service":"","host":"host2","pwd":"","username":""}}
                ],
"enabled":false}

So far I've been tweaking here and there, to have the results written as intended, however each time,I'm getting only the last row values written.
ie.: putting the targetobj as a variable inside the targets:[]

{"changed_time": 0, "year": 0, "description": 'ConvertedConfigFile', 'targets':[targetobj],

I know I'm missing something, I just need to find what and where.
Any help would be highly appreciated.
thank you

Body:
Just create your main_dict first and append to it in your loop, i.e.:

main_dict = {"changed_time": 0,
             "year": 0,
             "description": "blahblahblah",
             "targets": [],  # a new list for the target objects
             "enabled": False}

for val in rows:
    main_dict["targets"].append({  # append this dict to the targets list of main_dict
        "connection_props": {
            "port": 7800,
            "service": "",
            "host": val.Hostname,
            "pwd": "",
            "username": ""},
        "group_list": val.Groups,
        "cpu_core_cnt": 2,
        "target_name": "somename",
        "target_type": "somethingsamething",
        "os": val.OS,
        "rule_list": [],
        "user_list": val.Users
    })


问:
Swift 3, Multipeer, send struct as Data
I am struggling with a problem. I want to send a struct to connected devices.

Here is the code I use copied into Playground

In the code I added some extension to the Data class for coding/decoding. I create a Dictionary of [String:Player] and use NSKeyedArchiver to create a Data record to send.

I don't do the send here but in my program I do. Here in the playground the code/decode work fine. When I do it in my program the decoding fails when extracting the Player from Data. It fails with: EXC_BAD_ACCESS

If I use a String instead of the Player structure it decodes fine in the didReceive data function. Fails only when using a Struct.

Anyone with some suggestions?

```<code>//: Playground - noun: a place where people can play
import UIKit

// Player structure
struct Player {
    var initials : String
    var name : String
}

//
// Data extension
//
extension Data {

    // struct
    init<T>(from value: T) {
        var value = value
        self.init(bytes: &value, count: MemoryLayout<T>.size)
    }

    // extract Struct
    func extract<T>(from: T.Type) -> T {
        return self.withUnsafeBytes { $0.pointee }   // FAILS HERE: EXC_BAD_ACCESS
    }
}

// Make a data record for sending
let sply = Player(initials: "PN", name: "Player Name")
let spda = Data(from: sply)
let sdic : [String:Data] = ["Player" : spda]
let sdta : Data = NSKeyedArchiver.archivedData(withRootObject: sdic)

// Do the sending
// ... send...

//Decode
// The following code that is used on the receiving device in
// the "didReceive data" function.
let rdic = NSKeyedUnarchiver.unarchiveObject(with: sdta) as! [String : Data]
let rdta = rdic["Player"]!
let rply = rdta.extract(from: Player.self)
print(rply.name)        // Prints: "Player Name"
</code>```

答:
What worked for me was a custom class that inherits from NSObject and conforms to NSCoding.

```<code>class Player: NSObject, NSCoding {
    var initials: String!
    var name: String!

    required convenience init(coder decoder: NSCoder) {
        self.init()
        self.initials = decoder.decodeObject(forKey: "initials") as! String
        self.name = decoder.decodeObject(forKey: "name") as! String
    }

    convenience init(initials: String, name: String) {
        self.init()
        self.initials = initials
        self.name = name
    }

    func encode(with aCoder: NSCoder) {
        if let initials = initials { aCoder.encode(initials, forKey: "initials") }
        if let name = name { aCoder.encode(name, forKey: "name") }
    }
}
</code>```

Make data to send:

```<code>let data = NSKeyedArchiver.archivedData(withRootObject: Player(initials: "PN", name: "Player Name"))
</code>```

Get data back to Player:

```<code>guard let player: Player = NSKeyedUnarchiver.unarchiveObject(with: data) as! Player? else { return }
</code>```

Title: Swift 3, Multipeer, send struct as Data

Body:
I am struggling with a problem. I want to send a struct to connected devices.

Here is the code I use copied into Playground

In the code I added some extension to the Data class for coding/decoding. I create a Dictionary of [String:Player] and use NSKeyedArchiver to create a Data record to send.

I don't do the send here but in my program I do. Here in the playground the code/decode work fine. When I do it in my program the decoding fails when extracting the Player from Data. It fails with: EXC_BAD_ACCESS

If I use a String instead of the Player structure it decodes fine in the didReceive data function. Fails only when using a Struct.

Anyone with some suggestions?

//: Playground - noun: a place where people can play
import UIKit

// Player structure
struct Player {
    var initials : String
    var name : String
}

//
// Data extension
//
extension Data {

    // struct
    init<T>(from value: T) {
        var value = value
        self.init(bytes: &value, count: MemoryLayout<T>.size)
    }

    // extract Struct
    func extract<T>(from: T.Type) -> T {
        return self.withUnsafeBytes { $0.pointee }   // FAILS HERE: EXC_BAD_ACCESS
    }
}

// Make a data record for sending
let sply = Player(initials: "PN", name: "Player Name")
let spda = Data(from: sply)
let sdic : [String:Data] = ["Player" : spda]
let sdta : Data = NSKeyedArchiver.archivedData(withRootObject: sdic)

// Do the sending
// ... send...

//Decode
// The following code that is used on the receiving device in
// the "didReceive data" function.
let rdic = NSKeyedUnarchiver.unarchiveObject(with: sdta) as! [String : Data]
let rdta = rdic["Player"]!
let rply = rdta.extract(from: Player.self)
print(rply.name)        // Prints: "Player Name"

Body:
What worked for me was a custom class that inherits from NSObject and conforms to NSCoding.

class Player: NSObject, NSCoding {
    var initials: String!
    var name: String!

    required convenience init(coder decoder: NSCoder) {
        self.init()
        self.initials = decoder.decodeObject(forKey: "initials") as! String
        self.name = decoder.decodeObject(forKey: "name") as! String
    }

    convenience init(initials: String, name: String) {
        self.init()
        self.initials = initials
        self.name = name
    }

    func encode(with aCoder: NSCoder) {
        if let initials = initials { aCoder.encode(initials, forKey: "initials") }
        if let name = name { aCoder.encode(name, forKey: "name") }
    }
}

Make data to send:

let data = NSKeyedArchiver.archivedData(withRootObject: Player(initials: "PN", name: "Player Name"))

Get data back to Player:

guard let player: Player = NSKeyedUnarchiver.unarchiveObject(with: data) as! Player? else { return }


问:
Changing time zone in xts taking care of dst (daylight saving time)
Suppose we have these three dates:

```<code>original_dates<-  c("2015-12-31T07:00:00", "2015-12-31T08:00:00", "2015-12-31T09:00:00")
</code>```

and this vector:

```<code>vector<- c("a", "b", "c")
</code>```

We transform the dates to POSIXct format:

```<code>original_dates2<- as.POSIXct(original_dates, format="%Y-%m-%dT%H", tz = "GMT")
</code>```

and build a xts:

```<code>my_xts<- xts(vector, order.by = original_dates2, frequency = "hourly")
</code>```

so we have the following xts object:

```<code>> my_xts
                    [,1]
2015-12-31 07:00:00 "a"
2015-12-31 08:00:00 "b"
2015-12-31 09:00:00 "c"
Warning message:
timezone of object (GMT) is different than current timezone ().
</code>```

If I want to change to local time I would change the time zone:

```<code>indexTZ(my_xts)<- "America/Los_Angeles"
</code>```

but this yields a wrong result because I know that 2015-12-31 07:00:00 GMT should be equal to 2015-12-31 00:00:00 LA time (i.e. 7 h. before), not 2015-12-30 23:00:00 (i.e. 8 h. before)

```<code>> my_xts
                    [,1]
2015-12-30 23:00:00 "a"
2015-12-31 00:00:00 "b"
2015-12-31 01:00:00 "c"
Warning message:
timezone of object (America/Los_Angeles) is different than current timezone ().
</code>```

I guess this happens because the timezone conversion indexTZ(my_xts)<- "America/Los_Angeles" does not consider the daylight savings time (dst), as shown by the dst function:

```<code>> dst(my_xts)
[1] FALSE FALSE FALSE
</code>```

The question is, how can I change the timezone such that the dst is taken care of?

More details:

```<code>> Sys.timezone()
[1] "Europe/Paris"
> R.version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
version.string R version 3.3.1 (2016-06-21)
</code>```

答:
You said:

but this yields a wrong result because I know that 2015-12-31 07:00:00 GMT should be equal to 2015-12-31 00:00:00 LA time (i.e. 7 h. before), not 2015-12-30 23:00:00 (i.e. 8 h. before)

That is incorrect.  The Pacific Time zone is UTC-8 during standard time, and UTC-7 during daylight time.  In December, standard time is in effect.  Therefore, the result you see is as expected.

Body:
Suppose we have these three dates:

original_dates<-  c("2015-12-31T07:00:00", "2015-12-31T08:00:00", "2015-12-31T09:00:00")

and this vector:

vector<- c("a", "b", "c")

We transform the dates to POSIXct format:

original_dates2<- as.POSIXct(original_dates, format="%Y-%m-%dT%H", tz = "GMT")

and build a xts:

my_xts<- xts(vector, order.by = original_dates2, frequency = "hourly")

so we have the following xts object:

> my_xts
                    [,1]
2015-12-31 07:00:00 "a"
2015-12-31 08:00:00 "b"
2015-12-31 09:00:00 "c"
Warning message:
timezone of object (GMT) is different than current timezone ().

If I want to change to local time I would change the time zone:

indexTZ(my_xts)<- "America/Los_Angeles"

but this yields a wrong result because I know that 2015-12-31 07:00:00 GMT should be equal to 2015-12-31 00:00:00 LA time (i.e. 7 h. before), not 2015-12-30 23:00:00 (i.e. 8 h. before)

> my_xts
                    [,1]
2015-12-30 23:00:00 "a"
2015-12-31 00:00:00 "b"
2015-12-31 01:00:00 "c"
Warning message:
timezone of object (America/Los_Angeles) is different than current timezone ().

I guess this happens because the timezone conversion indexTZ(my_xts)<- "America/Los_Angeles" does not consider the daylight savings time (dst), as shown by the dst function:

> dst(my_xts)
[1] FALSE FALSE FALSE

The question is, how can I change the timezone such that the dst is taken care of?

More details:

> Sys.timezone()
[1] "Europe/Paris"
> R.version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
version.string R version 3.3.1 (2016-06-21)