问:
Function with variable parameter size: How to conditionally set some arguments?
To create a boost::process with output redirection, you should do:

```<code>bp::ipstream out;
bp::child c("c++filt", std_out > out);
</code>```

Now, what would be the syntax to conditionally control the redirection:

```<code>bool redirect = true; // or false
bp::ipstream out;
bp::child c("c++filt", (redirect) ? std_out > out : "what should I put here??" );
</code>```

答:
I've been there.

Indeed, launcher functions (not exactly factories, but composable procedural wrappers) were what I used.

Intro

We had a CommandRunner with a legacy implementation that I rewrote to use Boost. I'm skipping the public interface:

```<code>class CommandRunner {
    public: struct IRunnerImpl;
};
</code>```

The implementation was Pimpl-ed and worked with the base implementation storing mostly simple implementation-independent parameters:

```<code>struct CommandRunner::IRunnerImpl {
    virtual ~IRunnerImpl() = default;

    virtual void run()                    = 0;
    virtual void ensure_completed()       = 0;
    virtual std::string to_string() const = 0;

    friend class CommandRunner;
  protected:
    std::string            _working_directory;
    mylibrary::optional<mylibrary::io::time::duration> _time_constraint;
    std::string            _stdin_data;
    int                    _redirected_output_fd     = -1;
    std::string            _redirected_output_fname;
    bool                   _discard_output           = false;
    int                    _exit_code;
    std::string            _stdout_str;
    std::string            _stderr_str;
    bool                   _command_timed_out        = false;
    bool                   _sensitive_args           = false;
    string_map_t           _env;
};
</code>```

The Boost RunnerImpl

The core of ensure_completed was composed using helper lambdas like this:

```<code>try {
    mylibrary::threads::safe_io_service safe_ios;
    boost::asio::io_service& ios = safe_ios;
    mylibrary::io::time::timer deadline(ios);

    bp::group process_group;

    bp::async_pipe input(ios);
    std::future<std::string> output, error;

    if (_working_directory.empty())
        _working_directory = ".";

    auto on_exit = [this, &deadline](int exit, std::error_code ec) {
        if (!_command_timed_out) {
            _exit_code = exit;
        }
        deadline.cancel();
        if (ec) s_logger.log(LOG_WARNING) << "Child process returned " << ec.message();
        else    s_logger.log(LOG_DEBUG)   << "Child process returned";
    };

    auto launcher = [](auto&&... args) { return bp::child(std::forward<decltype(args)>(args).../*, bp::posix::fd.restrict_inherit()*/); };

    auto redirect_out = [&](auto f) {
        return [&,f](auto&&... args) {
            if (_discard_output) {
                if (_redirected_output_fd != -1 && !_redirected_output_fname.empty()) {
                    s_logger.log(LOG_ERR) << "Ignoring output redirection with set_discard_output. This is a bug.";
                }
                return f(std::forward<decltype(args)>(args)..., bp::std_out > bp::null, bp::std_err > bp::null);
            }

            if (_redirected_output_fd != -1 && !_redirected_output_fname.empty()) {
                s_logger.log(LOG_WARNING) << "Conflicting output redirection, ignoring filename with descriptor";
            }

            if (_redirected_output_fd != -1) {
                return f(std::forward<decltype(args)>(args)..., bp::posix::fd.bind(1, _redirected_output_fd), bp::std_err > error);
            }

            return _redirected_output_fname.empty()
                ? f(std::forward<decltype(args)>(args)..., bp::std_out > output,                   bp::std_err > error)
                : f(std::forward<decltype(args)>(args)..., bp::std_out > _redirected_output_fname, bp::std_err > error);
        };
    };

    bp::environment bp_env = boost::this_process::environment();
    for (auto& p : _env)
        bp_env[p.first] = p.second;

    auto c = redirect_out(launcher)(_command_path, _args,
            process_group,
            bp::std_in < input,
            bp::start_dir(_working_directory),
            bp_env,
            ios, bp::on_exit(on_exit)
        );

    if (_time_constraint) {
        deadline.expires_from_now(*_time_constraint);
        deadline.async_wait([&](boost::system::error_code ec) {
            if (ec != boost::asio::error::operation_aborted) {
                if (ec) {
                    s_logger.log(LOG_WARNING) << "Unexpected condition in CommandRunner deadline: " << ec.message();
                }

                _command_timed_out = true;
                _exit_code = 1;
                ::killpg(process_group.native_handle(), SIGTERM);

                deadline.expires_from_now(3s); // grace time
                deadline.async_wait([&](boost::system::error_code ec) { if (!ec) process_group.terminate(); }); // timed out
            }
        });
    }

    boost::asio::async_write(input, bp::buffer(_stdin_data), [&input](auto ec, auto bytes_written){
        if (ec) {
            s_logger.log(LOG_WARNING) << "Standard input rejected: " << ec.message() << " after " << bytes_written << " bytes written";
        }
        may_fail([&] { input.close(); });
    });

    ios.run();

    if (output.valid()) _stdout_str = output.get();
    if (error.valid())  _stderr_str = error.get();

    // make sure no grand children survive
    if (process_group && process_group.joinable() && !process_group.wait_for(1s))
        process_group.terminate();

    // Note: even kills get the child reaped; 'on_exit' handler is
    // actually the 'on wait_pid() complete'). No need for c.wait()
    // in this scenario
    //// may_fail([&] { if (c.running()) c.wait(); }); // to avoid zombies
} catch(bp::process_error const& e) {
    if (e.code().value() != static_cast<int>(std::errc::no_child_process)) throw;
}
</code>```

Full Self-Contained Listing

This compiles, but doesn't have any public interface. Merely for expositional purposes.

Note:

this didn't go into production as there were cases in which the Boost implementation would get stuck in async IO operations. The reason for this has remained unclear, but I suspect it is a hairy case of epoll is fundamentally broken related to our use cases being "wildly" multi-threaded and forking.

this does not include our attempted workarounds for safe_io_service (that guarantees fork synchronization and notifications on all active io_services)

this does not include our patch that adds restricted FD inheritance:

```<code>auto launcher = [](auto&&... args) { return
     bp::child(std::forward<decltype(args)>(args)...,
     bp::posix::fd.restrict_inherit()); };
</code>```

other crucial things like on-fork handlers for global (library) state have not been shown here (they used pthread_atfork and similar)

Compiling On Coliru

```<code>#include <boost/process.hpp>
#include <boost/process/extend.hpp>
#include <boost/process/async.hpp>
#include <boost/process/posix.hpp>
#include <boost/optional.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <signal.h> // ::killpg
#include <iomanip>
#include <map>

///////
// mockups for standalone exposition
//#include "log.h"
enum LOG_LEVELS{LOG_DEBUG, LOG_WARNING, LOG_ERR};

struct DummyLogger {
    struct Tx {
        template <typename...Ts> friend Tx operator<<(Tx const&, Ts&&...) { return {}; }
    };
    Tx log(LOG_LEVELS) { return {}; }
} s_logger;

//#include "safe_io_service.h"
namespace mylibrary {
    namespace threads {
        //this did manage fork notifications
        using safe_io_service = boost::asio::io_service;
    }
    using boost::optional;
    namespace io { namespace time {
            using clock = std::chrono::high_resolution_clock;
            using duration = clock::duration;
            using timer = boost::asio::high_resolution_timer;
        }
    }
}
using namespace std::chrono_literals;

using string_vector_t = std::vector<std::string>;
using string_map_t = std::map<std::string, std::string>;

class CommandRunner {
    public: struct IRunnerImpl;
};

struct CommandRunner::IRunnerImpl {
    virtual ~IRunnerImpl() = default;

    virtual void run()                    = 0;
    virtual void ensure_completed()       = 0;
    virtual std::string to_string() const = 0;

    friend class CommandRunner;
  protected:
    std::string            _working_directory;
    mylibrary::optional<mylibrary::io::time::duration> _time_constraint;
    std::string            _stdin_data;
    int                    _redirected_output_fd     = -1;
    std::string            _redirected_output_fname;
    bool                   _discard_output           = false;
    int                    _exit_code;
    std::string            _stdout_str;
    std::string            _stderr_str;
    bool                   _command_timed_out        = false;
    bool                   _sensitive_args           = false;
    string_map_t           _env;
};

//
//////////////////////////////////////

namespace {

    namespace bp = boost::process;

    template <typename F> static auto may_fail(F&& f) {
        try {
            return std::forward<F>(f)();
        } catch(std::exception const& e) {
            s_logger.log(LOG_DEBUG) << "Ignoring non-fatal error (" << e.what() << ")";
        } catch(...) {
            s_logger.log(LOG_DEBUG) << "Ignoring non-fatal, unspecified error";
        }
    }

}

namespace mylibrary { namespace process { namespace with_boost {

    struct BoostRunnerImpl : CommandRunner::IRunnerImpl {

        BoostRunnerImpl(std::string cmd_path, string_vector_t args) :
            _command_path(std::move(cmd_path)),
            _args(std::move(args))
        {
        }

        std::string _command_path;
        string_vector_t _args;

        virtual void run() override {
            if (_completed) {
                s_logger.log(LOG_DEBUG) << "NOT running already completed command: " << *this;
                return;
            }
            ensure_completed();
        }

        ////////////////////////////
        // implementation
        virtual void ensure_completed() override {
            if (_completed) return;

            // Log command and args
            s_logger.log(LOG_DEBUG) << "Running command: " << *this;

            try {
                try {
                    mylibrary::threads::safe_io_service safe_ios;
                    boost::asio::io_service& ios = safe_ios;
                    mylibrary::io::time::timer deadline(ios);

                    bp::group process_group;

                    bp::async_pipe input(ios);
                    std::future<std::string> output, error;

                    if (_working_directory.empty())
                        _working_directory = ".";

                    auto on_exit = [this, &deadline](int exit, std::error_code ec) {
                        if (!_command_timed_out) {
                            _exit_code = exit;
                        }
                        deadline.cancel();
                        if (ec) s_logger.log(LOG_WARNING) << "Child process returned " << ec.message();
                        else    s_logger.log(LOG_DEBUG)   << "Child process returned";
                    };

                    auto launcher = [](auto&&... args) { return bp::child(std::forward<decltype(args)>(args).../*, bp::posix::fd.restrict_inherit()*/); };

                    auto redirect_out = [&](auto f) {
                        return [&,f](auto&&... args) {
                            if (_discard_output) {
                                if (_redirected_output_fd != -1 && !_redirected_output_fname.empty()) {
                                    s_logger.log(LOG_ERR) << "Ignoring output redirection with set_discard_output. This is a bug.";
                                }
                                return f(std::forward<decltype(args)>(args)..., bp::std_out > bp::null, bp::std_err > bp::null);
                            }

                            if (_redirected_output_fd != -1 && !_redirected_output_fname.empty()) {
                                s_logger.log(LOG_WARNING) << "Conflicting output redirection, ignoring filename with descriptor";
                            }

                            if (_redirected_output_fd != -1) {
                                return f(std::forward<decltype(args)>(args)..., bp::posix::fd.bind(1, _redirected_output_fd), bp::std_err > error);
                            }

                            return _redirected_output_fname.empty()
                                ? f(std::forward<decltype(args)>(args)..., bp::std_out > output,                   bp::std_err > error)
                                : f(std::forward<decltype(args)>(args)..., bp::std_out > _redirected_output_fname, bp::std_err > error);
                        };
                    };

                    bp::environment bp_env = boost::this_process::environment();
                    for (auto& p : _env)
                        bp_env[p.first] = p.second;

                    auto c = redirect_out(launcher)(_command_path, _args,
                            process_group,
                            bp::std_in < input,
                            bp::start_dir(_working_directory),
                            bp_env,
                            ios, bp::on_exit(on_exit)
                        );

                    if (_time_constraint) {
                        deadline.expires_from_now(*_time_constraint);
                        deadline.async_wait([&](boost::system::error_code ec) {
                            if (ec != boost::asio::error::operation_aborted) {
                                if (ec) {
                                    s_logger.log(LOG_WARNING) << "Unexpected condition in CommandRunner deadline: " << ec.message();
                                }

                                _command_timed_out = true;
                                _exit_code = 1;
                                ::killpg(process_group.native_handle(), SIGTERM);

                                deadline.expires_from_now(3s); // grace time
                                deadline.async_wait([&](boost::system::error_code ec) { if (!ec) process_group.terminate(); }); // timed out
                            }
                        });
                    }

                    boost::asio::async_write(input, bp::buffer(_stdin_data), [&input](auto ec, auto bytes_written){
                        if (ec) {
                            s_logger.log(LOG_WARNING) << "Standard input rejected: " << ec.message() << " after " << bytes_written << " bytes written";
                        }
                        may_fail([&] { input.close(); });
                    });

                    ios.run();

                    if (output.valid()) _stdout_str = output.get();
                    if (error.valid())  _stderr_str = error.get();

                    // make sure no grand children survive
                    if (process_group && process_group.joinable() && !process_group.wait_for(1s))
                        process_group.terminate();

                    // Note: even kills get the child reaped; 'on_exit' handler is
                    // actually the 'on wait_pid() complete'). No need for c.wait()
                    // in this scenario
                    //// may_fail([&] { if (c.running()) c.wait(); }); // to avoid zombies
                } catch(bp::process_error const& e) {
                    if (e.code().value() != static_cast<int>(std::errc::no_child_process)) throw;
                }
            } catch(std::exception const& e) {
                s_logger.log(LOG_ERR) << "CommandRunner: " << e.what();
                _completed = true;
                _exit_code = 1;
                throw;
            } catch(...) {
                s_logger.log(LOG_ERR) << "CommandRunner: unexpected error";
                _completed = true;
                _exit_code = 1;
                throw;
            }

            _completed = true;
        }

      private:
        bool _completed = false;

        friend std::ostream& operator<<(std::ostream& os, BoostRunnerImpl const& i) {
            os << i._command_path;
            if (i._sensitive_args)
                os << " (" << i._args.size() << " args)";
            else for (auto& arg : i._args)
                os << " " << std::quoted(arg);
            return os;
        }

        virtual std::string to_string() const override {
            std::ostringstream oss;
            oss << *this;
            return oss.str();
        }
    };

} } }

int main(){}
</code>```

Body:
To create a boost::process with output redirection, you should do:

bp::ipstream out;
bp::child c("c++filt", std_out > out);

Now, what would be the syntax to conditionally control the redirection:

bool redirect = true; // or false
bp::ipstream out;
bp::child c("c++filt", (redirect) ? std_out > out : "what should I put here??" );

Body:
I've been there.

Indeed, launcher functions (not exactly factories, but composable procedural wrappers) were what I used.

Intro

We had a CommandRunner with a legacy implementation that I rewrote to use Boost. I'm skipping the public interface:

class CommandRunner {
    public: struct IRunnerImpl;
};

The implementation was Pimpl-ed and worked with the base implementation storing mostly simple implementation-independent parameters:

struct CommandRunner::IRunnerImpl {
    virtual ~IRunnerImpl() = default;

    virtual void run()                    = 0;
    virtual void ensure_completed()       = 0;
    virtual std::string to_string() const = 0;

    friend class CommandRunner;
  protected:
    std::string            _working_directory;
    mylibrary::optional<mylibrary::io::time::duration> _time_constraint;
    std::string            _stdin_data;
    int                    _redirected_output_fd     = -1;
    std::string            _redirected_output_fname;
    bool                   _discard_output           = false;
    int                    _exit_code;
    std::string            _stdout_str;
    std::string            _stderr_str;
    bool                   _command_timed_out        = false;
    bool                   _sensitive_args           = false;
    string_map_t           _env;
};

The Boost RunnerImpl

The core of ensure_completed was composed using helper lambdas like this:

try {
    mylibrary::threads::safe_io_service safe_ios;
    boost::asio::io_service& ios = safe_ios;
    mylibrary::io::time::timer deadline(ios);

    bp::group process_group;

    bp::async_pipe input(ios);
    std::future<std::string> output, error;

    if (_working_directory.empty())
        _working_directory = ".";

    auto on_exit = [this, &deadline](int exit, std::error_code ec) {
        if (!_command_timed_out) {
            _exit_code = exit;
        }
        deadline.cancel();
        if (ec) s_logger.log(LOG_WARNING) << "Child process returned " << ec.message();
        else    s_logger.log(LOG_DEBUG)   << "Child process returned";
    };

    auto launcher = [](auto&&... args) { return bp::child(std::forward<decltype(args)>(args).../*, bp::posix::fd.restrict_inherit()*/); };

    auto redirect_out = [&](auto f) {
        return [&,f](auto&&... args) {
            if (_discard_output) {
                if (_redirected_output_fd != -1 && !_redirected_output_fname.empty()) {
                    s_logger.log(LOG_ERR) << "Ignoring output redirection with set_discard_output. This is a bug.";
                }
                return f(std::forward<decltype(args)>(args)..., bp::std_out > bp::null, bp::std_err > bp::null);
            }

            if (_redirected_output_fd != -1 && !_redirected_output_fname.empty()) {
                s_logger.log(LOG_WARNING) << "Conflicting output redirection, ignoring filename with descriptor";
            }

            if (_redirected_output_fd != -1) {
                return f(std::forward<decltype(args)>(args)..., bp::posix::fd.bind(1, _redirected_output_fd), bp::std_err > error);
            }

            return _redirected_output_fname.empty()
                ? f(std::forward<decltype(args)>(args)..., bp::std_out > output,                   bp::std_err > error)
                : f(std::forward<decltype(args)>(args)..., bp::std_out > _redirected_output_fname, bp::std_err > error);
        };
    };

    bp::environment bp_env = boost::this_process::environment();
    for (auto& p : _env)
        bp_env[p.first] = p.second;

    auto c = redirect_out(launcher)(_command_path, _args,
            process_group,
            bp::std_in < input,
            bp::start_dir(_working_directory),
            bp_env,
            ios, bp::on_exit(on_exit)
        );

    if (_time_constraint) {
        deadline.expires_from_now(*_time_constraint);
        deadline.async_wait([&](boost::system::error_code ec) {
            if (ec != boost::asio::error::operation_aborted) {
                if (ec) {
                    s_logger.log(LOG_WARNING) << "Unexpected condition in CommandRunner deadline: " << ec.message();
                }

                _command_timed_out = true;
                _exit_code = 1;
                ::killpg(process_group.native_handle(), SIGTERM);

                deadline.expires_from_now(3s); // grace time
                deadline.async_wait([&](boost::system::error_code ec) { if (!ec) process_group.terminate(); }); // timed out
            }
        });
    }

    boost::asio::async_write(input, bp::buffer(_stdin_data), [&input](auto ec, auto bytes_written){
        if (ec) {
            s_logger.log(LOG_WARNING) << "Standard input rejected: " << ec.message() << " after " << bytes_written << " bytes written";
        }
        may_fail([&] { input.close(); });
    });

    ios.run();

    if (output.valid()) _stdout_str = output.get();
    if (error.valid())  _stderr_str = error.get();

    // make sure no grand children survive
    if (process_group && process_group.joinable() && !process_group.wait_for(1s))
        process_group.terminate();

    // Note: even kills get the child reaped; 'on_exit' handler is
    // actually the 'on wait_pid() complete'). No need for c.wait()
    // in this scenario
    //// may_fail([&] { if (c.running()) c.wait(); }); // to avoid zombies
} catch(bp::process_error const& e) {
    if (e.code().value() != static_cast<int>(std::errc::no_child_process)) throw;
}

Full Self-Contained Listing

This compiles, but doesn't have any public interface. Merely for expositional purposes.

Note:

this didn't go into production as there were cases in which the Boost implementation would get stuck in async IO operations. The reason for this has remained unclear, but I suspect it is a hairy case of epoll is fundamentally broken related to our use cases being "wildly" multi-threaded and forking.

this does not include our attempted workarounds for safe_io_service (that guarantees fork synchronization and notifications on all active io_services)

this does not include our patch that adds restricted FD inheritance:

auto launcher = [](auto&&... args) { return
     bp::child(std::forward<decltype(args)>(args)...,
     bp::posix::fd.restrict_inherit()); };

other crucial things like on-fork handlers for global (library) state have not been shown here (they used pthread_atfork and similar)

Compiling On Coliru

#include <boost/process.hpp>
#include <boost/process/extend.hpp>
#include <boost/process/async.hpp>
#include <boost/process/posix.hpp>
#include <boost/optional.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <signal.h> // ::killpg
#include <iomanip>
#include <map>

///////
// mockups for standalone exposition
//#include "log.h"
enum LOG_LEVELS{LOG_DEBUG, LOG_WARNING, LOG_ERR};

struct DummyLogger {
    struct Tx {
        template <typename...Ts> friend Tx operator<<(Tx const&, Ts&&...) { return {}; }
    };
    Tx log(LOG_LEVELS) { return {}; }
} s_logger;

//#include "safe_io_service.h"
namespace mylibrary {
    namespace threads {
        //this did manage fork notifications
        using safe_io_service = boost::asio::io_service;
    }
    using boost::optional;
    namespace io { namespace time {
            using clock = std::chrono::high_resolution_clock;
            using duration = clock::duration;
            using timer = boost::asio::high_resolution_timer;
        }
    }
}
using namespace std::chrono_literals;

using string_vector_t = std::vector<std::string>;
using string_map_t = std::map<std::string, std::string>;

class CommandRunner {
    public: struct IRunnerImpl;
};

struct CommandRunner::IRunnerImpl {
    virtual ~IRunnerImpl() = default;

    virtual void run()                    = 0;
    virtual void ensure_completed()       = 0;
    virtual std::string to_string() const = 0;

    friend class CommandRunner;
  protected:
    std::string            _working_directory;
    mylibrary::optional<mylibrary::io::time::duration> _time_constraint;
    std::string            _stdin_data;
    int                    _redirected_output_fd     = -1;
    std::string            _redirected_output_fname;
    bool                   _discard_output           = false;
    int                    _exit_code;
    std::string            _stdout_str;
    std::string            _stderr_str;
    bool                   _command_timed_out        = false;
    bool                   _sensitive_args           = false;
    string_map_t           _env;
};

//
//////////////////////////////////////

namespace {

    namespace bp = boost::process;

    template <typename F> static auto may_fail(F&& f) {
        try {
            return std::forward<F>(f)();
        } catch(std::exception const& e) {
            s_logger.log(LOG_DEBUG) << "Ignoring non-fatal error (" << e.what() << ")";
        } catch(...) {
            s_logger.log(LOG_DEBUG) << "Ignoring non-fatal, unspecified error";
        }
    }

}

namespace mylibrary { namespace process { namespace with_boost {

    struct BoostRunnerImpl : CommandRunner::IRunnerImpl {

        BoostRunnerImpl(std::string cmd_path, string_vector_t args) :
            _command_path(std::move(cmd_path)),
            _args(std::move(args))
        {
        }

        std::string _command_path;
        string_vector_t _args;

        virtual void run() override {
            if (_completed) {
                s_logger.log(LOG_DEBUG) << "NOT running already completed command: " << *this;
                return;
            }
            ensure_completed();
        }

        ////////////////////////////
        // implementation
        virtual void ensure_completed() override {
            if (_completed) return;

            // Log command and args
            s_logger.log(LOG_DEBUG) << "Running command: " << *this;

            try {
                try {
                    mylibrary::threads::safe_io_service safe_ios;
                    boost::asio::io_service& ios = safe_ios;
                    mylibrary::io::time::timer deadline(ios);

                    bp::group process_group;

                    bp::async_pipe input(ios);
                    std::future<std::string> output, error;

                    if (_working_directory.empty())
                        _working_directory = ".";

                    auto on_exit = [this, &deadline](int exit, std::error_code ec) {
                        if (!_command_timed_out) {
                            _exit_code = exit;
                        }
                        deadline.cancel();
                        if (ec) s_logger.log(LOG_WARNING) << "Child process returned " << ec.message();
                        else    s_logger.log(LOG_DEBUG)   << "Child process returned";
                    };

                    auto launcher = [](auto&&... args) { return bp::child(std::forward<decltype(args)>(args).../*, bp::posix::fd.restrict_inherit()*/); };

                    auto redirect_out = [&](auto f) {
                        return [&,f](auto&&... args) {
                            if (_discard_output) {
                                if (_redirected_output_fd != -1 && !_redirected_output_fname.empty()) {
                                    s_logger.log(LOG_ERR) << "Ignoring output redirection with set_discard_output. This is a bug.";
                                }
                                return f(std::forward<decltype(args)>(args)..., bp::std_out > bp::null, bp::std_err > bp::null);
                            }

                            if (_redirected_output_fd != -1 && !_redirected_output_fname.empty()) {
                                s_logger.log(LOG_WARNING) << "Conflicting output redirection, ignoring filename with descriptor";
                            }

                            if (_redirected_output_fd != -1) {
                                return f(std::forward<decltype(args)>(args)..., bp::posix::fd.bind(1, _redirected_output_fd), bp::std_err > error);
                            }

                            return _redirected_output_fname.empty()
                                ? f(std::forward<decltype(args)>(args)..., bp::std_out > output,                   bp::std_err > error)
                                : f(std::forward<decltype(args)>(args)..., bp::std_out > _redirected_output_fname, bp::std_err > error);
                        };
                    };

                    bp::environment bp_env = boost::this_process::environment();
                    for (auto& p : _env)
                        bp_env[p.first] = p.second;

                    auto c = redirect_out(launcher)(_command_path, _args,
                            process_group,
                            bp::std_in < input,
                            bp::start_dir(_working_directory),
                            bp_env,
                            ios, bp::on_exit(on_exit)
                        );

                    if (_time_constraint) {
                        deadline.expires_from_now(*_time_constraint);
                        deadline.async_wait([&](boost::system::error_code ec) {
                            if (ec != boost::asio::error::operation_aborted) {
                                if (ec) {
                                    s_logger.log(LOG_WARNING) << "Unexpected condition in CommandRunner deadline: " << ec.message();
                                }

                                _command_timed_out = true;
                                _exit_code = 1;
                                ::killpg(process_group.native_handle(), SIGTERM);

                                deadline.expires_from_now(3s); // grace time
                                deadline.async_wait([&](boost::system::error_code ec) { if (!ec) process_group.terminate(); }); // timed out
                            }
                        });
                    }

                    boost::asio::async_write(input, bp::buffer(_stdin_data), [&input](auto ec, auto bytes_written){
                        if (ec) {
                            s_logger.log(LOG_WARNING) << "Standard input rejected: " << ec.message() << " after " << bytes_written << " bytes written";
                        }
                        may_fail([&] { input.close(); });
                    });

                    ios.run();

                    if (output.valid()) _stdout_str = output.get();
                    if (error.valid())  _stderr_str = error.get();

                    // make sure no grand children survive
                    if (process_group && process_group.joinable() && !process_group.wait_for(1s))
                        process_group.terminate();

                    // Note: even kills get the child reaped; 'on_exit' handler is
                    // actually the 'on wait_pid() complete'). No need for c.wait()
                    // in this scenario
                    //// may_fail([&] { if (c.running()) c.wait(); }); // to avoid zombies
                } catch(bp::process_error const& e) {
                    if (e.code().value() != static_cast<int>(std::errc::no_child_process)) throw;
                }
            } catch(std::exception const& e) {
                s_logger.log(LOG_ERR) << "CommandRunner: " << e.what();
                _completed = true;
                _exit_code = 1;
                throw;
            } catch(...) {
                s_logger.log(LOG_ERR) << "CommandRunner: unexpected error";
                _completed = true;
                _exit_code = 1;
                throw;
            }

            _completed = true;
        }

      private:
        bool _completed = false;

        friend std::ostream& operator<<(std::ostream& os, BoostRunnerImpl const& i) {
            os << i._command_path;
            if (i._sensitive_args)
                os << " (" << i._args.size() << " args)";
            else for (auto& arg : i._args)
                os << " " << std::quoted(arg);
            return os;
        }

        virtual std::string to_string() const override {
            std::ostringstream oss;
            oss << *this;
            return oss.str();
        }
    };

} } }

int main(){}


来源: stackexchange

问:
How to make repeating matrix with increasing number without loop
I am trying to make repeating matrix. And one condition is element increases in constant with every repeated step.

For example,
with [a b], I want to make multiple arrays like [a b a+D b+D a+2D b+2D a+3D b+3D] and [a b a b a+C b+C a+C b+C]. (C and D are constant)

Since eliminating for loop is essential, are there any special functions (like repmat) or tricks to make those kind of matrix?

答:
Using a combination of repmat and reshape, you can achieve it as follows:

```<code>A = [1 2];
n = 5;
D = 10;
B = reshape(repmat(A(:), 1, n) + D*(0:(n-1)), 1, [])
</code>```

pre 2016b (does not allow implicit expansion)

```<code>B = reshape(bsxfun(@plus, repmat(A(:), 1, n), D*(0:(n-1))), 1, [])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using a combination of repmat and reshape, you can achieve it as follows:

A = [1 2];
n = 5;
D = 10;
B = reshape(repmat(A(:), 1, n) + D*(0:(n-1)), 1, [])

pre 2016b (does not allow implicit expansion)

B = reshape(bsxfun(@plus, repmat(A(:), 1, n), D*(0:(n-1))), 1, [])


问:
My nav bar is covering up header
I tried to create a simple nav bar under which a welcome text as header will be available. But the nav bar is covering up the header. I tried fixing the problem by fixing the margins. But by doing that header is also moving along with the nav bar. So what should I do so that the nav bar doesn't cover up the header and remain in fixed position.

body {
  margin: 0;
  padding: 0;
  background: #2E4053;
  color: white;
  font-family: 'Raleway', sans-serif;
}

.welcome {
  height: 100px;
  margin: px; /* ? */
}

.welcome h1 {
  text-align: center;
  font-family: 'Berkshire Swash', cursive;
  color: white;
  padding: 26px;
  margin: 0 25%;
  border-bottom: 2px solid white;
}

.nav {
  height: 60px;
  width: 100%;
  background-color: lawngreen;
  position: fixed;
}

.search {
  float: right;
  margin-top: -52px;
  margin-right: 35px;
}

input {
  height: 20px;
  border-radius: 7px;
}

.nav ul {
  list-style: none;
  text-decoration: none;
}

.nav ul li a {
  text-decoration: none;
}

.nav ul li {
  display: inline-block;
  padding: 0px 20px;
  font-size: 25px;
  color: black;
  margin: 3px 50px;
  font-family: 'Boogaloo', cursive;
}

.nav ul li a:hover {
  text-decoration: line-through;
  color: blue;
  transition: 0.5s;
}

.search a i:hover {
  color: white;
  font-size: 33px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

<div class="nav">
  <ul>
    <li>About Me</li>
    <li>Contact</li>
    <li>Gallery</li>
    <li>Find Us</li>
  </ul>
  <div class="search">
    <input type="text" placeholder="Search">
    <i class="fa fa-search" style="font-
    size:30px;"></i>
  </div>
</div>

<div class="welcome">
  <h1>Welcome to My Travel Blog</h1>
</div></code>```

答:
What's happening?

When declaring position: fixed on any element you are also taking it out of the natural document flow.

So imagine a bowl of cereal, when you take a spoon full of fruit loops, the space those fruit loops occupied before is now filled up by the fruit loops around it, as though they were never there to begin with, but they are, they are just above.

How to resolve it

You need to account for the space they no longer occupy in the DOM (document object model).

This is usually done by offsetting the height of the fixed element with margin or padding properties - which ever one is more appropriate.

In your case either will work. The only reason why margin hadn't appeared to result in the expected behaviour before was due to the absence of any top property declared on your fixed element (.nav), e.g:

```<code>.nav {
  height: 60px;
  width: 100%;
  background-color: lawngreen;
  position: fixed;
  top: 0; /* for good measure */
}
</code>```

Then you can declare the appropriate margin property on the applicable element (in this case .welcome), e.g:

```<code>.welcome {
  height: 100px;
  margin-top: 60px;
}
</code>```

Code Snippet Demonstration:

body {
  margin: 0;
  padding: 0;
  background: #2E4053;
  color: white;
  font-family: 'Raleway', sans-serif;
}

.welcome {
  height: 100px;
  margin-top: 60px;
}

.welcome h1 {
  text-align: center;
  font-family: 'Berkshire Swash', cursive;
  color: white;
  padding: 26px;
  margin: 0px 25%;
  border-bottom: 2px solid white;
}

.nav {
  height: 60px;
  width: 100%;
  background-color: lawngreen;
  position: fixed;
  top: 0; /* for good measure */
}

.search {
  float: right;
  margin-top: -52px;
  margin-right: 35px;
}

input {
  height: 20px;
  border-radius: 7px;
}

.nav ul {
  list-style: none;
  text-decoration: none;
}

.nav ul li a {
  text-decoration: none;
}

.nav ul li {
  display: inline-block;
  padding: 0px 20px;
  font-size: 25px;
  color: black;
  margin: 3px 50px;
  font-family: 'Boogaloo', cursive;
}

.nav ul li a:hover {
  text-decoration: line-through;
  color: blue;
  transition: 0.5s;
}

.search a i:hover {
  color: white;
  font-size: 33px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <meta charset="UTF-8">
  <title>My Travel Blog</title>
  <link rel="stylesheet" href="home.css">
  <link href="https://fonts.googleapis.com/css?
    family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth" rel="stylesheet">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
    awesome.min.css" rel="stylesheet">
</head>

<body>
  <div class="nav">
    <ul>
      <li>About Me</li>
      <li>Contact</li>
      <li>Gallery</li>
      <li>Find Us</li>
    </ul>
    <div class="search">
      <input type="text" placeholder="Search">

      <i class="fa fa-search" style="font-
        size:30px;"></i>
    </div>
  </div>
  <div class="welcome">
    <h1>Welcome to My Travel Blog</h1>
  </div>
</body></code>```

Title: My nav bar is covering up header

Body:
I tried to create a simple nav bar under which a welcome text as header will be available. But the nav bar is covering up the header. I tried fixing the problem by fixing the margins. But by doing that header is also moving along with the nav bar. So what should I do so that the nav bar doesn't cover up the header and remain in fixed position.

body {
  margin: 0;
  padding: 0;
  background: #2E4053;
  color: white;
  font-family: 'Raleway', sans-serif;
}

.welcome {
  height: 100px;
  margin: px; /* ? */
}

.welcome h1 {
  text-align: center;
  font-family: 'Berkshire Swash', cursive;
  color: white;
  padding: 26px;
  margin: 0 25%;
  border-bottom: 2px solid white;
}

.nav {
  height: 60px;
  width: 100%;
  background-color: lawngreen;
  position: fixed;
}

.search {
  float: right;
  margin-top: -52px;
  margin-right: 35px;
}

input {
  height: 20px;
  border-radius: 7px;
}

.nav ul {
  list-style: none;
  text-decoration: none;
}

.nav ul li a {
  text-decoration: none;
}

.nav ul li {
  display: inline-block;
  padding: 0px 20px;
  font-size: 25px;
  color: black;
  margin: 3px 50px;
  font-family: 'Boogaloo', cursive;
}

.nav ul li a:hover {
  text-decoration: line-through;
  color: blue;
  transition: 0.5s;
}

.search a i:hover {
  color: white;
  font-size: 33px;
}

<link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

About Me

Contact

Gallery

Find Us

    <input type="text" placeholder="Search">

Welcome to My Travel Blog

Body:
What's happening?

When declaring position: fixed on any element you are also taking it out of the natural document flow.

So imagine a bowl of cereal, when you take a spoon full of fruit loops, the space those fruit loops occupied before is now filled up by the fruit loops around it, as though they were never there to begin with, but they are, they are just above.

How to resolve it

You need to account for the space they no longer occupy in the DOM (document object model).

This is usually done by offsetting the height of the fixed element with margin or padding properties - which ever one is more appropriate.

In your case either will work. The only reason why margin hadn't appeared to result in the expected behaviour before was due to the absence of any top property declared on your fixed element (.nav), e.g:

.nav {
  height: 60px;
  width: 100%;
  background-color: lawngreen;
  position: fixed;
  top: 0; /* for good measure */
}

Then you can declare the appropriate margin property on the applicable element (in this case .welcome), e.g:

.welcome {
  height: 100px;
  margin-top: 60px;
}

Code Snippet Demonstration:

body {
  margin: 0;
  padding: 0;
  background: #2E4053;
  color: white;
  font-family: 'Raleway', sans-serif;
}

.welcome {
  height: 100px;
  margin-top: 60px;
}

.welcome h1 {
  text-align: center;
  font-family: 'Berkshire Swash', cursive;
  color: white;
  padding: 26px;
  margin: 0px 25%;
  border-bottom: 2px solid white;
}

.nav {
  height: 60px;
  width: 100%;
  background-color: lawngreen;
  position: fixed;
  top: 0; /* for good measure */
}

.search {
  float: right;
  margin-top: -52px;
  margin-right: 35px;
}

input {
  height: 20px;
  border-radius: 7px;
}

.nav ul {
  list-style: none;
  text-decoration: none;
}

.nav ul li a {
  text-decoration: none;
}

.nav ul li {
  display: inline-block;
  padding: 0px 20px;
  font-size: 25px;
  color: black;
  margin: 3px 50px;
  font-family: 'Boogaloo', cursive;
}

.nav ul li a:hover {
  text-decoration: line-through;
  color: blue;
  transition: 0.5s;
}

.search a i:hover {
  color: white;
  font-size: 33px;
}

<head>
  <meta charset="UTF-8">
  <title>My Travel Blog</title>
  <link rel="stylesheet" href="home.css">
  <link href="https://fonts.googleapis.com/css?
    family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth" rel="stylesheet">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
    awesome.min.css" rel="stylesheet">
</head>

<body>
  <div class="nav">
    <ul>
      <li><a href="#me">About Me</a></li>
      <li><a href="#contact">Contact</a></li>
      <li><a href="#gallery">Gallery</a></li>
      <li><a href="#find">Find Us</a></li>
    </ul>
    <div class="search">
      <input type="text" placeholder="Search">

      <a href="https://google.com"><i class="fa fa-search" style="font-
        size:30px;"></i></a>
    </div>
  </div>
  <div class="welcome">
    <h1>Welcome to My Travel Blog</h1>
  </div>
</body>


问:
changed my wordpress url from http to https and now admin panel is not working
i changed the URL from HTTP to HTTP'S and the moment i did it my admin panel stopped working add the line in WP-config site URL and all but still not working
now i don't what do please help me out</p>

答:
This is not something you should fix in the functions.php. I strongly suggest that you use the following:

Go to your phpmyadmin, mysql workbench or a equivalent control panel where       you can edit your database.

Go to your wordpress database

Go to the wp_options table

Change the siteurl and home record back to a working url

Save your changes

This way you are 99.9% sure that the changes are commited.

If you do not have access to the control panel, you can use the functions.php equivalent as sintakonte suggested, or ask your database administrator.

Be sure to check if the record has updated in the database.


问:
XAML WebBrowser emulation without registry change
I am trying to render some HTML page of mine hosted on a NodeJS in a WPF app.

I have tried few things and the following option seems the most convenient:
C# webbrowser Ajax call

However it is modifying the registry which I cannot (company policy).

Therefore would there be a way to do the same on the fly? ie. load the WebBrowser with this setup without updating the registry?

Thank you

答:
Therefore would there be a way to do the same on the fly? ie. load the WebBrowser with this setup without updating the registry?

I am afraid not. There is no property or method of the WebBrowser control itself that you can set or call.

Changing the registry keys or use another (third-party) control are your only options I would say.


问:
C# - SQLite Storing small amount of data constantly
My Setup:

Multi-Threaded application using Parallel.ForEach set to 40 threads.

Adds the index of the foreach into a concurrentbag each loop.

Once its added to the bag, it string.joins() them with , and sends it to SQLite Table.
(It does around 14 loops/sec, sometimes more).

It works, but the CPU is unbearable. Spikes to 80-90 then goes to 10~ then back and loop. The moment I remove the .CommandText and .ExeecuteNonQueryAsync it barely goes past 4%.

Screenshot of the CPU Usage Debug Window:

Why I do the setup above is to store the checked indexes of each loop on a hashset so that when I close, reopen and restart that loop, it knows what indexes I have already looped so that I can remove them from the hashset and continue looping without those indexes.

Is there a better way of doing what I am doing?

The code I am executing in the ForEach:

```<code>looper_checkedIndexes.Add(Index);
using (SQLiteCommand command = sqldb.CreateCommand()) {
    command.CommandText = "UPDATE `timeMachine` SET `indexes`='" + string.Join(",", looper_checkedIndexes) + "' WHERE `config`='" + General["name"].ToString().Replace("'", "\\'") + "'";
    command.ExecuteNonQueryAsync();
}
</code>```

答: The best way to speed up many small writes is to combine them into a single transaction, and/or to use WAL mode.</p>

ContentLicense: CC BY-SA 4.0

Body:
My Setup:

Multi-Threaded application using Parallel.ForEach set to 40 threads.

Adds the index of the foreach into a concurrentbag each loop.

Once its added to the bag, it string.joins() them with , and sends it to SQLite Table.
(It does around 14 loops/sec, sometimes more).

It works, but the CPU is unbearable. Spikes to 80-90 then goes to 10~ then back and loop. The moment I remove the .CommandText and .ExeecuteNonQueryAsync it barely goes past 4%.

Screenshot of the CPU Usage Debug Window:

Why I do the setup above is to store the checked indexes of each loop on a hashset so that when I close, reopen and restart that loop, it knows what indexes I have already looped so that I can remove them from the hashset and continue looping without those indexes.

Is there a better way of doing what I am doing?

The code I am executing in the ForEach:

looper_checkedIndexes.Add(Index);
using (SQLiteCommand command = sqldb.CreateCommand()) {
    command.CommandText = "UPDATE `timeMachine` SET `indexes`='" + string.Join(",", looper_checkedIndexes) + "' WHERE `config`='" + General["name"].ToString().Replace("'", "\\'") + "'";
    command.ExecuteNonQueryAsync();
}


问:
Buttons activate/deactivate elements in list (complex case)
I've been trying as hard as I can but I think I'm over my head on this one, I just don't have the jQuery knowledge to accomplish what I need, I'm pretty new as you will see.

This may be a complex case, so I will try to explain as good as I can:

I have a list of items, LIs, grouped by titles in an accordion, so when you expand/collapse a section, you see the corresponding list for that section.

Each section contains the list and at the bottom of the list are two buttons: Clear Selected and Select All.

Upon entering the page, the first accordion section is expanded, inside you'll see the list, and at the bottom of the list you see the Clear Selected and Select All buttons. The Clear Selected button is visible but 'inactive'. To create the 'inactive' effect I just used opacity:.5; in the CSS. I need this button visible when it's 'inactive',

So far, I've been able to have the "Select All" button change its class, but the rest of the cases and behaviors are too complex for me.

The interaction between the buttons and the elements on the list, and between the buttons themselves is what I need help with.

Just FYI, what I'm building is a results system in which you can filter those results by clicking on the elements/options inside the accordions.

Here's a DEMO.

Any help on this it's greatly appreciated.

Thanks,

EDIT--

Read the comments in the JavaScript section of the DEMO to know the functionalities that are needed.

答:
I think I have most of you're asking for worked out. Take a look at my code and see if it's what you're wanting.
http://www.jsfiddle.net/lmcculley/ujuH6/10/
Hope it works!</p>

ContentLicense: CC BY-SA 2.5


问:
Opencv only process the parts of image
I want to make a negative transformation for the image which is a very simple program.

But when I run the program. I want to transform all of the pixels in the image, but only 1/3 parts of that are processed. I don't make sure where is wrong. all the code I followed the book. But the result is different.

I think there is something wrong about the columns, but when I change the value of I.cols in negativeImage function with the actual value of image. the output still keep the same. only 1/3 parts of image are processed. If I 3 times the I.cols all of the pixels in the iamge could be processed.

```<code>vector<uchar> getNegativeLUT() {
vector<uchar> LUT(256, 0);
for (int i = 0; i < 256; ++i)
    LUT[i] = (uchar)(255 - i);
return LUT;
}

void negativeImage(Mat& I) {
vector<uchar> LUT = getNegativeLUT();
for (int i = 0; i < I.rows; ++i) {
    for (int j = 0; j <  I.cols; ++j) {
        I.at<uchar>(i, j) = LUT[I.at<uchar>(i, j)];
        //stack overflow
    }
  }
}

int main() {
Mat image = imread("1.png");
Mat processed_image2 = image.clone();
negativeImage(processed_image2);
printf("%d", image.cols);

imshow("Input Image", image);
imshow("Negative Image", processed_image2);
waitKey(0);

return 0;
}
</code>```

Output Image

答:
You need to put correct type with at<> operator. Your PNG image has to be converted to 8UC1 to then use uchar type to access each pixel. I suppose your image has 3 channels, so you only iterate over 1/3 of the image. Also, I suggest you to use ptr<> operator in rows loop and then access to pixel as an array.

```<code>Mat M;
cvtColor(I, M, CV_BGR2GRAY);

// M is CV_8UC1 type
for(int i = 0; i < M.rows; i++)
{
    uchar* p  = M.ptr<uchar>(i);
    for(int j = 0; j < I.cols; j++)
    {
        p[j] = LUT[p[j]];
    }
}
</code>```

EDIT: you should use cv::LUT instead of doing it yourself.

```<code>cv::Mat lut(1, 256, CV_8UC1);
for( int i = 0; i < 256; ++i)
{
    lut.at<uchar>(0,i) = uchar(255-i);
}
cv::LUT(M, lut, result);
</code>```

Title: Opencv only process the parts of image

Body:
I want to make a negative transformation for the image which is a very simple program.

But when I run the program. I want to transform all of the pixels in the image, but only 1/3 parts of that are processed. I don't make sure where is wrong. all the code I followed the book. But the result is different.

I think there is something wrong about the columns, but when I change the value of I.cols in negativeImage function with the actual value of image. the output still keep the same. only 1/3 parts of image are processed. If I 3 times the I.cols all of the pixels in the iamge could be processed.

vector<uchar> getNegativeLUT() {
vector<uchar> LUT(256, 0);
for (int i = 0; i < 256; ++i)
    LUT[i] = (uchar)(255 - i);
return LUT;
}

void negativeImage(Mat& I) {
vector<uchar> LUT = getNegativeLUT();
for (int i = 0; i < I.rows; ++i) {
    for (int j = 0; j <  I.cols; ++j) {
        I.at<uchar>(i, j) = LUT[I.at<uchar>(i, j)];
        //stack overflow
    }
  }
}

int main() {
Mat image = imread("1.png");
Mat processed_image2 = image.clone();
negativeImage(processed_image2);
printf("%d", image.cols);

imshow("Input Image", image);
imshow("Negative Image", processed_image2);
waitKey(0);

return 0;
}

Output Image

Body:
You need to put correct type with at<> operator. Your PNG image has to be converted to 8UC1 to then use uchar type to access each pixel. I suppose your image has 3 channels, so you only iterate over 1/3 of the image. Also, I suggest you to use ptr<> operator in rows loop and then access to pixel as an array.

Mat M;
cvtColor(I, M, CV_BGR2GRAY);

// M is CV_8UC1 type
for(int i = 0; i < M.rows; i++)
{
    uchar* p  = M.ptr<uchar>(i);
    for(int j = 0; j < I.cols; j++)
    {
        p[j] = LUT[p[j]];
    }
}

EDIT: you should use cv::LUT instead of doing it yourself.

cv::Mat lut(1, 256, CV_8UC1);
for( int i = 0; i < 256; ++i)
{
    lut.at<uchar>(0,i) = uchar(255-i);
}
cv::LUT(M, lut, result);


问:
Codeigniter3: How to check database record existance in a folder or directory?
I want to compare database record with a folder or directory in Codeigniter, so I can check whether the record id from database exists in folder or directory of codeingiter.
Please help!</p>

答:
Using these code you will get the directory listing:

```<code>function getDir($dir_path='*'){
          $dirs = array_filter(glob($dir_path), 'is_dir');
            $directory = array();
            foreach ($dirs as $item => $key ) {
                array_push($directory, $key);
            }
            return $directory;
    }
</code>```

Note: Make sure that you function getDir() is a Helper function

call function getDir() in your controller

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends Admin_Controller{
    public function __construct() {
        parent :: __construct();
        $this->load->model('database_model_name');
    }

    public function index() {

        $dir_array=getDir(); //only directory listing make it recursive to get folder details
        $db_dir_array = $this->database_model_name->getDir();

        // Compare both the array and do whatever you want to

    }
}
?>
</code>```

May be it will help you .

Body:
Using these code you will get the directory listing:

function getDir($dir_path='*'){
          $dirs = array_filter(glob($dir_path), 'is_dir');
            $directory = array();
            foreach ($dirs as $item => $key ) {
                array_push($directory, $key);
            }
            return $directory;
    }

Note: Make sure that you function getDir() is a Helper function

call function getDir() in your controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends Admin_Controller{
    public function __construct() {
        parent :: __construct();
        $this->load->model('database_model_name');
    }

    public function index() {

        $dir_array=getDir(); //only directory listing make it recursive to get folder details
        $db_dir_array = $this->database_model_name->getDir();

        // Compare both the array and do whatever you want to

    }
}
?>

May be it will help you .


问:
Create button OnClientClick asp net
I'm creating button from code c#:

```<code>        Button btnAddCalculation = new Button();
        btnAddCalculation.ID = "btnAddCalculation";
        btnAddCalculation.Text = "Add count";
        btnAddCalculation.SkinID = "middleButton";
        btnAddCalculation.Visible = true;

        string sPath = String.Format(
            "WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
            SessionViewstateConstants.CalculationType,
            CalcType.New,
            Guid.NewGuid(),
            oEditedDocument.Id.ToString()
        );
        //          btnAddCalculation.Attributes.Add("onclick", @"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
        btnAddCalculation.Click += new EventHandler(btnClick_cl);
        btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";

    public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
    {
        return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
    }
</code>```

but in the client side the function OnClientClick does not work, when I click
nothing happens. What Did I do wrong???

Generated HTML:

```<code><input type="submit" name="ctl00$ctl00$Main$EditorMain$tabTabContainer$ctl00$Attr433$btnAddCalculation"
value="Add count"
id="ctl00_ctl00_Main_EditorMain_tabTabContainer_ctl00_Attr433_btnAddCalculation"
disabled="disabled" class="blue_button" />
</code>```

答:
For Button being disabled

If the dynamic button is added to a container that is itself disabled, then this dynamic button will also be disabled. To make this sure that button is added properly, use a new container in HTML (e.g. <asp:PlaceHolder>)  and add button to that container from codebehind.

Also good to check following :-

When Creating the new button, use CausesValidation = false. This will avoid any RequiredFieldValidator getting fired when this button is clicked. RequiredFieldValidator also stops button from being clicked.
e.g.

```<code>Button btnAddCalculation = new Button();
btnAddCalculation.ID = "btnAddCalculation";
btnAddCalculation.Text = "Add count";
btnAddCalculation.SkinID = "middleButton";
btnAddCalculation.Visible = true;
btnAddCalculation.Enabled = true;
btnAddCalculation.CausesValidation = false;
</code>```

Title: Create button OnClientClick asp net

Body:
I'm creating button from code c#:

        Button btnAddCalculation = new Button();
        btnAddCalculation.ID = "btnAddCalculation";
        btnAddCalculation.Text = "Add count";
        btnAddCalculation.SkinID = "middleButton";
        btnAddCalculation.Visible = true;

        string sPath = String.Format(
            "WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
            SessionViewstateConstants.CalculationType,
            CalcType.New,
            Guid.NewGuid(),
            oEditedDocument.Id.ToString()
        );
        //          btnAddCalculation.Attributes.Add("onclick", @"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
        btnAddCalculation.Click += new EventHandler(btnClick_cl);
        btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";

    public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
    {
        return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
    }

but in the client side the function OnClientClick does not work, when I click
nothing happens. What Did I do wrong???

Generated HTML:

<input type="submit" name="ctl00$ctl00$Main$EditorMain$tabTabContainer$ctl00$Attr433$btnAddCalculation"
value="Add count"
id="ctl00_ctl00_Main_EditorMain_tabTabContainer_ctl00_Attr433_btnAddCalculation"
disabled="disabled" class="blue_button" />

Body:
For Button being disabled

If the dynamic button is added to a container that is itself disabled, then this dynamic button will also be disabled. To make this sure that button is added properly, use a new container in HTML (e.g. <asp:PlaceHolder>)  and add button to that container from codebehind.

Also good to check following :-

When Creating the new button, use CausesValidation = false. This will avoid any RequiredFieldValidator getting fired when this button is clicked. RequiredFieldValidator also stops button from being clicked.
e.g.

Button btnAddCalculation = new Button();
btnAddCalculation.ID = "btnAddCalculation";
btnAddCalculation.Text = "Add count";
btnAddCalculation.SkinID = "middleButton";
btnAddCalculation.Visible = true;
btnAddCalculation.Enabled = true;
btnAddCalculation.CausesValidation = false;


问:
How to map a column to JSONB instead of JSON, with Doctrine and Postgresql?
In my project I'm using Doctrine doctrine 2.5.4/postgres 9.5. I'm trying to add a jsonb field using YAML:

```<code>fields:
  obj: json_array
</code>```

This gets interpreted as a json column type (and not jsonb).  The specification notes about picking up json or jsonb:

Chosen if the column definition contains the jsonb option inside the platformOptions attribute array and is set to true.

But platformOptions doesn't seem to work (tried to add it below obj, at the top... with no success). How can I add a jsonb field?

答:
This is supported by doctrine/dbal v2.6+ (it requires PHP 7.1). All you need to do is use json_array and set options={"jsonb"=true} I tested this on doctrine/dbal v2.6.3

This is what it looks like in PHP format:

/**
 * @ORM\Column(type="json_array",nullable=true,options={"jsonb"=true})
 */
  private $details;
```
<p>and it creates a query such as (for an existing table):</p>
<pre class="lang-sql prettyprint-override"><code>ALTER TABLE mytable ADD details JSONB NOT NULL;
</code>```

More details about type mapping can be found at Doctrine mapping matrix.

Body:
In my project I'm using Doctrine doctrine 2.5.4/postgres 9.5. I'm trying to add a jsonb field using YAML:

fields:
  obj: json_array

This gets interpreted as a json column type (and not jsonb).  The specification notes about picking up json or jsonb:

Chosen if the column definition contains the jsonb option inside the platformOptions attribute array and is set to true.

But platformOptions doesn't seem to work (tried to add it below obj, at the top... with no success). How can I add a jsonb field?

Body:
This is supported by doctrine/dbal v2.6+ (it requires PHP 7.1). All you need to do is use json_array and set options={"jsonb"=true} I tested this on doctrine/dbal v2.6.3

This is what it looks like in PHP format:

/**
 * @ORM\Column(type="json_array",nullable=true,options={"jsonb"=true})
 */
  private $details;

and it creates a query such as (for an existing table):

ALTER TABLE mytable ADD details JSONB NOT NULL;

More details about type mapping can be found at Doctrine mapping matrix.


问:
Why is "this" bound different in some instances, but the same in others in React?
In this component, I'm not able to call a function in the render method by going this.functionName if it's not an arrow function. Howevever, I am able to call this.setState effectively in both an arrow function and a regular function. Why is "this" different in some situations, but seemingly the same in other situations in a React component like this?</p>

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

class Address extends React.Component {

state = {
    fullAddress: "5001"
}

componentDidMount() {
    this.setState({
        fullAddress: "hello"
    })
}

hello = () => {
    this.setState({
        fullAddress: "hello1"
    })
}

logMessage() {
    console.log(this.state.fullAddress);
}

 render() {
   return (
     <div className="address">
       {this.state.fullAddress}
       <input type="button" value="Log" onClick={this.hello} />
     </div>
   );
 }
}

export default Address;
</code>```

答:
In your example, logMessage will probably break since you need to specify your this context to it.

In this case, simply bind it in Address's  constructor like so:

```<code>class Address extends Component {
  constructor(props) {
    super(props)

    this.logMessage = this.logMessage.bind(this)
  }
}
</code>```

A second approach would be the same you already used with hello as arrow function like. Arrow functions keep your current context (this) and that's why you have access to this.setState inside hello's body for example.

Body:
In this component, I'm not able to call a function in the render method by going this.functionName if it's not an arrow function. Howevever, I am able to call this.setState effectively in both an arrow function and a regular function. Why is "this" different in some situations, but seemingly the same in other situations in a React component like this?

import React from 'react';

class Address extends React.Component {

state = {
    fullAddress: "5001"
}

componentDidMount() {
    this.setState({
        fullAddress: "hello"
    })
}

hello = () => {
    this.setState({
        fullAddress: "hello1"
    })
}

logMessage() {
    console.log(this.state.fullAddress);
}

 render() {
   return (

       {this.state.fullAddress}
       <input type="button" value="Log" onClick={this.hello} />

   );
 }
}

export default Address;

Body:
In your example, logMessage will probably break since you need to specify your this context to it.

In this case, simply bind it in Address's  constructor like so:

class Address extends Component {
  constructor(props) {
    super(props)

    this.logMessage = this.logMessage.bind(this)
  }
}

A second approach would be the same you already used with hello as arrow function like. Arrow functions keep your current context (this) and that's why you have access to this.setState inside hello's body for example.


问:
own len function with recursion in Go
I'm trying to build simple function to count elements in slice (like len) It must be simple (without additional libs) and with recursion. The problem is when i try to check is slice is empty (is nul).

```<code>package main
import "fmt"

func main() {
  x := []int{1, 2, 3}
  fmt.Println(len2(x))
}
func len2(s []int) int {
  if s == nil {
    return 0
  }
  return 1 + len2(s[1:])
}
</code>```

the result it should be in this example '3'.

It's broken in if s == nil:

```<code>panic: runtime error: slice bounds out of range
</code>```

答:
It panics because you have no valid termination condition.

When your len2() is called with a non-nil empty slice, it attempts to slice it like s[1:], which will be a runtime panic.

Instead of checking for nil slice, check if the slice is empty by comparing its length to 0:

```<code>func len2(s []int) int {
    if len(s) == 0 {
        return 0
    }
    return 1 + len2(s[1:])
}
</code>```

Try it on the Go Playground.

If you can't use the builtin len() function (which you already did in your solution), you may use the for ... range:

```<code>func len2(s []int) int {
    size := 0
    for i := range s {
        size = i + 1
    }
    return size
}
</code>```

Try this on the Go Playground.

And if it must be recursive, then for example:

```<code>func len2(s []int) int {
    size := 0
    for range s {
        size = 1 + len2(s[1:])
        break
    }
    return size
}
</code>```

Try this on the Go Playground.

But know that these are awful solutions compared to using the builtin len().

Title: own len function with recursion in Go

Body:
I'm trying to build simple function to count elements in slice (like len) It must be simple (without additional libs) and with recursion. The problem is when i try to check is slice is empty (is nul).

package main
import "fmt"

func main() {
  x := []int{1, 2, 3}
  fmt.Println(len2(x))
}
func len2(s []int) int {
  if s == nil {
    return 0
  }
  return 1 + len2(s[1:])
}

the result it should be in this example '3'.

It's broken in if s == nil:

panic: runtime error: slice bounds out of range

Body:
It panics because you have no valid termination condition.

When your len2() is called with a non-nil empty slice, it attempts to slice it like s[1:], which will be a runtime panic.

Instead of checking for nil slice, check if the slice is empty by comparing its length to 0:

func len2(s []int) int {
    if len(s) == 0 {
        return 0
    }
    return 1 + len2(s[1:])
}

Try it on the Go Playground.

If you can't use the builtin len() function (which you already did in your solution), you may use the for ... range:

func len2(s []int) int {
    size := 0
    for i := range s {
        size = i + 1
    }
    return size
}

Try this on the Go Playground.

And if it must be recursive, then for example:

func len2(s []int) int {
    size := 0
    for range s {
        size = 1 + len2(s[1:])
        break
    }
    return size
}

Try this on the Go Playground.

But know that these are awful solutions compared to using the builtin len().


问:
Programmatically format the java code using java
I would like to format strings which contains codes like:

```<code> "function() { for(i=0;i<n;i++){ return i; }}"
</code>```

The point is to put new lines to each ; except in the for loop, so the formatted output should be something like this:

```<code>function() {
   for(i=0;i<n;i++){
    return i;
  }
 }
</code>```

Is there any written function for this, or I have to loop through the whole string?

答:
You have to use google-java-format-1.5.jar and google-java-format-1.5-all-deps.jar

and see the below example code

```<code>public class Main {
   public static void main(String[] args) {
      Formatter formatter = new Formatter();
      try {
        System.out.println(formatter.formatSource("public class Test{public static void main(String[] args) {String s;}}"));
      } catch (FormatterException e) {
        e.printStackTrace();
    }
 }

}
</code>```

and output will be

```<code>public class Test {
  public static void main(String[] args) {
     String s;
  }
}
</code>```

Sample working code

Hope this would helps to you

Body:
I would like to format strings which contains codes like:

 "function() { for(i=0;i<n;i++){ return i; }}"

The point is to put new lines to each ; except in the for loop, so the formatted output should be something like this:

function() {
   for(i=0;i<n;i++){
    return i;
  }
 }

Is there any written function for this, or I have to loop through the whole string?

Body:
You have to use google-java-format-1.5.jar and google-java-format-1.5-all-deps.jar

and see the below example code

public class Main {
   public static void main(String[] args) {
      Formatter formatter = new Formatter();
      try {
        System.out.println(formatter.formatSource("public class Test{public static void main(String[] args) {String s;}}"));
      } catch (FormatterException e) {
        e.printStackTrace();
    }
 }

}

and output will be

public class Test {
  public static void main(String[] args) {
     String s;
  }
}

Sample working code

Hope this would helps to you


问:
c# Serialize a ObservableCollection ignoring a property
I am developing an UWP app using the Creators Update SDK.
I am trying to serialize a ObservableCollection ignoring a property of their class.

Here is my code, it have my class and the methods to serialize, you can see I am using  [DataContract] and [IgnoreDataMember] but it's not working.

```<code>public class Classes
    {
        [DataContract]
        public class Car : BindableBase
        {
            [DataMember]
            private string _Name;
            public string Name
            {
                get { return _Name; }
                set { Set(ref _Name, value); }
            }

            [DataMember]
            private string _Brand;
            public string Brand
            {
                get { return _Brand; }
                set { Set(ref _Brand, value); }
            }

            [IgnoreDataMember]
            private bool _Electric;
            public bool Electric
            {
                get { return _Electric; }
                set { Set(ref _Electric, value); }
            }

            [DataMember]
            private double _Price;
            public double Price
            {
                get { return _Price; }
                set { Set(ref _Price, value); }
            }
        }

        public class Values_Car : ObservableCollection<Car> { }

        public static class Garage
        {
            public static Values_Car Cars = new Values_Car();

            static Garage()
            {
            }
        }

        [XmlRoot("Root")]
        public class GarageDTO
        {
            [XmlElement]
            public Values_Car Cars { get { return Garage.Cars; } }
        }
    }

   public class NewSerialization
    {
        private static void FillList()
        {
            Car e_1 = new Car()
            {
                Name = "element_Name",
                Brand = "element_Brand",
                Electric = true,
                Price = 1,
            };
            Car e_2 = new Car()
            {
                Name = "element_Name",
                Brand = "element_Brand",
                Electric = true,
                Price = 2,
            };

            Garage.Cars.Add(e_1);
            Garage.Cars.Add(e_2);
        }

        public static string Serializer()
        {
            FillList();

            var _Instance = new GarageDTO();

            var serializer = new XmlSerializer(typeof(GarageDTO));

            using (var stream_original = new MemoryStream())
            {
                serializer.Serialize(stream_original, _Instance);

                string string_original = string.Empty;

                stream_original.Position = 0;

                using (StreamReader reader = new StreamReader(stream_original, Encoding.Unicode))
                {
                    string_original = reader.ReadToEnd();
                }

                return string_original;
            }
        }
    }
</code>```

using NewSerialization.Serializer(); I got:
But in the xml I got the Electric property which is ignored.

```<code><?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Cars>
    <Name>element_Name</Name>
    <Brand>element_Brand</Brand>
    <Electric>true</Electric>
    <Price>1</Price>
  </Cars>
  <Cars>
    <Name>element_Name</Name>
    <Brand>element_Brand</Brand>
    <Electric>true</Electric>
    <Price>2</Price>
  </Cars>
</Root>
</code>```

How I can  ignoring a property of my  ObservableCollection on serialization?

Appreciate your help.

答:
Thanks to the comments of @dbc and @Aluan Haddad I found the exact I was finding, this should be my class to achieve that:</p>

```<code>public class Car : BindableBase
        {
            private string _Name;
            public string Name
            {
                get { return _Name; }
                set { Set(ref _Name, value); }
            }

            private string _Brand;
            public string Brand
            {
                get { return _Brand; }
                set { Set(ref _Brand, value); }
            }

            private bool _Electric;
            [XmlIgnore] //<----This!
            public bool Electric
            {
                get { return _Electric; }
                set { Set(ref _Electric, value); }
            }

            private double _Price;
            public double Price
            {
                get { return _Price; }
                set { Set(ref _Price, value); }
            }
        }
</code>```

Body:
I am developing an UWP app using the Creators Update SDK.
I am trying to serialize a ObservableCollection ignoring a property of their class.

Here is my code, it have my class and the methods to serialize, you can see I am using  [DataContract] and [IgnoreDataMember] but it's not working.

public class Classes
    {
        [DataContract]
        public class Car : BindableBase
        {
            [DataMember]
            private string _Name;
            public string Name
            {
                get { return _Name; }
                set { Set(ref _Name, value); }
            }

            [DataMember]
            private string _Brand;
            public string Brand
            {
                get { return _Brand; }
                set { Set(ref _Brand, value); }
            }

            [IgnoreDataMember]
            private bool _Electric;
            public bool Electric
            {
                get { return _Electric; }
                set { Set(ref _Electric, value); }
            }

            [DataMember]
            private double _Price;
            public double Price
            {
                get { return _Price; }
                set { Set(ref _Price, value); }
            }
        }

        public class Values_Car : ObservableCollection<Car> { }

        public static class Garage
        {
            public static Values_Car Cars = new Values_Car();

            static Garage()
            {
            }
        }

        [XmlRoot("Root")]
        public class GarageDTO
        {
            [XmlElement]
            public Values_Car Cars { get { return Garage.Cars; } }
        }
    }

   public class NewSerialization
    {
        private static void FillList()
        {
            Car e_1 = new Car()
            {
                Name = "element_Name",
                Brand = "element_Brand",
                Electric = true,
                Price = 1,
            };
            Car e_2 = new Car()
            {
                Name = "element_Name",
                Brand = "element_Brand",
                Electric = true,
                Price = 2,
            };

            Garage.Cars.Add(e_1);
            Garage.Cars.Add(e_2);
        }

        public static string Serializer()
        {
            FillList();

            var _Instance = new GarageDTO();

            var serializer = new XmlSerializer(typeof(GarageDTO));

            using (var stream_original = new MemoryStream())
            {
                serializer.Serialize(stream_original, _Instance);

                string string_original = string.Empty;

                stream_original.Position = 0;

                using (StreamReader reader = new StreamReader(stream_original, Encoding.Unicode))
                {
                    string_original = reader.ReadToEnd();
                }

                return string_original;
            }
        }
    }

using NewSerialization.Serializer(); I got:
But in the xml I got the Electric property which is ignored.

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Cars>
    <Name>element_Name</Name>
    <Brand>element_Brand</Brand>
    <Electric>true</Electric>
    <Price>1</Price>
  </Cars>
  <Cars>
    <Name>element_Name</Name>
    <Brand>element_Brand</Brand>
    <Electric>true</Electric>
    <Price>2</Price>
  </Cars>
</Root>

How I can  ignoring a property of my  ObservableCollection on serialization?

Appreciate your help.

Body:
Thanks to the comments of @dbc and @Aluan Haddad I found the exact I was finding, this should be my class to achieve that:

public class Car : BindableBase
        {
            private string _Name;
            public string Name
            {
                get { return _Name; }
                set { Set(ref _Name, value); }
            }

            private string _Brand;
            public string Brand
            {
                get { return _Brand; }
                set { Set(ref _Brand, value); }
            }

            private bool _Electric;
            [XmlIgnore] //<----This!
            public bool Electric
            {
                get { return _Electric; }
                set { Set(ref _Electric, value); }
            }

            private double _Price;
            public double Price
            {
                get { return _Price; }
                set { Set(ref _Price, value); }
            }
        }


问:
Getting Uncaught TypeError: Cannot read property 'substring' of undefined
```<code>   (function( $ ) {
     $(document).ready( function(){
       $('form.wpcf7-form input').each(function(){
         //or you could also do this which is even less maintenance
         var name = $(this).attr('name').substring(0, 10);
         var type = $(this).attr('type');
         switch(type){
           case 'radio':
            case 'checkbox':
             name += '-'+$(this).attr('value');
         }
         $(this).attr('class',name);
       });
     });
   })( jQuery );
</code>```

I try to cut the class name but I am getting Uncaught TypeError: Cannot read property 'substring' of undefined error.

Can some one help me get this error fixed?

Thanks!

答:
As this is WordPress, and Contact Form 7, I figure some of the HTML is out of your control.

Adding a class based on the name would give the impression you want to do some styling against those inputs.  Did you know you can style based on the name, without adding classes?  For example, for a text input named "first-name", you could do this in your CSS:

```<code>input[type="radio"][name="first-name"] {
    border-color: red;
}
</code>```

If that's doesn't satisfy your needs (and to answer the direct question you asked) then you'd need to do a conditional so that you don't throw this error:

```<code>// simplify to a single no-conflict safe document-ready
jQuery( function( $ ) {
    $('form.wpcf7-form input').each( function() {
        if ( $(this).attr('name') ) {
             var name = $(this).attr('name').substring(0, 10);
             var type = $(this).attr('type');
             switch(type) {
                 case 'radio':
                 case 'checkbox':
                     name += '-'+$(this).attr('value');
             }

             $(this).attr('class',name);
        }
    } );
} );
</code>```

Body:
   (function( $ ) {
     $(document).ready( function(){
       $('form.wpcf7-form input').each(function(){
         //or you could also do this which is even less maintenance
         var name = $(this).attr('name').substring(0, 10);
         var type = $(this).attr('type');
         switch(type){
           case 'radio':
            case 'checkbox':
             name += '-'+$(this).attr('value');
         }
         $(this).attr('class',name);
       });
     });
   })( jQuery );

I try to cut the class name but I am getting Uncaught TypeError: Cannot read property 'substring' of undefined error.

Can some one help me get this error fixed?

Thanks!

Body:
As this is WordPress, and Contact Form 7, I figure some of the HTML is out of your control.

Adding a class based on the name would give the impression you want to do some styling against those inputs.  Did you know you can style based on the name, without adding classes?  For example, for a text input named "first-name", you could do this in your CSS:

input[type="radio"][name="first-name"] {
    border-color: red;
}

If that's doesn't satisfy your needs (and to answer the direct question you asked) then you'd need to do a conditional so that you don't throw this error:

// simplify to a single no-conflict safe document-ready
jQuery( function( $ ) {
    $('form.wpcf7-form input').each( function() {
        if ( $(this).attr('name') ) {
             var name = $(this).attr('name').substring(0, 10);
             var type = $(this).attr('type');
             switch(type) {
                 case 'radio':
                 case 'checkbox':
                     name += '-'+$(this).attr('value');
             }

             $(this).attr('class',name);
        }
    } );
} );


问:
Avoiding and renaming .x and .y columns when merging or joining in r
Often I go about joining two dataframes together that have the same name.  Is there a way to do this within the join-step so that I don't end up with a .x and a .y column?  So the names might be 'original_mpg', and 'new_mpg'?</p>

```<code>  library(dplyr)
  left_join(mtcars, mtcars[,c("mpg",'cyl')], by=c("cyl"))
  names(mtcars) #ugh
</code>```

Body:
Often I go about joining two dataframes together that have the same name.  Is there a way to do this within the join-step so that I don't end up with a .x and a .y column?  So the names might be 'original_mpg', and 'new_mpg'?

  library(dplyr)
  left_join(mtcars, mtcars[,c("mpg",'cyl')], by=c("cyl"))
  names(mtcars) #ugh

Body:
The default suffixes, c(".x", ".y"), can be overridden by passing them as a character vector of length 2:

library(dplyr)
left_join(mtcars, mtcars[,c("mpg","cyl")],
              by = c("cyl"),
              suffix = c("_original", "_new")) %>%
      head()

Output

 mpg_original cyl disp  hp drat   wt  qsec vs am gear carb mpg_new
1           21   6  160 110  3.9 2.62 16.46  0  1    4    4    21.0
2           21   6  160 110  3.9 2.62 16.46  0  1    4    4    21.0
3           21   6  160 110  3.9 2.62 16.46  0  1    4    4    21.4
4           21   6  160 110  3.9 2.62 16.46  0  1    4    4    18.1
5           21   6  160 110  3.9 2.62 16.46  0  1    4    4    19.2
6           21   6  160 110  3.9 2.62 16.46  0  1    4    4    17.8


问:
Change year/quarter date format to previous period in python
I have a dataset containing monthly observations of a time-series.
What I want to do is transform the datetime to year/quarter format and then extract the first value DATE[0] as the previous quarter. For example 2006-10-31 belongs to 4Q of 2006. But I want to change it to 2006Q3.
For the extraction of the subsequent values I will just use the last value from each quarter.
So, for 2006Q4 I will keep BBGN, SSD, and QQ4567 values only from DATE[2]. Similarly, for 2007Q1 I will keep only DATE[5] values, and so forth.

Original dataset:

```<code>               DATE                BBGN    SSD             QQ4567
    0  2006-10-31 00:00:00        1.210  22.022          9726.550
    1  2006-11-30 00:00:00        1.270  22.060          9891.008
    2  2006-12-31 00:00:00        1.300  22.080         10055.466
    3  2007-01-31 00:00:00        1.330  22.099         10219.924
    4  2007-02-28 00:00:00        1.393  22.110         10350.406
    5  2007-03-31 00:00:00        1.440  22.125         10480.888
</code>```

After processing the DATE

```<code>       DATE          BBGN    SSD             QQ4567
    0  2006Q3        1.210  22.022          9726.550
    2  2006Q4        1.300  22.080         10055.466
    5  2007Q1        1.440  22.125         10480.888
</code>```

The steps I have taken so far are:

Turn the values from the yyyy-mm-dd hh format to yyyyQQ format

```<code>DF['DATE'] = pd.to_datetime(DF['DATE']).dt.to_period('Q')
</code>```

and I get this

```<code>    DATE          BBGN    SSD             QQ4567
0  2006Q4        1.210  22.022          9726.550
1  2006Q4        1.270  22.060          9891.008
2  2006Q4        1.300  22.080         10055.466
3  2007Q1        1.330  22.099         10219.924
4  2007Q1        1.393  22.110         10350.406
5  2007Q1        1.440  22.125         10480.888
</code>```

The next step is to extract the last values from each quarter. But because I always want to keep the first row I will exclude DATE[0] from the function.

```<code>quarterDF = DF.iloc[1:,].drop_duplicates(subset='DATE', keep='last')
</code>```

Now, my question is how can I change the value in DATE[0] to always be the previous quarter. So, from 2006Q4 to be 2006Q3. Also, how this will work if DATE[0] is 2007Q1, can I change it to 2006Q4?

答:
My suggestion would be to create a new DATE column with a day 3 months in the past. Like this

```<code>import pandas as pd
df = pd.DataFrame()
df['Date'] = pd.to_datetime(['2006-10-31', '2007-01-31'])
one_quarter = pd.tseries.offsets.DateOffset(months=3)
df['Last_quarter'] = df.Date - one_quarter
</code>```

This will give you

```<code>    Date    Last_quarter
0   2006-10-31  2006-07-31
1   2007-01-31  2006-10-31
</code>```

Then you can do the same process as you described above on Last_quarter

Body:
I have a dataset containing monthly observations of a time-series.
What I want to do is transform the datetime to year/quarter format and then extract the first value DATE[0] as the previous quarter. For example 2006-10-31 belongs to 4Q of 2006. But I want to change it to 2006Q3.
For the extraction of the subsequent values I will just use the last value from each quarter.
So, for 2006Q4 I will keep BBGN, SSD, and QQ4567 values only from DATE[2]. Similarly, for 2007Q1 I will keep only DATE[5] values, and so forth.

Original dataset:

               DATE                BBGN    SSD             QQ4567
    0  2006-10-31 00:00:00        1.210  22.022          9726.550
    1  2006-11-30 00:00:00        1.270  22.060          9891.008
    2  2006-12-31 00:00:00        1.300  22.080         10055.466
    3  2007-01-31 00:00:00        1.330  22.099         10219.924
    4  2007-02-28 00:00:00        1.393  22.110         10350.406
    5  2007-03-31 00:00:00        1.440  22.125         10480.888

After processing the DATE

       DATE          BBGN    SSD             QQ4567
    0  2006Q3        1.210  22.022          9726.550
    2  2006Q4        1.300  22.080         10055.466
    5  2007Q1        1.440  22.125         10480.888

The steps I have taken so far are:

Turn the values from the yyyy-mm-dd hh format to yyyyQQ format

DF['DATE'] = pd.to_datetime(DF['DATE']).dt.to_period('Q')

and I get this

    DATE          BBGN    SSD             QQ4567
0  2006Q4        1.210  22.022          9726.550
1  2006Q4        1.270  22.060          9891.008
2  2006Q4        1.300  22.080         10055.466
3  2007Q1        1.330  22.099         10219.924
4  2007Q1        1.393  22.110         10350.406
5  2007Q1        1.440  22.125         10480.888

The next step is to extract the last values from each quarter. But because I always want to keep the first row I will exclude DATE[0] from the function.

quarterDF = DF.iloc[1:,].drop_duplicates(subset='DATE', keep='last')

Now, my question is how can I change the value in DATE[0] to always be the previous quarter. So, from 2006Q4 to be 2006Q3. Also, how this will work if DATE[0] is 2007Q1, can I change it to 2006Q4?

Body:
My suggestion would be to create a new DATE column with a day 3 months in the past. Like this

import pandas as pd
df = pd.DataFrame()
df['Date'] = pd.to_datetime(['2006-10-31', '2007-01-31'])
one_quarter = pd.tseries.offsets.DateOffset(months=3)
df['Last_quarter'] = df.Date - one_quarter

This will give you

    Date    Last_quarter
0   2006-10-31  2006-07-31
1   2007-01-31  2006-10-31

Then you can do the same process as you described above on Last_quarter


问:
What is the best free (or under 200 dollar) database manager software?
I am currently using Toad, but am not very satisied.</p>

答: SQuirreL</p>

Body: SQuirreL


问:
Nokogiri: Searching node with ":"
I have a simple XML structure:

```<code><?xml version="1.0" encoding="utf-8"?>
<response xmlns:msg="..." xmlns:ld="...">
  <msg:testResultBatch providerId="12345" testName="Hello Labs">
    .
    .
    .
  </msg:testResultBatch>
</response>
</code>```

When I pass it to Nokogiri.XML like:

```<code>req = Nokogiri.XML('
    <?xml version="1.0" encoding="utf-8"?>
    <response xmlns:msg="..." xmlns:ld="...">
      <msg:testResultBatch providerId="12345" testName="Hello Labs">
        .
        .
        .
      </msg:testResultBatch>
    </response>
')
</code>```

I'm unable to search nodes with ":". So,

```<code>req.search("response") # works
</code>```

but,

```<code>req.search("msg:testResultBatch") # doesn't works
</code>```

and gives me []

答:
By using xpath and '//msg:testResultBatch' you can get the msg:testResultBatch:

```<code>require 'nokogiri'

req = Nokogiri.XML('
<?xml version="1.0" encoding="utf-8"?>
<response xmlns:msg="..." xmlns:ld="...">
  <msg:testResultBatch providerId="12345" testName="Hello Labs">
  </msg:testResultBatch>
</response>
')
p req.xpath('//msg:testResultBatch').first.name # "testResultBatch"
</code>```

Title: Nokogiri: Searching node with ":"

Body:
I have a simple XML structure:

<?xml version="1.0" encoding="utf-8"?>
<response xmlns:msg="..." xmlns:ld="...">
  <msg:testResultBatch providerId="12345" testName="Hello Labs">
    .
    .
    .
  </msg:testResultBatch>
</response>

When I pass it to Nokogiri.XML like:

req = Nokogiri.XML('
    <?xml version="1.0" encoding="utf-8"?>
    <response xmlns:msg="..." xmlns:ld="...">
      <msg:testResultBatch providerId="12345" testName="Hello Labs">
        .
        .
        .
      </msg:testResultBatch>
    </response>
')

I'm unable to search nodes with ":". So,

req.search("response") # works

but,

req.search("msg:testResultBatch") # doesn't works

and gives me []

Body:
By using xpath and '//msg:testResultBatch' you can get the msg:testResultBatch:

require 'nokogiri'

req = Nokogiri.XML('
<?xml version="1.0" encoding="utf-8"?>
<response xmlns:msg="..." xmlns:ld="...">
  <msg:testResultBatch providerId="12345" testName="Hello Labs">
  </msg:testResultBatch>
</response>
')
p req.xpath('//msg:testResultBatch').first.name # "testResultBatch"


问:
Why am I getting variable not declared
I have the following in my partial view...

```<code>@Model.ServerDetails
<div>
..... various markup
</div>
<script type="text/javascript">
    var bs = '@Model.BackupServer';
    if (bs == null) {
        bs = "";
    }
    var bssn = bs + '|' + '@Model.ServerName';

    $(document).ready( function() {
        if (bs != "") {
          $getJSON('@UrlContent("~/Details/OtherBackedUpServers?bsn=" + bssn)', function(returnedServers) {
             ..... removed for brevity...
          }
        }
    });
</code>```

Unfortunately bssn in the $getJSON() paramater is showing an error: 'bssn' is not declared. It may be inaccessible due to its protection level.

Can someone explain why and how I can correct it?

Thanks

答:
Or write:

```<code>$getJSON('@UrlContent("OtherBackedUpServers", "Details")?bsn=' + bssn, function(returnedServers) {
             ..... removed for brevity...
          }
</code>```

CORRECTION

```<code>$getJSON('@Url.Action("OtherBackedUpServers", "Details")?bsn=' + bssn, function(returnedServers) {
             ..... removed for brevity...
          }
</code>```

Title: Why am I getting variable not declared

Body:
I have the following in my partial view...

@Model.ServerDetails

..... various markup

Body:
Or write:

$getJSON('@UrlContent("OtherBackedUpServers", "Details")?bsn=' + bssn, function(returnedServers) {
             ..... removed for brevity...
          }

CORRECTION

$getJSON('@Url.Action("OtherBackedUpServers", "Details")?bsn=' + bssn, function(returnedServers) {
             ..... removed for brevity...
          }


问:
Microsoft Dynamics CRM SDK : Check if a field value is changed in entity
Apart from Plugins, Is there any way to check if value in entity record has changed using C# MS Dynamics CRM SDK? (Online version) </p>

答:
You could:

Use an on change of field workflow.

Use an on change of JavaScript function (client side only).

Programmatically examine the audit logs.

Programmatically check for record changes every 5 minutes from an external application.


问:
How to do One to One association in hibernate with foreign key and join table and unidirectional
I wish to have a one to one association with a join table in unidirectional way. -

Tables :

A (A_id, D_id, A_Data)

B (A_id, C_id) // Join table just contain relation between A and C

C (C_id, C_Data)

```<code>Class A {
   .
   .
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name = "B",
        joinColumns = @JoinColumn(name = "A_id", referencedColumnName = "A_id"),
        inverseJoinColumns = @JoinColumn(name = "C_id", referencedColumnName = "C_id"))
private C c;
}
</code>```

I am using hibernate with jpa 2.0.
Entity D is not important in the model hence ignored.
I only wish to read data ,hence insert/update/delete use cases should not be concern, but one can suggest best practice in that case also.

This setup does not work. Can some one suggest how to do it in correct way?

It gives following exception

```<code>org.hibernate.MappingException: Unable to find column with logical name: A_id in org.hibernate.mapping.Table(A) and its related supertables and secondary tables
</code>```

答:
In order to get your desired schema:

```<code>    // Given the following C entity
    @Entity
    public class C {

        @Id
        @Column(name = "C_ID")
        private long id;

        private String C_Data;

        //...
    }

    // A Entity should be
    @Entity
    public class A {

        @Id
        @Column(name = "A_ID")
        private long id;

        private String A_Data;

        @OneToOne(cascade = CascadeType.ALL )
        @JoinTable(name = "B", joinColumns = @JoinColumn(name = "A_id"), inverseJoinColumns = @JoinColumn(name = "C_id", unique = true))
        private C c;

        //...

    }
</code>```

I've omitted referencedColumnName, so hibernate will map it to the entity primary key.

Note also that A_id column of B table will be the primary key.

Body:
I wish to have a one to one association with a join table in unidirectional way. -

Tables :

A (A_id, D_id, A_Data)

B (A_id, C_id) // Join table just contain relation between A and C

C (C_id, C_Data)

Class A {
   .
   .
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name = "B",
        joinColumns = @JoinColumn(name = "A_id", referencedColumnName = "A_id"),
        inverseJoinColumns = @JoinColumn(name = "C_id", referencedColumnName = "C_id"))
private C c;
}

I am using hibernate with jpa 2.0.
Entity D is not important in the model hence ignored.
I only wish to read data ,hence insert/update/delete use cases should not be concern, but one can suggest best practice in that case also.

This setup does not work. Can some one suggest how to do it in correct way?

It gives following exception

org.hibernate.MappingException: Unable to find column with logical name: A_id in org.hibernate.mapping.Table(A) and its related supertables and secondary tables

Body:
In order to get your desired schema:

    // Given the following C entity
    @Entity
    public class C {

        @Id
        @Column(name = "C_ID")
        private long id;

        private String C_Data;

        //...
    }

    // A Entity should be
    @Entity
    public class A {

        @Id
        @Column(name = "A_ID")
        private long id;

        private String A_Data;

        @OneToOne(cascade = CascadeType.ALL )
        @JoinTable(name = "B", joinColumns = @JoinColumn(name = "A_id"), inverseJoinColumns = @JoinColumn(name = "C_id", unique = true))
        private C c;

        //...

    }

I've omitted referencedColumnName, so hibernate will map it to the entity primary key.

Note also that A_id column of B table will be the primary key.