问:
CMake: How to copy different files to build directory according to configuration and architecture
I'm generating my vcxproj and sln files for MSVC with CMake. I want to copy some dlls in build directory as POST_BUILD event which are different according whether I'm building Debug or Release configuration and whether it is x86 or x64 architecture. I'm using add_custom_command the following way

```<code>add_custom_command(TARGET ${TARGET_NAME} POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E copy_if_different
    ${FILES_TO_COPY} ${CMAKE_CURRENT_BINARY_DIR})
</code>```

I want to set FILES_TO_COPY to different values according to architecture and configuration or to use different add_custom_command according the same conditions. But CMake MSVC is multi config generator and CMAKE_BUILD_TYPE is empty under it and I cannot simply write something like:

```<code>if (CMAKE_SIZEOF_VOID_P EQUAL 4)
  if (CMAKE_BUILD_TYPE STREQUAL "Debug")

    set (FILES_TO_COPY
      "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/Debug/i386/libdb52d.dll")

  elseif (CMAKE_BUILD_TYPE STREQUAL "Release")

    set (FILES_TO_COPY
      "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/Release/i386/libdb52.dll")

  else ()
    message (FATAL_ERROR "Invalid configuration name ${CMAKE_BUILD_TYPE}.")
  endif ()
elseif (CMAKE_SIZEOF_VOID_P EQUAL 8)
  if (CMAKE_BUILD_TYPE STREQUAL "Debug")

    set (FILES_TO_COPY
      "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/Debug/x64/libdb52d.dll")

  elseif (CMAKE_BUILD_TYPE STREQUAL "Release")

    set (FILES_TO_COPY
      "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/Release/x64/libdb52.dll")

  else ()
    message (FATAL_ERROR "Invalid configuration name ${CMAKE_BUILD_TYPE}.")
  endif ()
else ()
  message (FATAL_ERROR "Unsupported architecture with ${CMAKE_SIZEOF_VOID_P}
    bytes pointer size.")
endif ()
</code>```

How to do this properly?

答:
try this:</p>

```<code>set(arch "i386")
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
    set(arch "x64")
endif()

set(FILES_TO_COPY "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/$<CONFIG>/${arch}/libdb52$<$<CONFIG:Debug>:d>.dll")
</code>```

Body:
I'm generating my vcxproj and sln files for MSVC with CMake. I want to copy some dlls in build directory as POST_BUILD event which are different according whether I'm building Debug or Release configuration and whether it is x86 or x64 architecture. I'm using add_custom_command the following way

add_custom_command(TARGET ${TARGET_NAME} POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E copy_if_different
    ${FILES_TO_COPY} ${CMAKE_CURRENT_BINARY_DIR})

I want to set FILES_TO_COPY to different values according to architecture and configuration or to use different add_custom_command according the same conditions. But CMake MSVC is multi config generator and CMAKE_BUILD_TYPE is empty under it and I cannot simply write something like:

if (CMAKE_SIZEOF_VOID_P EQUAL 4)
  if (CMAKE_BUILD_TYPE STREQUAL "Debug")

    set (FILES_TO_COPY
      "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/Debug/i386/libdb52d.dll")

  elseif (CMAKE_BUILD_TYPE STREQUAL "Release")

    set (FILES_TO_COPY
      "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/Release/i386/libdb52.dll")

  else ()
    message (FATAL_ERROR "Invalid configuration name ${CMAKE_BUILD_TYPE}.")
  endif ()
elseif (CMAKE_SIZEOF_VOID_P EQUAL 8)
  if (CMAKE_BUILD_TYPE STREQUAL "Debug")

    set (FILES_TO_COPY
      "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/Debug/x64/libdb52d.dll")

  elseif (CMAKE_BUILD_TYPE STREQUAL "Release")

    set (FILES_TO_COPY
      "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/Release/x64/libdb52.dll")

  else ()
    message (FATAL_ERROR "Invalid configuration name ${CMAKE_BUILD_TYPE}.")
  endif ()
else ()
  message (FATAL_ERROR "Unsupported architecture with ${CMAKE_SIZEOF_VOID_P}
    bytes pointer size.")
endif ()

How to do this properly?

Body:
try this:

set(arch "i386")
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
    set(arch "x64")
endif()

set(FILES_TO_COPY "${CMAKE_SOURCE_DIR}/Externals/DLLs/bdb/$<CONFIG>/${arch}/libdb52$<$<CONFIG:Debug>:d>.dll")


来源: stackexchange

问:
Intent object showing error Android
I am working with android activities , and trying to launch an activity when a button is clicked on the previous activity, the problem start in intent object, because the first parameter i.e; context parameter of intent constructor doesn't work with "this, MainActivity.this, getApplicationContext(),getBaseContext" i tried all of the parameters in the first parameter of the intent constructor object. Below is my code.

```<code>package com.example.nadeemahmad.guitest;

import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    Button ma_sub_btn,prof_sub_btn;
    RelativeLayout ma_rel_lay2,ma_rel_lay3,ma_dots_ly;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ma_sub_btn = (Button)findViewById(R.id.ma_sub_btn);
        ma_rel_lay2 = (RelativeLayout)findViewById(R.id.ma_rel_lay2);
        ma_rel_lay3 = (RelativeLayout)findViewById(R.id.ma_rel_lay3);
        ma_dots_ly = (RelativeLayout)findViewById(R.id.ma_dots_ly);

        ma_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ma_rel_lay2.setVisibility(View.GONE);
                ma_rel_lay3.setVisibility(View.VISIBLE);
                ma_dots_ly.setVisibility(View.GONE);
            }
        });

        prof_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(this, profile.class);
                startActivity(i);
            }
        });

    }

}
</code>```

Image

答:
You are getting NullPointerException for Button prof_sub_btn. The problem is you have not initialized Button prof_sub_btn before setting OnClickListener to it..

Try this:

```<code>prof_sub_btn = (Button) findViewById(R.id.prof_sub_btn);
prof_sub_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(MainActivity.this, profile.class);
            startActivity(i);
        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Intent object showing error Android

Body:
I am working with android activities , and trying to launch an activity when a button is clicked on the previous activity, the problem start in intent object, because the first parameter i.e; context parameter of intent constructor doesn't work with "this, MainActivity.this, getApplicationContext(),getBaseContext" i tried all of the parameters in the first parameter of the intent constructor object. Below is my code.

package com.example.nadeemahmad.guitest;

import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    Button ma_sub_btn,prof_sub_btn;
    RelativeLayout ma_rel_lay2,ma_rel_lay3,ma_dots_ly;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ma_sub_btn = (Button)findViewById(R.id.ma_sub_btn);
        ma_rel_lay2 = (RelativeLayout)findViewById(R.id.ma_rel_lay2);
        ma_rel_lay3 = (RelativeLayout)findViewById(R.id.ma_rel_lay3);
        ma_dots_ly = (RelativeLayout)findViewById(R.id.ma_dots_ly);

        ma_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ma_rel_lay2.setVisibility(View.GONE);
                ma_rel_lay3.setVisibility(View.VISIBLE);
                ma_dots_ly.setVisibility(View.GONE);
            }
        });

        prof_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(this, profile.class);
                startActivity(i);
            }
        });

    }

}

Image

Body:
You are getting NullPointerException for Button prof_sub_btn. The problem is you have not initialized Button prof_sub_btn before setting OnClickListener to it..

Try this:

prof_sub_btn = (Button) findViewById(R.id.prof_sub_btn);
prof_sub_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(MainActivity.this, profile.class);
            startActivity(i);
        }
    });


问:
prepare to focus first active element in a container
I have a container on a page that should be prepared for focusing, i.e. when user pressed TAB button, the first active element in the container must be focused.

The simplest way I have thought so far is to find the last active element before the container, focus it and then blur it. Will it work? Is there a simpler way? How to find the last active element before the container (cross-browser)?

I do not want to change tabbed elements order, I just want to define the next element that will be selected.

Please use raw javascript, not frameworks.

答:
Add a listener to the document and change focus onKeyUp.  Remove the listener once tab has been pressed:</p>

```<code>document.onkeyup = onKeyEvent;

function onKeyEvent (e) {
    if (e.keyCode == 9) {
       document.onkeyup = null;
       document.getElementById ('whatever').focus();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Add a listener to the document and change focus onKeyUp.  Remove the listener once tab has been pressed:

document.onkeyup = onKeyEvent;

function onKeyEvent (e) {
    if (e.keyCode == 9) {
       document.onkeyup = null;
       document.getElementById ('whatever').focus();
    }
}


问:
What is the opposite of evt.preventDefault();
Once I've fired an evt.preventDefault(), how can I resume default actions again?

答:
jquery on() could be another solution to this. escpacially when it comes to the use of namespaces.

jquery on() is just the current way of binding events ( instead of bind() ). off() is to unbind these. and when you use a namespace, you can add and remove multiple different events.

```<code>$( selector ).on("submit.my-namespace", function( event ) {
    //prevent the event
    event.preventDefault();

    //cache the selector
    var $this = $(this);

    if ( my_condition_is_true ) {
        //when 'my_condition_is_true' is met, the binding is removed and the event is triggered again.
        $this.off("submit.my-namespace").trigger("submit");
    }
});
</code>```

now with the use of namespace, you could add multiple of these events and are able to remove those, depending on your needs.. while submit might not be the best example, this might come in handy on a click or keypress or whatever..

Body:
jquery on() could be another solution to this. escpacially when it comes to the use of namespaces.

jquery on() is just the current way of binding events ( instead of bind() ). off() is to unbind these. and when you use a namespace, you can add and remove multiple different events.

$( selector ).on("submit.my-namespace", function( event ) {
    //prevent the event
    event.preventDefault();

    //cache the selector
    var $this = $(this);

    if ( my_condition_is_true ) {
        //when 'my_condition_is_true' is met, the binding is removed and the event is triggered again.
        $this.off("submit.my-namespace").trigger("submit");
    }
});

now with the use of namespace, you could add multiple of these events and are able to remove those, depending on your needs.. while submit might not be the best example, this might come in handy on a click or keypress or whatever..


问:
what is the difference between No Upfront Reserved Instances and on demand instances aws?
When trying to purchase a AWS reserved instance, I have found for no upfront,  What is the difference between it and on demand instances ?  </p>

答:
To add to Fredric's answer, Reserved Instance(RI) is a commitment from AWS to reserve capacity in exchange of customer's billing commitment.

Billing can be commited as no-upfront, partial upfront or all upfront. For committing to RIs, customers get pricing discount depending upon type of RIs and tenure. Once RIs are purchased, you would be billed for those RIs irrespective of your actually utilization of RIs.  Customer cannot cancel RIs once they are purchased post 15 days of purchase. Customer can switch between instance types if RIs are convertible or sell of their RIs in marketplace in case they are planning to not use them.


问:
angular2 let-entity directive
I've create a component which takes in a template:

```<code>export class TemplateParamComponent implements OnInit {
    @Input() items: Array<any>;
    @Input() template: TemplateRef<any>;
 }
</code>```

With html:

```<code><template #defaultTemplate let-item="item">
    <strong>{{item.name}}</strong>
</template>
<ul>
    <li *ngFor="let item of items">
        <template [ngTemplateOutlet]="template || defaultTemplate" [ngOutletContext]="{item: item}"></template>
    </li>
</ul>
</code>```

I'm confused on what the directive let-item does,  does that create a variable called item?  is let a special directive that lets you declare variable to use in scope for html?

答:
Best suggestion for you to understand how angular handle <template> element is reading documentation: https://angular.io/guide/structural-directives

Long story short: consider <template> as function (method) and let-something as input variable. So

```<code><template #defaultTemplate let-item="item">
     <strong>{{item.name}}</strong>
</template>
</code>```

Can be read as

```<code>function defaultTemplate(item: any){
    return "<strong>" + item.name + "</strong>";
}
</code>```

Title: angular2 let-entity directive

Body:
I've create a component which takes in a template:

export class TemplateParamComponent implements OnInit {
    @Input() items: Array<any>;
    @Input() template: TemplateRef<any>;
 }

With html:

<template #defaultTemplate let-item="item">
    {{item.name}}
</template>

        <template [ngTemplateOutlet]="template || defaultTemplate" [ngOutletContext]="{item: item}"></template>

I'm confused on what the directive let-item does,  does that create a variable called item?  is let a special directive that lets you declare variable to use in scope for html?

Body:
Best suggestion for you to understand how angular handle <template> element is reading documentation: https://angular.io/guide/structural-directives

Long story short: consider <template> as function (method) and let-something as input variable. So

<template #defaultTemplate let-item="item">
     <strong>{{item.name}}</strong>
</template>

Can be read as

function defaultTemplate(item: any){
    return "<strong>" + item.name + "</strong>";
}


问:
Groovy multiple resource closure
I'm using the resource closure feature of Groovy, and was wondering if it was possible to create one closure that manages two resources.  For example, if I have the following two separate closures, is it possible to create one closure that manages both?  Or do I really have to nest the closures?

```<code>new File(baseDir, 'haiku.txt').withWriter('utf-8') { writer ->
    writer.writeLine 'Into the ancient pond'
}
</code>```

```<code>new Scanner(System.in).with { consoleInput ->
    println consoleInput.nextLine()
}
</code>```

答:
No. The syntax method(arg) {} is an alternative syntax to method(arg, {}), thus, you can do this:

```<code>fn = { writer ->
    writer.writeLine 'Into the ancient pond'
}

new File(baseDir, 'haiku.txt').withWriter('utf-8', fn)

new Scanner(System.in).with(fn)
</code>```

Note that the closure must contain expected code for both method invocations.

Title: Groovy multiple resource closure

Body:
I'm using the resource closure feature of Groovy, and was wondering if it was possible to create one closure that manages two resources.  For example, if I have the following two separate closures, is it possible to create one closure that manages both?  Or do I really have to nest the closures?

new File(baseDir, 'haiku.txt').withWriter('utf-8') { writer ->
    writer.writeLine 'Into the ancient pond'
}

new Scanner(System.in).with { consoleInput ->
    println consoleInput.nextLine()
}

Body:
No. The syntax method(arg) {} is an alternative syntax to method(arg, {}), thus, you can do this:

fn = { writer ->
    writer.writeLine 'Into the ancient pond'
}

new File(baseDir, 'haiku.txt').withWriter('utf-8', fn)

new Scanner(System.in).with(fn)

Note that the closure must contain expected code for both method invocations.


问:
Extract Insert statements from Oracle DB through Shell script
I want to extract the insert statements for the data in a table in Oracle DB through the shell script. It would be similar to DB backup but I need insert statements for data in all tables in DB.</p>

答:
If your aim is :
Extract all insert statement for all tables in database, than run those insert in different database ? Or wish to save these insert statement for future use ?

If above requirement is true, their are better way to achieve this. Insert statement with "data" shown expose data to anyone who can read these extract & a serious security threat. You should look for using datapump for this requirement.

Abhi


问:
C - Function which takes 2 floats and returns their difference after the block using pointers
I'm trying to write a function which takes two generic floats (make it 'a' and 'b') and returns their difference assigned to the variables, so a=a-b and b=b-a.
It should print the values with 2 decimal places and it must work after I exit the block... What is wrong with my code?

```<code>#include <stdio.h>
float diff_abs (float *a, float *b) {
*a= *a-*b;
*b= *b-*a;
}

int main(void) {
    float c, d;
    scanf("%f", &c);
    scanf("%f", &d);
printf("%.2f\n%.2f", diff_abs(&c, &d));
return 0;
}
</code>```

I would appreciate your suggestions, thank you.

答:
First, you are changing a value then using it to the next calculation so simplify change your function to:

```<code>void diff_abs (float *a, float *b) {
    *a= *a-*b;
    *b = -*a
}
</code>```

Second, since you can't return multiple variables in a C function, one of the solution is to use void returning function but change variables while using pointers (like you're somehow doing)

Finally, since your function returns void you can't use it as floats in the printf function so just use c and d

like this:

```<code>printf("%.2f\n%.2f",c,d);
</code>```

of course don't forget to call:

```<code>diff_abs(&c, &d)
</code>```

before trying to print

you can refer to this topic for returning multiple variables in C

Body:
I'm trying to write a function which takes two generic floats (make it 'a' and 'b') and returns their difference assigned to the variables, so a=a-b and b=b-a.
It should print the values with 2 decimal places and it must work after I exit the block... What is wrong with my code?

#include <stdio.h>
float diff_abs (float *a, float *b) {
*a= *a-*b;
*b= *b-*a;
}

int main(void) {
    float c, d;
    scanf("%f", &c);
    scanf("%f", &d);
printf("%.2f\n%.2f", diff_abs(&c, &d));
return 0;
}

I would appreciate your suggestions, thank you.

Body:
First, you are changing a value then using it to the next calculation so simplify change your function to:

void diff_abs (float *a, float *b) {
    *a= *a-*b;
    *b = -*a
}

Second, since you can't return multiple variables in a C function, one of the solution is to use void returning function but change variables while using pointers (like you're somehow doing)

Finally, since your function returns void you can't use it as floats in the printf function so just use c and d

like this:

printf("%.2f\n%.2f",c,d);

of course don't forget to call:

diff_abs(&c, &d)

before trying to print

you can refer to this topic for returning multiple variables in C


问:
Getting error bundle.js:39454 Uncaught TypeError: Cannot read property 'email' of undefined using MERN stack
I am using the MERN stack and can't seem to figure out why this is happening. I have a list of post that show up just fine. When I click a post I get Cannot read property 'email' undefined inside the console. But if I hit refresh everything works just fine and that post shows up with all the working issues.

I was able to pinpoint the error to my renderComments() function. That is where everything is showing up undefined at.

EDIT : I think I found out what is happening, but I am not sure why it is happening. Before the rendering happens the comment that is created in the array.map function is only the comment ID. Only when the component renders is the comment an actual full object with all its properties. I will post the back-end to show how I am getting the comments on the post to help out.

It was asked to show a console.log of post before the array.map function. As this does point out what I said in the edit I will go ahead and show below to help.

Post controller with comments:

```<code>exports.getOnePost = function(req, res, next) {
  Posts.findById(req.params.id).populate("comments").exec(function(err, foundPost) {
    if(err) {
      return next(err);
    } else {
      res.json(foundPost);
    }
  });
}
</code>```

Post and Comment models:

```<code>var mongoose = require("mongoose");
const Schema = mongoose.Schema;

var postsSchema = new Schema({
    title: String,
    createdAt: {type: Date, default: Date.now},
    content: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "user"
        },
        email: String
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "comments"
        }
    ]
});

var Posts = mongoose.model("posts", postsSchema);

module.exports = Posts;
</code>```

```<code>var mongoose = require("mongoose");
const Schema = mongoose.Schema;

var commentSchema = new Schema({
    text: String,
    createdAt: {type: Date, default: Date.now },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        email: String
    }
});

module.exports = mongoose.model("comments", commentSchema);
</code>```

Post_show page:

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import * as actions from '../../actions/posts_actions';
import * as actionsIndex from '../../actions/index';
import * as actionsComments from '../../actions/comments_actions';

class ShowPosts extends Component {
  constructor(props) {
    super(props);

    this.onDeleteClick = this.onDeleteClick.bind(this);
    this.deleteComment = this.deleteComment.bind(this);
  }

  componentDidMount() {
    const {id} = this.props.match.params;
    this.props.getOnePost(id);

    if(this.props.auth) {
      this.props.getUser();
    }
  }

  renderButtons() {
    const { post } = this.props;

    if(!this.props.user) {
      return ( <div></div> );
    }

    if(this.props.auth) {
      if(this.props.user._id === post.author.id) {
        return (
          <div>
            <button
              onClick={this.onDeleteClick}
              className="btn btn-danger"
              >
              Delete
            </button>
            <Link
              to={`/posts/${post._id}/edit`}
              className="btn btn-success"
              >
              Edit
            </Link>
          </div>
        )
      }
    } else {
      return (
        <div></div>
      )
    }
  }

  renderCommentsButtons(comment) {
    const { post, user, auth } = this.props;

    if(!user) {
      return (<div></div>);
    }

    if(auth) {
      if(user._id === comment.author.id) {
        return (
          <div>
            <button
              onClick={() => this.deleteComment(comment)}
              className="btn btn-xs btn-danger">
              Delete
            </button>
            <Link
              to={`/posts/${post._id}/comments/${comment._id}/edit`}
              className="btn btn-xs btn-warning">
              Edit
            </Link>
          </div>
        )
      }
    }
  }

  renderComments() {
    const { post } = this.props;

    return post.comments.map((comment) => {
      return (
        <li className="list-group-item" key={comment._id}>
          <div>
            {comment.text} : {comment.author.email}
          </div>
          {this.renderCommentsButtons(comment)}
        </li>
      );
    });
  }

  deleteComment(comment) {
    const {id} = this.props.match.params;
    const {user, post, auth} = this.props;

    if(!user) {
      return (<div></div>);
    }

    if(auth) {
      if(user._id === comment.author.id){
        console.log(comment._id, '-', post._id);
        // this.props.deleteComments(id, comment._id, () => {
        //   this.props.history.push(`/posts/${post._id}`);
        // });
      }
    }
  }

  onDeleteClick() {
    const {id} = this.props.match.params;

    if(!this.props.user) {
      return (<div></div>);
    }

    if(this.props.auth) {
      if(this.props.user._id === this.props.post.author.id) {
        this.props.deletePost(id, () => {
          this.props.history.push("/posts");
        });
      }
    }
  }

  render() {
    const { post } = this.props;

    if (!post) {
      return <div> Loading...No Post</div>;
    }

    return (
      <div>
        <Link className="btn btn-primary" to="/posts">Back To Post</Link>
        <h3>{post.title}</h3>
        <p>{post.content}</p>
        <p>created by: {post.author.email}</p>
        <ul className="list-group">
          {this.renderComments()}
        </ul>
        {this.renderButtons()}
        <Link
          className="btn btn-warning"
          to={`/posts/${post._id}/comments/new`}>
            Comment
        </Link>
      </div>
    );
  }
}

function mapStateToProps({ posts, auth, user }, ownProps) {
  return {
    post: posts[ownProps.match.params.id],
    user: user,
    auth: auth.authenticated
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({...actions, ...actionsIndex, ...actionsComments}, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(ShowPosts);
</code>```

Post

```<code>import React , { Component } from 'react';
import * as actions from '../../actions/posts_actions';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';
import _ from 'lodash';

class Posts extends Component {
  componentDidMount() {
    this.props.getAllPosts();
  }

  renderPosts() {
    return _.map(this.props.posts, post => {
      return (
        <Link to={`/posts/${post._id}`} key={post._id}>
          <li className="list-group-item">
            {post.title}
          </li>
        </Link>
      )
    });
  }

  render() {
    return (
      <div>
        <div className="text-xs-right">
          <Link className="btn btn-primary" to="/posts/new">
            Add a Post
          </Link>
        </div>
        <h3>Posts</h3>
        <ul className="list-group">
          {this.renderPosts()}
        </ul>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    posts: state.posts
  };
}

export default connect(mapStateToProps, actions)(Posts);
</code>```

答:
This was a back-end problem. As stated in the edit the post first being rendered only had the comment ID for the comment instead of the full comment object. I believe what was happening is that the initial post was coming from posts[ownProps.match.params.id] which all that was doing was grabbing the singular post from the post on the client side.

If you look on the back-end I store the comments as objectIDs and then later on populate them when a call to getOnePost is called.

What I needed to do is populate the comments on all post before they get called that way the comments are already populated and aren't just IDs. So to fix this I did the following (I will also post all the other code needed).

export function that goes to the backend router:

Old:

```<code>exports.getAllPosts = function(req, res, next) {
  Posts.find({}, function(err, posts) {
    if(err) {
      return next(err);
    } else {
      res.json(posts);
    }
  });
}
</code>```

New:

```<code>exports.getAllPosts = function(req, res, next) {
  Posts.find({}).populate("comments").exec(function(err, posts) {
    if(err) {
      return next(err);
    } else {
      res.json(posts);
    }
  });
}
</code>```

Here is the post model:

```<code>var mongoose = require("mongoose");
const Schema = mongoose.Schema;

var postsSchema = new Schema({
    title: String,
    createdAt: {type: Date, default: Date.now},
    content: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "user"
        },
        email: String
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "comments"
        }
    ]
});

var Posts = mongoose.model("posts", postsSchema);

module.exports = Posts;
</code>```

Both models are already posted above.

Body:
I am using the MERN stack and can't seem to figure out why this is happening. I have a list of post that show up just fine. When I click a post I get Cannot read property 'email' undefined inside the console. But if I hit refresh everything works just fine and that post shows up with all the working issues.

I was able to pinpoint the error to my renderComments() function. That is where everything is showing up undefined at.

EDIT : I think I found out what is happening, but I am not sure why it is happening. Before the rendering happens the comment that is created in the array.map function is only the comment ID. Only when the component renders is the comment an actual full object with all its properties. I will post the back-end to show how I am getting the comments on the post to help out.

It was asked to show a console.log of post before the array.map function. As this does point out what I said in the edit I will go ahead and show below to help.

Post controller with comments:

exports.getOnePost = function(req, res, next) {
  Posts.findById(req.params.id).populate("comments").exec(function(err, foundPost) {
    if(err) {
      return next(err);
    } else {
      res.json(foundPost);
    }
  });
}

Post and Comment models:

var mongoose = require("mongoose");
const Schema = mongoose.Schema;

var postsSchema = new Schema({
    title: String,
    createdAt: {type: Date, default: Date.now},
    content: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "user"
        },
        email: String
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "comments"
        }
    ]
});

var Posts = mongoose.model("posts", postsSchema);

module.exports = Posts;

var mongoose = require("mongoose");
const Schema = mongoose.Schema;

var commentSchema = new Schema({
    text: String,
    createdAt: {type: Date, default: Date.now },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        email: String
    }
});

module.exports = mongoose.model("comments", commentSchema);

Post_show page:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import * as actions from '../../actions/posts_actions';
import * as actionsIndex from '../../actions/index';
import * as actionsComments from '../../actions/comments_actions';

class ShowPosts extends Component {
  constructor(props) {
    super(props);

    this.onDeleteClick = this.onDeleteClick.bind(this);
    this.deleteComment = this.deleteComment.bind(this);
  }

  componentDidMount() {
    const {id} = this.props.match.params;
    this.props.getOnePost(id);

    if(this.props.auth) {
      this.props.getUser();
    }
  }

  renderButtons() {
    const { post } = this.props;

    if(!this.props.user) {
      return (

 );
    }

    if(this.props.auth) {
      if(this.props.user._id === post.author.id) {
        return (

            <button
              onClick={this.onDeleteClick}
              className="btn btn-danger"
              >
              Delete
            </button>
            <Link
              to={`/posts/${post._id}/edit`}
              className="btn btn-success"
              >
              Edit
            </Link>

        )
      }
    } else {
      return (

      )
    }
  }

  renderCommentsButtons(comment) {
    const { post, user, auth } = this.props;

    if(!user) {
      return (

);
    }

    if(auth) {
      if(user._id === comment.author.id) {
        return (

            <button
              onClick={() => this.deleteComment(comment)}
              className="btn btn-xs btn-danger">
              Delete
            </button>
            <Link
              to={`/posts/${post._id}/comments/${comment._id}/edit`}
              className="btn btn-xs btn-warning">
              Edit
            </Link>

        )
      }
    }
  }

  renderComments() {
    const { post } = this.props;

    return post.comments.map((comment) => {
      return (

            {comment.text} : {comment.author.email}

          {this.renderCommentsButtons(comment)}

      );
    });
  }

  deleteComment(comment) {
    const {id} = this.props.match.params;
    const {user, post, auth} = this.props;

    if(!user) {
      return (

);
    }

    if(auth) {
      if(user._id === comment.author.id){
        console.log(comment._id, '-', post._id);
        // this.props.deleteComments(id, comment._id, () => {
        //   this.props.history.push(`/posts/${post._id}`);
        // });
      }
    }
  }

  onDeleteClick() {
    const {id} = this.props.match.params;

    if(!this.props.user) {
      return (

);
    }

    if(this.props.auth) {
      if(this.props.user._id === this.props.post.author.id) {
        this.props.deletePost(id, () => {
          this.props.history.push("/posts");
        });
      }
    }
  }

  render() {
    const { post } = this.props;

    if (!post) {
      return
 Loading...No Post
;
    }

    return (

        <Link className="btn btn-primary" to="/posts">Back To Post</Link>

{post.title}

{post.content}

created by: {post.author.email}

          {this.renderComments()}

        {this.renderButtons()}
        <Link
          className="btn btn-warning"
          to={`/posts/${post._id}/comments/new`}>
            Comment
        </Link>

    );
  }
}

function mapStateToProps({ posts, auth, user }, ownProps) {
  return {
    post: posts[ownProps.match.params.id],
    user: user,
    auth: auth.authenticated
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({...actions, ...actionsIndex, ...actionsComments}, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(ShowPosts);

Post

import React , { Component } from 'react';
import * as actions from '../../actions/posts_actions';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';
import _ from 'lodash';

class Posts extends Component {
  componentDidMount() {
    this.props.getAllPosts();
  }

  renderPosts() {
    return _.map(this.props.posts, post => {
      return (
        <Link to={`/posts/${post._id}`} key={post._id}>

            {post.title}

        </Link>
      )
    });
  }

  render() {
    return (

          <Link className="btn btn-primary" to="/posts/new">
            Add a Post
          </Link>

Posts

          {this.renderPosts()}

    );
  }
}

function mapStateToProps(state) {
  return {
    posts: state.posts
  };
}

export default connect(mapStateToProps, actions)(Posts);

Body:
This was a back-end problem. As stated in the edit the post first being rendered only had the comment ID for the comment instead of the full comment object. I believe what was happening is that the initial post was coming from posts[ownProps.match.params.id] which all that was doing was grabbing the singular post from the post on the client side.

If you look on the back-end I store the comments as objectIDs and then later on populate them when a call to getOnePost is called.

What I needed to do is populate the comments on all post before they get called that way the comments are already populated and aren't just IDs. So to fix this I did the following (I will also post all the other code needed).

export function that goes to the backend router:

Old:

exports.getAllPosts = function(req, res, next) {
  Posts.find({}, function(err, posts) {
    if(err) {
      return next(err);
    } else {
      res.json(posts);
    }
  });
}

New:

exports.getAllPosts = function(req, res, next) {
  Posts.find({}).populate("comments").exec(function(err, posts) {
    if(err) {
      return next(err);
    } else {
      res.json(posts);
    }
  });
}

Here is the post model:

var mongoose = require("mongoose");
const Schema = mongoose.Schema;

var postsSchema = new Schema({
    title: String,
    createdAt: {type: Date, default: Date.now},
    content: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "user"
        },
        email: String
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "comments"
        }
    ]
});

var Posts = mongoose.model("posts", postsSchema);

module.exports = Posts;

Both models are already posted above.


问:
Change the state of the condition variable for a while loop outside the while loop
I am currently trying to start and stop a while loop by a pressing a key  (start) and stopping by releasing the key.

So something like this:

```<code>from pynput import keyboard
global condition
condition = False

def on_press(key):
    global condition
    if key == keyboard.Key.cmd_r:
        print('pressed cmd_r'.format(key))
        condition = True
    else:
        print('incorrect character {0}, press cmd_r'.format(key))

def on_release(key):
    global condition
    print('{0} released'.format(key))
    if key == keyboard.Key.cmd_r:
        condition = False
        #keyboard.Listener.stop
        #return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

while condition==True:
    print "Condition true"
</code>```

I am not sure why this is not working?..
It should in my head?

答:
The issue is that when you call listener.join() your code waits at this point for the thread to complete. But it never will complete because it's always listening! Instead you want to call listener.start() so that the thread runs in the background and you are free to do what you want.

Sharing variables between threads is not generally accepted, so here I make a modified listener class that associates the variable key_pressed to itself when a key is pressed, and None when it is released. You can then do what you want with this variable by checking it at any time in a separate loop by calling listener.key_pressed

```<code>from pynput import keyboard
import time

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(self.on_press, self.on_release)
        self.key_pressed = None

    def on_press(self, key):
        self.key_pressed = key

    def on_release(self, key):
        self.key_pressed = None

listener = MyListener()
listener.start()

while True:
    time.sleep(0.1)
    print listener.key_pressed
</code>```

Note that if you don't include a delay with time.sleep as above, you will overload the buffer and lead to delays in the output. Just put a small delay if you want it fast, but not zero.

Body:
I am currently trying to start and stop a while loop by a pressing a key  (start) and stopping by releasing the key.

So something like this:

from pynput import keyboard
global condition
condition = False

def on_press(key):
    global condition
    if key == keyboard.Key.cmd_r:
        print('pressed cmd_r'.format(key))
        condition = True
    else:
        print('incorrect character {0}, press cmd_r'.format(key))

def on_release(key):
    global condition
    print('{0} released'.format(key))
    if key == keyboard.Key.cmd_r:
        condition = False
        #keyboard.Listener.stop
        #return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

while condition==True:
    print "Condition true"

I am not sure why this is not working?..
It should in my head?

Body:
The issue is that when you call listener.join() your code waits at this point for the thread to complete. But it never will complete because it's always listening! Instead you want to call listener.start() so that the thread runs in the background and you are free to do what you want.

Sharing variables between threads is not generally accepted, so here I make a modified listener class that associates the variable key_pressed to itself when a key is pressed, and None when it is released. You can then do what you want with this variable by checking it at any time in a separate loop by calling listener.key_pressed

from pynput import keyboard
import time

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(self.on_press, self.on_release)
        self.key_pressed = None

    def on_press(self, key):
        self.key_pressed = key

    def on_release(self, key):
        self.key_pressed = None

listener = MyListener()
listener.start()

while True:
    time.sleep(0.1)
    print listener.key_pressed

Note that if you don't include a delay with time.sleep as above, you will overload the buffer and lead to delays in the output. Just put a small delay if you want it fast, but not zero.


问:
Compiling JavaScript which requires CommonJS functionality to native Java
I was wondering if anyone has tried/had any luck with compilation of JavaScript files which implement CommonJS APIs (require()), into native Java code.

I've currently got a site I'm building that will be using a text editor similar to this one, which stackoverflow open-sourced (a port of WMD editor):
http://code.google.com/p/pagedown/

This project comes with a few JavaScript files which sanitise and convert the markup language of the editor into valid HTML.

Having played around a bit with Rhino 1.7R4, I have managed to load the JavaScript files/modules at runtime, and I am able to execute the require functions as and when.

However, I would rather pre-compile these scripts into native Java code. I've managed to compile single scripts which don't use CommonJS features following this Rhino doc:

https://developer.mozilla.org/en-US/docs/Rhino/JavaScript_Compiler

But I'm at a loss as to the correct way to compile multiple dependent scripts that implement CommonJS features, and Rhino itself is not very well documented.

The idea is to have native Java code for markup conversion and sanitisation, without the translation cost of writing/maintaining two different code bases (by just converting the JS to JAVA).

Cheers

答:
RingoJS can do such a thing:

Ringo implements the CommonJS Modules specification. In short this means:

Every JavaScript file is treated a module living in its own top-level scope.

Any function or property attached to a module's exports object will be exposed.

The require() function returns a module's exports object.

If the given identifier string starts with ./ or ../ Ringo's module loader searches for a file and tries to load it. Therefore require('./foo') advices Ringo to load the file ./foo.js as module.

Otherwise Ringo looks for the module in every folder of the module path.

The module path is a list of standard locations in which Ringo will look for modules.

The module path can be set in the following ways:

Setting the RINGO_MODULE_PATH environment variable.

Setting the ringo.modulepath Java system property.

Using the -m or --modules option to the ringo command-line tool.

Using the module-path servlet init parameter with JsgiServlet.

Adding or removing elements to the require.paths Array-like property from within Ringo.

Packages provide a means of bundling several modules and other resources into one unit. Packages are directories that contain a package.json package descriptor file. The main property in the package.json descriptor is recognized by Ringo's module loader as the main entry point for a module:

```<code>{
    "main": "lib/main.js"
}
</code>```

If a module id resolves directly to a package directory and package.json defines a main property, Ringo will try to load the specified resource. The value of the main property must be a path relative to the package root.

If a module id resolves to a directory that does not contain a package.json file, or package.json does not define a main property, Ringo will try to load file index.js in that directory.

If part of a module id resolves to a package directory, Ringo will try to resolve the remaining part of the id against the lib directory of that package. The location of the lib directory can be overridden using the directories.lib property in package.json.

```<code>{
    "directories": {
        "lib": "new-lib"
    }
}
</code>```

The CommonJS modules specification was kept deliberately small. Ringo provides some extra niceties for exporting and importing stuff. The downside to using these is that your code is tied to Ringo, but it's relatively easy to convert the code to "pure" CommonJS, and there's also a command line tool for that purpose.

One Ringo extension is the include function. This is similar to require, but instead of returning the other module's exports object as a whole it directly copies each of its properties to the calling module's scope, making them usable like they were locally defined.

include is great for shell work and quick scripts where typing economy is paramount, and that's what it's meant for. It's usually not a great idea to use it for large, long lived programs as it conceals the origin of top-level functions used in the program.

For this purpose, it's more advisable to use require in combination with JavaScript 1.8 destructuring assignment to explicitly include selected properties from another module in the local scope:

```<code>var {foo, bar} = require("some/module");
</code>```

The above statements imports the "foo" and "bar" properties of the API exported by "some/module" directly in the calling scope.

Writing command line scripts with Ringo is straightforward. Every arbitrary JavaScript file can be passed as [script-file] argument to the ringo command:

```<code>ringo [script-file] [script-arg1] [script-arg2] ...
</code>```

Ringo loads the script file and provides the argument via the system module's args array. The first element in the args array is the script file's name.

References

Modules in Ringo - RingoJS

Command line tools - RingoJS

Java Integration - RingoJS

rhino/RELEASE-NOTES.md at master · mozilla/rhino

Body:
RingoJS can do such a thing:

Ringo implements the CommonJS Modules specification. In short this means:

Every JavaScript file is treated a module living in its own top-level scope.

Any function or property attached to a module's exports object will be exposed.

The require() function returns a module's exports object.

If the given identifier string starts with ./ or ../ Ringo's module loader searches for a file and tries to load it. Therefore require('./foo') advices Ringo to load the file ./foo.js as module.

Otherwise Ringo looks for the module in every folder of the module path.

The module path is a list of standard locations in which Ringo will look for modules.

The module path can be set in the following ways:

Setting the RINGO_MODULE_PATH environment variable.

Setting the ringo.modulepath Java system property.

Using the -m or --modules option to the ringo command-line tool.

Using the module-path servlet init parameter with JsgiServlet.

Adding or removing elements to the require.paths Array-like property from within Ringo.

Packages provide a means of bundling several modules and other resources into one unit. Packages are directories that contain a package.json package descriptor file. The main property in the package.json descriptor is recognized by Ringo's module loader as the main entry point for a module:

{
    "main": "lib/main.js"
}

If a module id resolves directly to a package directory and package.json defines a main property, Ringo will try to load the specified resource. The value of the main property must be a path relative to the package root.

If a module id resolves to a directory that does not contain a package.json file, or package.json does not define a main property, Ringo will try to load file index.js in that directory.

If part of a module id resolves to a package directory, Ringo will try to resolve the remaining part of the id against the lib directory of that package. The location of the lib directory can be overridden using the directories.lib property in package.json.

{
    "directories": {
        "lib": "new-lib"
    }
}

The CommonJS modules specification was kept deliberately small. Ringo provides some extra niceties for exporting and importing stuff. The downside to using these is that your code is tied to Ringo, but it's relatively easy to convert the code to "pure" CommonJS, and there's also a command line tool for that purpose.

One Ringo extension is the include function. This is similar to require, but instead of returning the other module's exports object as a whole it directly copies each of its properties to the calling module's scope, making them usable like they were locally defined.

include is great for shell work and quick scripts where typing economy is paramount, and that's what it's meant for. It's usually not a great idea to use it for large, long lived programs as it conceals the origin of top-level functions used in the program.

For this purpose, it's more advisable to use require in combination with JavaScript 1.8 destructuring assignment to explicitly include selected properties from another module in the local scope:

var {foo, bar} = require("some/module");

The above statements imports the "foo" and "bar" properties of the API exported by "some/module" directly in the calling scope.

Writing command line scripts with Ringo is straightforward. Every arbitrary JavaScript file can be passed as [script-file] argument to the ringo command:

ringo [script-file] [script-arg1] [script-arg2] ...

Ringo loads the script file and provides the argument via the system module's args array. The first element in the args array is the script file's name.

References

Modules in Ringo - RingoJS

Command line tools - RingoJS

Java Integration - RingoJS

rhino/RELEASE-NOTES.md at master · mozilla/rhino


问:
Resizing QTableView section with custom editor
I have an application with a QTableView and a model derived from QAbstractItemModel: the first column of the table contains a text (a label for each row), while the second column shows a value that can be selected using a QComboBox created from a custom item delegate. The content of the table may change dynamically (number of rows, language...).

I'd like to resize columns so the second one fits the content and the first one stretches occupying the remaining space.

My first attempt was:

```<code>tblData->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
tblData->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
</code>```

Result:

The problem is that when the QComboBox is selected it doesn't fit the section and it is clipped:

I've managed to solve this issue by manually increasing the width:

```<code>tblData->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
tblData->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
tblData->resizeColumnToContents(1);
tblData->horizontalHeader()->resizeSection(1, tblData->horizontalHeader()->sectionSize(1) + 40);
</code>```

Now the issue here is that by using such constant (40 in this case) the width of the section will vary depending on values displayed rather than in all the possible values (if the largest ones are already displayed vs if only the shortest). Also, that constant will be dependant to the style used, since it is also related to the space consumed by the QComboBox.

I've thought about using the Qt::SizeHintRole to manually compute the section width, but it is completely ignored. Even if it was, I cannot compute the actual width of the text (using QFontMetrics::width) because I don't have any font information in the model.

Another approach I've tried is to set the adjust size policy of the QComboBox in the QItemDelegate::createEditor method:

```<code>QWidget* myItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const {
  auto comboBox = new QComboBox(parent);
  comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
  // ...
}
</code>```

But now the combo boxes are either clipped or shortened.

How can I solve set the section size based on the complete range of content instead of just visible data?

I'm self-answering the question with the best approach I've found so far, and the one I'm using in the project right now, but I'm not convinced with it (I detail reasons on the answer) so I'd like to know the correct way to do it. Thanks!

答:
The best option I've found so far is to re-implement the QItemDelegate::sizeHint: I have the font information from the QStyleOptionViewItem and the list of elements to be included in the QComboBox.

```<code>QSize myItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
  auto hint = QItemDelegate::sizeHint(option, index);

  QFontMetrics fm(option.font);

  std::unique_ptr<QWidget> editor(createEditor(nullptr, option, index));
  auto comboBox = qobject_cast<QComboBox*>(editor.get());
  if (comboBox != nullptr) {
    int width = 0;
    for (int ii = 0; ii < comboBox->count(); ++ii) {
      width = std::max(width, fm.width(comboBox->itemText(ii)) + 20);
    }
    hint.setWidth(std::max(hint.width(), width));
  }

  return hint;
}
</code>```

Results:

Drawbacks of this solution are:

I don't have information regarding the additional space required by the QComboBox so it is not style-independant yet (as with the second approach on the question)

If new editors are added to the item delegate then I'd have to include them manually in the size hint computation too, which is not a terrible pain but feels like a bad design.

PS: using the QComboBox::sizeHint here doesn't work since size hint is computed using the QComboBox::sizeAdjustPolicy which, as highlighted in the question, doesn't adjust combo boxes correctly into the cell.

UPDATE

I've updated the solution following the indications from comments and accepted answer. Here is the complete code for future reference:

```<code>QStringList myItemDelegate::getPossibleValuesForIndex(const QModelIndex& index) const
{
  // returns list of all possible values for given index (the content of the combo box)
}

QSize myItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
  auto hint = QItemDelegate::sizeHint(option, index);

  QFontMetrics fm(option.font);
  QStyleOptionComboBox comboOption;
  comboOption.rect  = option.rect;
  comboOption.state = option.state | QStyle::State_Enabled;

  Q_FOREACH (const auto& value, getPossibleValuesForIndex(index)) {
    hint = hint.expandedTo(qApp->style()->sizeFromContents(QStyle::CT_ComboBox,
                           &comboOption, QSize(fm.width(value), hint.height())));
  }

  return hint;
}
</code>```

Body:
I have an application with a QTableView and a model derived from QAbstractItemModel: the first column of the table contains a text (a label for each row), while the second column shows a value that can be selected using a QComboBox created from a custom item delegate. The content of the table may change dynamically (number of rows, language...).

I'd like to resize columns so the second one fits the content and the first one stretches occupying the remaining space.

My first attempt was:

tblData->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
tblData->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);

Result:

The problem is that when the QComboBox is selected it doesn't fit the section and it is clipped:

I've managed to solve this issue by manually increasing the width:

tblData->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
tblData->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
tblData->resizeColumnToContents(1);
tblData->horizontalHeader()->resizeSection(1, tblData->horizontalHeader()->sectionSize(1) + 40);

Now the issue here is that by using such constant (40 in this case) the width of the section will vary depending on values displayed rather than in all the possible values (if the largest ones are already displayed vs if only the shortest). Also, that constant will be dependant to the style used, since it is also related to the space consumed by the QComboBox.

I've thought about using the Qt::SizeHintRole to manually compute the section width, but it is completely ignored. Even if it was, I cannot compute the actual width of the text (using QFontMetrics::width) because I don't have any font information in the model.

Another approach I've tried is to set the adjust size policy of the QComboBox in the QItemDelegate::createEditor method:

QWidget* myItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const {
  auto comboBox = new QComboBox(parent);
  comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
  // ...
}

But now the combo boxes are either clipped or shortened.

How can I solve set the section size based on the complete range of content instead of just visible data?

I'm self-answering the question with the best approach I've found so far, and the one I'm using in the project right now, but I'm not convinced with it (I detail reasons on the answer) so I'd like to know the correct way to do it. Thanks!

Body:
The best option I've found so far is to re-implement the QItemDelegate::sizeHint: I have the font information from the QStyleOptionViewItem and the list of elements to be included in the QComboBox.

QSize myItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
  auto hint = QItemDelegate::sizeHint(option, index);

  QFontMetrics fm(option.font);

  std::unique_ptr<QWidget> editor(createEditor(nullptr, option, index));
  auto comboBox = qobject_cast<QComboBox*>(editor.get());
  if (comboBox != nullptr) {
    int width = 0;
    for (int ii = 0; ii < comboBox->count(); ++ii) {
      width = std::max(width, fm.width(comboBox->itemText(ii)) + 20);
    }
    hint.setWidth(std::max(hint.width(), width));
  }

  return hint;
}

Results:

Drawbacks of this solution are:

I don't have information regarding the additional space required by the QComboBox so it is not style-independant yet (as with the second approach on the question)

If new editors are added to the item delegate then I'd have to include them manually in the size hint computation too, which is not a terrible pain but feels like a bad design.

PS: using the QComboBox::sizeHint here doesn't work since size hint is computed using the QComboBox::sizeAdjustPolicy which, as highlighted in the question, doesn't adjust combo boxes correctly into the cell.

UPDATE

I've updated the solution following the indications from comments and accepted answer. Here is the complete code for future reference:

QStringList myItemDelegate::getPossibleValuesForIndex(const QModelIndex& index) const
{
  // returns list of all possible values for given index (the content of the combo box)
}

QSize myItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
  auto hint = QItemDelegate::sizeHint(option, index);

  QFontMetrics fm(option.font);
  QStyleOptionComboBox comboOption;
  comboOption.rect  = option.rect;
  comboOption.state = option.state | QStyle::State_Enabled;

  Q_FOREACH (const auto& value, getPossibleValuesForIndex(index)) {
    hint = hint.expandedTo(qApp->style()->sizeFromContents(QStyle::CT_ComboBox,
                           &comboOption, QSize(fm.width(value), hint.height())));
  }

  return hint;
}


问:
GoogleApiClient connection failed: ConnectionResult{statusCode=SIGN_IN_REQUIRED,
I am attempting to integrate Google Drive into my application with little success. Using the code from the Quick Start repository, I get the following error message every time I select a user account for log in:

```<code>I/DriveDemo: GoogleApiClient connection failed: ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{867e070: android.os.BinderProxy@13cdfe9}, message=null}
</code>```

I have followed the directions at the urls below:

https://developers.google.com/drive/android/get-started

https://github.com/googledrive/android-quickstart

and followed the video at:

https://youtu.be/RezC1XP6jcs

I have also looked at numerous Stack Overflow questions and answers with no idea what I am doing wrong.

manifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lightkeeper54.chuck.drivedemo">

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Code:

```<code>protected void onResume() {
    super.onResume();
    if (mGoogleApiClient == null) {
        // Create the API client and bind it to an instance variable.
        // We use this instance as the callback for connection and connection
        // failures.
        // Since no account name is passed, the user is prompted to choose.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    // Connect the client. Once connected, the camera is launched.
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
    super.onPause();
}

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {
        case REQUEST_CODE_CAPTURE_IMAGE:
            // Called after a photo has been taken.
            if (resultCode == Activity.RESULT_OK) {
                // Store the image data as a bitmap for writing later.
                mBitmapToSave = (Bitmap) data.getExtras().get("data");
            }
            break;
        case REQUEST_CODE_CREATOR:
            // Called after a file is saved to Drive.
            if (resultCode == RESULT_OK) {
                Log.i(TAG, "Image successfully saved.");
                mBitmapToSave = null;
                // Just start the camera again for another photo.
                startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                        REQUEST_CODE_CAPTURE_IMAGE);
            }
            break;
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    // Called whenever the API client fails to connect.
    Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
    if (!result.hasResolution()) {
        // show the localized error dialog.
        GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
        return;
    }
    // The failure has a resolution. Resolve it.
    // Called typically when the app is not yet authorized, and an
    // authorization
    // dialog is displayed to the user.
    try {
        result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
    } catch (IntentSender.SendIntentException e) {
        Log.e(TAG, "Exception while starting resolution activity", e);
    }
}

@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "API client connected.");
    if (mBitmapToSave == null) {
        // This activity has no UI of its own. Just start the camera.
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                REQUEST_CODE_CAPTURE_IMAGE);
        return;
    }
    saveFileToDrive();
}

@Override
public void onConnectionSuspended(int cause) {
    Log.i(TAG, "GoogleApiClient connection suspended");
}
</code>```

答:
I had a similar problem which got fixed after I ensured that every APK build was signed by the same keystore that I used when doing "Get an Android certificate and register your application" as described here

When using Studio, I carried out "automatic signing" by following the steps described in "Configure the build process to automatically sign your APK" as described here. Obviously, use the same keystore as the one used when registering your app (above).

Body:
I am attempting to integrate Google Drive into my application with little success. Using the code from the Quick Start repository, I get the following error message every time I select a user account for log in:

I/DriveDemo: GoogleApiClient connection failed: ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{867e070: android.os.BinderProxy@13cdfe9}, message=null}

I have followed the directions at the urls below:

https://developers.google.com/drive/android/get-started

https://github.com/googledrive/android-quickstart

and followed the video at:

https://youtu.be/RezC1XP6jcs

I have also looked at numerous Stack Overflow questions and answers with no idea what I am doing wrong.

manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lightkeeper54.chuck.drivedemo">

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Code:

protected void onResume() {
    super.onResume();
    if (mGoogleApiClient == null) {
        // Create the API client and bind it to an instance variable.
        // We use this instance as the callback for connection and connection
        // failures.
        // Since no account name is passed, the user is prompted to choose.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    // Connect the client. Once connected, the camera is launched.
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
    super.onPause();
}

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {
        case REQUEST_CODE_CAPTURE_IMAGE:
            // Called after a photo has been taken.
            if (resultCode == Activity.RESULT_OK) {
                // Store the image data as a bitmap for writing later.
                mBitmapToSave = (Bitmap) data.getExtras().get("data");
            }
            break;
        case REQUEST_CODE_CREATOR:
            // Called after a file is saved to Drive.
            if (resultCode == RESULT_OK) {
                Log.i(TAG, "Image successfully saved.");
                mBitmapToSave = null;
                // Just start the camera again for another photo.
                startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                        REQUEST_CODE_CAPTURE_IMAGE);
            }
            break;
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    // Called whenever the API client fails to connect.
    Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
    if (!result.hasResolution()) {
        // show the localized error dialog.
        GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
        return;
    }
    // The failure has a resolution. Resolve it.
    // Called typically when the app is not yet authorized, and an
    // authorization
    // dialog is displayed to the user.
    try {
        result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
    } catch (IntentSender.SendIntentException e) {
        Log.e(TAG, "Exception while starting resolution activity", e);
    }
}

@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "API client connected.");
    if (mBitmapToSave == null) {
        // This activity has no UI of its own. Just start the camera.
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                REQUEST_CODE_CAPTURE_IMAGE);
        return;
    }
    saveFileToDrive();
}

@Override
public void onConnectionSuspended(int cause) {
    Log.i(TAG, "GoogleApiClient connection suspended");
}


问:
Time conversion between ruby on rails and javascript vice versa?
How to convert ruby time to javascript time and vice versa?

Ruby on rails :

```<code> Time.now
</code>```

Javascript :

```<code> new Date()
</code>```

答:
These methods in both are equivalent, use either:

For Ruby:

```<code>Time.now.httpdate
</code>```

For Javascript:

```<code>new Date().toUTCString()
</code>```

Output for both:

```<code>Tue, 04 Jul 2017 14:18:31 GMT
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to convert ruby time to javascript time and vice versa?

Ruby on rails :

 Time.now

Javascript :

 new Date()

Body:
These methods in both are equivalent, use either:

For Ruby:

Time.now.httpdate

For Javascript:

new Date().toUTCString()

Output for both:

Tue, 04 Jul 2017 14:18:31 GMT


问:
Moment.js - Get all mondays between a date range
I have a date range that looks like this

```<code>let start = moment(this.absence.FromDate);
let end = moment(this.absence.ToDate);
</code>```

The user can decide to deactivate specific week days during that date range, so I have booleans

```<code>monday = true;
tuesday = false;
...
</code>```

I want to create a function that allows me to put all mondays during my date range in an array.

I've looked around on stack but I can only find help for people who need all the monday from a month for example.

答:
You can get next Monday using .day(1) and then loop until your date isBefore your end date adding 7 days for each iteration using add

Here a live sample:

//let start = moment(this.absence.FromDate);
//let end = moment(this.absence.ToDate);

// Test values
let start = moment();
let end = moment().add(45 , 'd');

var arr = [];
// Get "next" monday
let tmp = start.clone().day(1);
if( tmp.isAfter(start, 'd') ){
  arr.push(tmp.format('YYYY-MM-DD'));
}
while( tmp.isBefore(end) ){
  tmp.add(7, 'days');
  arr.push(tmp.format('YYYY-MM-DD'));
}
console.log(arr);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
I have a date range that looks like this

let start = moment(this.absence.FromDate);
let end = moment(this.absence.ToDate);

The user can decide to deactivate specific week days during that date range, so I have booleans

monday = true;
tuesday = false;
...

I want to create a function that allows me to put all mondays during my date range in an array.

I've looked around on stack but I can only find help for people who need all the monday from a month for example.

Body:
You can get next Monday using .day(1) and then loop until your date isBefore your end date adding 7 days for each iteration using add

Here a live sample:

//let start = moment(this.absence.FromDate);
//let end = moment(this.absence.ToDate);

// Test values
let start = moment();
let end = moment().add(45 , 'd');

var arr = [];
// Get "next" monday
let tmp = start.clone().day(1);
if( tmp.isAfter(start, 'd') ){
  arr.push(tmp.format('YYYY-MM-DD'));
}
while( tmp.isBefore(end) ){
  tmp.add(7, 'days');
  arr.push(tmp.format('YYYY-MM-DD'));
}
console.log(arr);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
How to clear out Array before writing new data in for loop in JavaScript?
I am creating a select option for Birthdate which includes Month and Date for testing purposes for now. Everything works fine but the problem is when i select January for instance then it will give days upto 31 but if i 31 remains selected and when i select Febraury it adds previous array with new array i.e. January's 31 days + Febraury 28 days. Please help me how do I clear previous array first then add new one.

Here's The Javascript:

```<code>    function change(){
    var s1 = document.getElementById('select1');
    var s2 = document.getElementById('select2');
    var i;
    var optionIndex = [];

    if(s1.value === 'January'){
        var i;
        s2.style.display = 'inline-block';
        for(i = 1; i <= 31; i = i + 1){
            optionIndex.push(i);
        }
    }else if(s1.value === 'February'){
         var i;
        s2.style.display = 'inline-block';
        for(i = 1; i <= 28; i = i + 1){
            optionIndex.push(i);
        }
    }

    var option;
    for(option in optionIndex){
        if(optionIndex.hasOwnProperty(option)){
        var pair = optionIndex[option];
        var createOption = document.createElement('option');
        createOption.innerHTML = pair;
        s2.appendChild(createOption);
        }
    }
}
</code>```

And the HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Selector</title>
</head>
<body>
    <select id = "select1" name = "select1" onchange="change()">
       <option>Select Year...</option>
        <option>January</option>
        <option>February</option>
        <option>March</option>
        <option>April</option>
        <option>May</option>
        <option>June</option>
        <option>July</option>
        <option>August</option>
        <option>September</option>
        <option>October</option>
        <option>November</option>
        <option>December</option>
    </select>
    <select id = "select2" name = "select2" style = "display:none;">

    </select>
</body>
</html>
</code>```

I tried array.pop(), array.splice() but still doesn't work! Please help me!

答:
your issue in not with array - it is good - the problem is that you don't clear s2 when you trigger change. Try

function change(){
            var s1 = document.getElementById('select1');
            var s2 = document.getElementById('select2');
            var i;
            var optionIndex = [];

            if(s1.value === 'January'){
                var i;
                s2.style.display = 'inline-block';
                for(i = 1; i <= 31; i = i + 1){
                    optionIndex.push(i);
                }
            }else if(s1.value === 'February'){
                 var i;
                s2.style.display = 'inline-block';
                for(i = 1; i <= 28; i = i + 1){
                    optionIndex.push(i);
                }
            }
            s2.innerHTML = ""; // You need this

            var option;
            for(option in optionIndex){
                if(optionIndex.hasOwnProperty(option)){
                    var pair = optionIndex[option];
                    var createOption = document.createElement('option');
                    createOption.innerHTML = pair;
                    s2.appendChild(createOption);
                }
            }
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id = "select1" name = "select1" onchange="change()">
       <option>Select Year...</option>
        <option>January</option>
        <option>February</option>
        <option>March</option>
        <option>April</option>
        <option>May</option>
        <option>June</option>
        <option>July</option>
        <option>August</option>
        <option>September</option>
        <option>October</option>
        <option>November</option>
        <option>December</option>
    </select>
    <select id = "select2" name = "select2" style = "display:none;">

    </select></code>```

Body:
I am creating a select option for Birthdate which includes Month and Date for testing purposes for now. Everything works fine but the problem is when i select January for instance then it will give days upto 31 but if i 31 remains selected and when i select Febraury it adds previous array with new array i.e. January's 31 days + Febraury 28 days. Please help me how do I clear previous array first then add new one.

Here's The Javascript:

    function change(){
    var s1 = document.getElementById('select1');
    var s2 = document.getElementById('select2');
    var i;
    var optionIndex = [];

    if(s1.value === 'January'){
        var i;
        s2.style.display = 'inline-block';
        for(i = 1; i <= 31; i = i + 1){
            optionIndex.push(i);
        }
    }else if(s1.value === 'February'){
         var i;
        s2.style.display = 'inline-block';
        for(i = 1; i <= 28; i = i + 1){
            optionIndex.push(i);
        }
    }

    var option;
    for(option in optionIndex){
        if(optionIndex.hasOwnProperty(option)){
        var pair = optionIndex[option];
        var createOption = document.createElement('option');
        createOption.innerHTML = pair;
        s2.appendChild(createOption);
        }
    }
}

And the HTML:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Form Selector</title>

    <select id = "select1" name = "select1" onchange="change()">
       <option>Select Year...</option>
        <option>January</option>
        <option>February</option>
        <option>March</option>
        <option>April</option>
        <option>May</option>
        <option>June</option>
        <option>July</option>
        <option>August</option>
        <option>September</option>
        <option>October</option>
        <option>November</option>
        <option>December</option>
    </select>
    <select id = "select2" name = "select2" style = "display:none;">

    </select>

I tried array.pop(), array.splice() but still doesn't work! Please help me!

Body:
your issue in not with array - it is good - the problem is that you don't clear s2 when you trigger change. Try

function change(){
            var s1 = document.getElementById('select1');
            var s2 = document.getElementById('select2');
            var i;
            var optionIndex = [];

            if(s1.value === 'January'){
                var i;
                s2.style.display = 'inline-block';
                for(i = 1; i <= 31; i = i + 1){
                    optionIndex.push(i);
                }
            }else if(s1.value === 'February'){
                 var i;
                s2.style.display = 'inline-block';
                for(i = 1; i <= 28; i = i + 1){
                    optionIndex.push(i);
                }
            }
            s2.innerHTML = ""; // You need this

            var option;
            for(option in optionIndex){
                if(optionIndex.hasOwnProperty(option)){
                    var pair = optionIndex[option];
                    var createOption = document.createElement('option');
                    createOption.innerHTML = pair;
                    s2.appendChild(createOption);
                }
            }
        }

<select id = "select1" name = "select1" onchange="change()">
       <option>Select Year...</option>
        <option>January</option>
        <option>February</option>
        <option>March</option>
        <option>April</option>
        <option>May</option>
        <option>June</option>
        <option>July</option>
        <option>August</option>
        <option>September</option>
        <option>October</option>
        <option>November</option>
        <option>December</option>
    </select>
    <select id = "select2" name = "select2" style = "display:none;">

    </select>


问:
Php using 2 classes
ive been trying to learn some php and i wanted to make a logger

I get user input, put in into an array and make it into json:

This is the class that gets the info:

```<code><?php
class account_Creation
{

    private $username;
    private $password;
    private $email;

    //user input
    public function user_input()
    {
        $username = 'username';
        $password = "password";
        $email = "email";
        $result_array= compact("username","password", "email");
    }
}

$account_creation= new account_Creation();
$account_creation-> user_input();
$logging= new Logging();
$logging-> json_Translator($result_array);
</code>```

This is the class that translates it into json:

```<code><?php
class Logging
{
    public function json_Translator($data)
    {
        echo json_encode($data);
    }
}
</code>```

I get the error: Uncaught Error: Class 'Logging' not found
How do i show the account creation class where the logging class is? I tried include but that did not work

答:
I fix your issue but suggest you to learn OOP</p>

```<code><?php
class account_Creation
{

private $username;
private $password;
private $email;
public $result_array;

//user input
public function user_input()
{
    $this->username = 'username';
    $this->password = "password";
    $this->email = "email";
    $this->result_array= ["username","password", "email"];
}

}
class Logging
{
        public function json_Translator($data)
    {
        echo json_encode($data);

    }

}
$account_creation= new account_Creation();
$account_creation->user_input();
$logging= new Logging();
$logging->json_Translator($account_creation->result_array);
</code>```

Title: Php using 2 classes

Body:
ive been trying to learn some php and i wanted to make a logger

I get user input, put in into an array and make it into json:

This is the class that gets the info:

<?php
class account_Creation
{

    private $username;
    private $password;
    private $email;

    //user input
    public function user_input()
    {
        $username = 'username';
        $password = "password";
        $email = "email";
        $result_array= compact("username","password", "email");
    }
}

$account_creation= new account_Creation();
$account_creation-> user_input();
$logging= new Logging();
$logging-> json_Translator($result_array);

This is the class that translates it into json:

<?php
class Logging
{
    public function json_Translator($data)
    {
        echo json_encode($data);
    }
}

I get the error: Uncaught Error: Class 'Logging' not found
How do i show the account creation class where the logging class is? I tried include but that did not work

Body:
I fix your issue but suggest you to learn OOP

<?php
class account_Creation
{

private $username;
private $password;
private $email;
public $result_array;

//user input
public function user_input()
{
    $this->username = 'username';
    $this->password = "password";
    $this->email = "email";
    $this->result_array= ["username","password", "email"];
}

}
class Logging
{
        public function json_Translator($data)
    {
        echo json_encode($data);

    }

}
$account_creation= new account_Creation();
$account_creation->user_input();
$logging= new Logging();
$logging->json_Translator($account_creation->result_array);


问:
Changing the "Timeout" Variable in agentd.conf
I am currently getting a "Zabbix agent %hostname is unreachable for X minutes". I want to increase this X to another value.

I have done some research and have noticed that I do not have to change the triggers but rather a variable in the .conf file. However, I am unable to actually find this file. I am wondering if this file is independent to each machine and has to be changed on each one (based on preference) or if there is some unique location I must look.

Sorry for the silly question!

答: That actually is a threshold in the trigger expression, not in any configuration files. Go to the host in question, look for triggers. If you want to change this for all hosts, change it in the template. If you want to change this only for a single host, modify the trigger in the template to use usermacro for the threshold, then override that value on the host.</p>


问:
Where is the code that causes setState (React) to be asynchronous?
I recently read through a large portion of the React and ReactDOM codebase in order to get an understanding of what happens when a call to setState occurs. At this point, I would say that I understand the sequence of events at a high level. A call to setState results in a message being added to a queue of updates that need to be processed. The updates are processed and changes to the DOM are only made if necessary.

Here's where I am lost. There are hundreds of blog posts discussing the asynchronous behavior of setState. While I don't doubt that setState is asynchronous, I cannot find a line of code in the ReactDOM codebase that would introduce asynchronous behavior. Does anyone know exactly where this happens?

答: i think setState isn't async, but there is an optimization of multiple setState calls and in some cases sync canot be guaranteed. </p>


问:
Can the compiler exploit empty base optimisation if the class contains a member of the base class?
Consider

```<code>struct base {};
struct child : base {};
</code>```

It's well-known that sizeof(child) can be 1 by application of the empty base optimisation.

Now however, consider

```<code>struct base {};
struct child : base {base b;};
</code>```

Can the compiler apply the empty base optimisation now, or must sizeof(child) be at least 2?

Reference: http://en.cppreference.com/w/cpp/language/ebo

答:
Objects in C++ are required to have unique "identity". From [intro.object]/8 (N4659):

Two objects a and b with overlapping lifetimes that are not bit-fields may have the same address if one is nested within the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they have distinct addresses.

A base class subobject and a member subobject are separate objects; neither is "nested within" the other. Therefore, if they are of the same type, they must have separate addresses.

Note that this extends recursively. Consider the following:

```<code>struct eb1 {};

struct eb2 : eb1 {};
struct not_empty(eb1 a;};

struct derived : eb2 {not_empty b;};
</code>```

Because of the unique identity rule of C++, derived::eb2::eb1 must have a different address from derived::b::a. Therefore, the compiler cannot employ EBO on derived.

Body:
Consider

struct base {};
struct child : base {};

It's well-known that sizeof(child) can be 1 by application of the empty base optimisation.

Now however, consider

struct base {};
struct child : base {base b;};

Can the compiler apply the empty base optimisation now, or must sizeof(child) be at least 2?

Reference: http://en.cppreference.com/w/cpp/language/ebo

Body:
Objects in C++ are required to have unique "identity". From [intro.object]/8 (N4659):

Two objects a and b with overlapping lifetimes that are not bit-fields may have the same address if one is nested within the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they have distinct addresses.

A base class subobject and a member subobject are separate objects; neither is "nested within" the other. Therefore, if they are of the same type, they must have separate addresses.

Note that this extends recursively. Consider the following:

struct eb1 {};

struct eb2 : eb1 {};
struct not_empty(eb1 a;};

struct derived : eb2 {not_empty b;};

Because of the unique identity rule of C++, derived::eb2::eb1 must have a different address from derived::b::a. Therefore, the compiler cannot employ EBO on derived.


问:
Python3: Base Constructor getting called implicitly
So I really don't understand how Python3 handles constructors. Most questions here seem to have the problem that their base constructor is not called, I've got the problem (I think) that it is being called.
What I'm trying to do is to define a class whose constructor returns a bytes objects based on some other data passed in the constructor.

```<code>class MyObj(bytes):
    def __init__(self, data):
        ## do stuff to calculate a bytes_object from data
        ## in the C++ example below, I just reinterpret_cast the data
        ## call super(MyObj, self).__init__(bytes_object) to invoke
        ## the copy constructor
        pass

construct_MyObj_for_this_data = [0.4,2.5,12.1]
newmyobj = MyObj(construct_MyObj_obj_for_this_data)
</code>```

If this is run in the Interpreter, I get this:

```<code>TypeError: 'float' object cannot be interpreted as an integer
</code>```

It seems that MyObj() is always calling the Base (i.e. bytes) constructor, which I don't want. Passing values to MyObj which are valid objects for the bytes constructor works, and newmyobj gets the value of that bytes object.
I believe I'm thinking too much C++...

If its still unclear what I want, here is a working C++ example doing the correct thing:

```<code>#include <vector>

struct list {
    float x;
    float y;
    float z;
};

class MyObj : std::vector<char> {
public:
    MyObj(list data) {
        this->resize(sizeof(data));
        std::copy(reinterpret_cast<char*>(&data)
                , reinterpret_cast<char*>(&data.x)+sizeof(data)
                , this->begin());
    }
};

int main (int argc, char* argv[]) {
    list data = {0.4,2.5,12.1};
    MyObj newmyobj = MyObj(data);
}
</code>```

The MyObj could then be used everywhere, where a std::vector can be used, and have all the other convenience C++ containers have.

答:
The __init__() is not the constructor. You need to implement __new__(), which is really the constructor. For example:

```<code>class MyObj(bytes):
    def __new__(cls, data):
        # do operations here
        # dummy example
        new_data = [int(x) for x in data]
        return super().__new__(cls, new_data)

newmyobj = MyObj([0.4,2.5,12.1])
</code>```

Also bytes are immutable. Therefore, doing something in __init__() might be too late.

Body:
So I really don't understand how Python3 handles constructors. Most questions here seem to have the problem that their base constructor is not called, I've got the problem (I think) that it is being called.
What I'm trying to do is to define a class whose constructor returns a bytes objects based on some other data passed in the constructor.

class MyObj(bytes):
    def __init__(self, data):
        ## do stuff to calculate a bytes_object from data
        ## in the C++ example below, I just reinterpret_cast the data
        ## call super(MyObj, self).__init__(bytes_object) to invoke
        ## the copy constructor
        pass

construct_MyObj_for_this_data = [0.4,2.5,12.1]
newmyobj = MyObj(construct_MyObj_obj_for_this_data)

If this is run in the Interpreter, I get this:

TypeError: 'float' object cannot be interpreted as an integer

It seems that MyObj() is always calling the Base (i.e. bytes) constructor, which I don't want. Passing values to MyObj which are valid objects for the bytes constructor works, and newmyobj gets the value of that bytes object.
I believe I'm thinking too much C++...

If its still unclear what I want, here is a working C++ example doing the correct thing:

#include <vector>

struct list {
    float x;
    float y;
    float z;
};

class MyObj : std::vector<char> {
public:
    MyObj(list data) {
        this->resize(sizeof(data));
        std::copy(reinterpret_cast<char*>(&data)
                , reinterpret_cast<char*>(&data.x)+sizeof(data)
                , this->begin());
    }
};

int main (int argc, char* argv[]) {
    list data = {0.4,2.5,12.1};
    MyObj newmyobj = MyObj(data);
}

The MyObj could then be used everywhere, where a std::vector can be used, and have all the other convenience C++ containers have.

Body:
The __init__() is not the constructor. You need to implement __new__(), which is really the constructor. For example:

class MyObj(bytes):
    def __new__(cls, data):
        # do operations here
        # dummy example
        new_data = [int(x) for x in data]
        return super().__new__(cls, new_data)

newmyobj = MyObj([0.4,2.5,12.1])

Also bytes are immutable. Therefore, doing something in __init__() might be too late.