问:
Update AWS S3 object key (key name)
I need to rename a huge number of files stored in an AWS S3 bucket. Each file/object will be renamed individually (based on the certain criteria - there is no common "prefix/suffix"). I came up with the list of 'current_filename' and 'new_filename' which can be executed the CLI as a .bat file/queue.

Is it possible to update just an object key (key name) in AWS S3 bucket via CLI or programmatically, without have to copy/move file as below:

```<code>aws s3 cp s3://mybucket/folder/myfilename.jpg s3://mybucket/folder/my_NEW_filename.jpg
</code>```

I can keep all other object metadata the same, but file name (key name) has to change.

答:
Objects/Files in Amazon S3 are immutable and cannot be appended to or
  changed. In order to simulate append, you would need to write the
  entire file again with the additional data.

You need to copy to a different object to change its name.
It would be efficient if you move between s3 buckets rather than copying locally and moving back.

We ran into a similar situation, how I'm going to change all the files. You need to find the pattern to group all the S3 keys and perform renaming parallelly. This is the beauty of a distributed system.

We stored with date/hour/15 minutes pattern. We were able to perform renaming in parallel by renaming them simultaneously through cli.

Hope it helps.

Title: Update AWS S3 object key (key name)

Body:
I need to rename a huge number of files stored in an AWS S3 bucket. Each file/object will be renamed individually (based on the certain criteria - there is no common "prefix/suffix"). I came up with the list of 'current_filename' and 'new_filename' which can be executed the CLI as a .bat file/queue.

Is it possible to update just an object key (key name) in AWS S3 bucket via CLI or programmatically, without have to copy/move file as below:

aws s3 cp s3://mybucket/folder/myfilename.jpg s3://mybucket/folder/my_NEW_filename.jpg

I can keep all other object metadata the same, but file name (key name) has to change.


来源: stackexchange

问:
ASIO example code closing socket before it should
I need a parallel synchronous TCP solution using ASIO. I'm trying to get the example code from these examples working: https://github.com/jvillasante/asio-network-programming-cookbook/tree/master/src (using the server in ch04: 02_Sync_parallel_tcp_server.cpp and the client in ch03: 01_Sync_tcp_client.cpp).

The only thing I changed is the logging to append to text files.

The problem is that while the server runs fine, the client dies after returning a single response from the server:

```<code>libc++abi.dylib: terminating with uncaught exception of type boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >: shutdown: Socket is not connected
</code>```

Code for the server:

```<code>#include <boost/asio.hpp>
#include <atomic>
#include <memory>
#include <thread>
#include <iostream>
#include <fstream>

using namespace boost;

class Service {
public:
  Service() = default;

  void StartHandlingClient(std::shared_ptr<asio::ip::tcp::socket> sock) {
    std::thread th{[this, sock]() { HandleClient(sock); }};
    th.detach();
  }

private:
  void HandleClient(std::shared_ptr<asio::ip::tcp::socket> sock) {
    try {
      asio::streambuf request;
      asio::read_until(*sock.get(), request, '\n');

      std::istream is(&request);
      std::string line;
      std::getline(is, line);

      std::ofstream log("logfile2.txt", std::ios_base::app | std::ios_base::out);
      log << "Request: " << line << "\n" << std::flush;

      // Emulate request processing.
      int i = 0;
      while (i != 1000000) i++;
      std::this_thread::sleep_for(std::chrono::milliseconds(500));

      // Sending response.
      std::string response = "Response\n";
      asio::write(*sock.get(), asio::buffer(response));
    } catch (std::system_error& e) {
      std::ofstream log("logfile1.txt", std::ios_base::app | std::ios_base::out);
      log << "Error occurred! Error code = " << e.code().value() << ". Message: " << e.what() << "\n" << std::flush;
    }

    // Clean up
    delete this;
  }
};

class Acceptor {
public:
  Acceptor(asio::io_service& ios, unsigned short port_num)
  : m_ios{ios}, m_acceptor{m_ios, asio::ip::tcp::endpoint{asio::ip::address_v4::any(), port_num}} {
    m_acceptor.listen();
  }

  void Accept() {
    auto sock = std::make_shared<asio::ip::tcp::socket>(m_ios);

    m_acceptor.accept(*sock.get());

    (new Service)->StartHandlingClient(sock);
  }

private:
  asio::io_service& m_ios;
  asio::ip::tcp::acceptor m_acceptor;
};

class Server {
public:
  Server() : m_stop{false} {}

  void Start(unsigned short port_num) {
    m_thread.reset(new std::thread([this, port_num]() { Run(port_num); }));
  }

  void Stop() {
    m_stop.store(true);
    m_thread->join();
  }

private:
  void Run(unsigned short port_num) {
    Acceptor acc{m_ios, port_num};

    while (!m_stop.load()) {
      acc.Accept();
    }
  }

private:
  std::unique_ptr<std::thread> m_thread;
  std::atomic<bool> m_stop;
  asio::io_service m_ios;
};

int main() {
  unsigned short port_num = 3333;

  try {
    Server srv;
    srv.Start(port_num);

    std::this_thread::sleep_for(std::chrono::seconds(60));

    srv.Stop();
  } catch (std::system_error& e) {
      std::ofstream log("logfile1.txt", std::ios_base::app | std::ios_base::out);
      log << "Error occurred! Error code = " << e.code().value() << ". Message: " << e.what() << "\n" << std::flush;
  }

  return 0;
}
</code>```

Code for the client:

```<code>#include <boost/asio.hpp>
#include <iostream>
#include <fstream>

using namespace boost;

class SyncTCPClient {
public:
  SyncTCPClient(const std::string& raw_ip_address, unsigned short port_num)
  : m_ep(asio::ip::address::from_string(raw_ip_address), port_num), m_sock(m_ios) {
    m_sock.open(m_ep.protocol());
  }
  ~SyncTCPClient() { close(); }

  void connect() { m_sock.connect(m_ep); }

  std::string emulateLongComputationOp(unsigned int duration_sec) {
    std::string request = "EMULATE_LONG_COMP_OP " + std::to_string(duration_sec) + "\n";
    sendRequest(request);
    return receiveResponse();
  }

private:
  void close() {
    if (m_sock.is_open()) {
      std::ofstream log("logfile1.txt", std::ios_base::app | std::ios_base::out);
      log << "shutting down\n" << std::flush;
      m_sock.shutdown(asio::ip::tcp::socket::shutdown_both);
      log << "closing the socket\n" << std::flush;
      m_sock.close();
      log << "socket closed\n" << std::flush;
    }
  }

  void sendRequest(const std::string& request) { asio::write(m_sock, asio::buffer(request)); }

  std::string receiveResponse() {
    asio::streambuf buf;
    asio::read_until(m_sock, buf, '\n');

    std::istream input(&buf);
    std::string response;
    std::getline(input, response);

    return response;
  }

private:
  asio::io_service m_ios;
  asio::ip::tcp::endpoint m_ep;
  asio::ip::tcp::socket m_sock;
};

int main() {
  const std::string raw_ip_address = "127.0.0.1";
  const unsigned short port_num = 3333;

  try {
    SyncTCPClient client{raw_ip_address, port_num};

    // Sync connect.
    client.connect();

    std::cout << "Sending request to the server...\n";
    std::string response = client.emulateLongComputationOp(10);

    std::cout << "Response received: " << response << "\n";
  } catch (std::system_error& e) {
      std::ofstream log("logfile1.txt", std::ios_base::app | std::ios_base::out);
      log << "Error occurred! Error code = " << e.code().value() << ". Message: " << e.what() << "\n" << std::flush;
    return e.code().value();
  }

  return 0;
}
</code>```

答:
I don't see a lot wrong, and I cannot reproduce the problem with the code shown.

Things I do see:

the thread procedure could be a static because it's stateless (delete this is a code smell)

the thread needn't be detached (using boost::thread_group::join_all would be much better)

you were writing to the same logfile from server as well as client; results are undefined

spelling .store() and .load() on an atomic<bool> is un-idiomatic

spelling out *sock.get() on any kind of smart pointer is unforgivably un-idiomatic

writing code().value() - swallowing the category - is a BAD thing to do, and e.what() is NOT the way to get the message (use e.code().message()).

If you need flush, you might as well use std::endl

There's really no reason to use a shared_ptr in c++14:

```<code>asio::ip::tcp::socket sock(m_ios);

m_acceptor.accept(sock);

std::thread([sock=std::move(sock)]() mutable { HandleClient(sock); }).detach();
</code>```

In C++11 stick to:

```<code>auto sock = std::make_shared<asio::ip::tcp::socket>(m_ios);

m_acceptor.accept(*sock);

std::thread([sock] { HandleClient(*sock); }).detach();
</code>```

This means HandleClient can just take a ip::tcp::socket& instead of a smart pointer.

INTEGRATING

Server.cpp

```<code>#include <atomic>
#include <boost/asio.hpp>
#include <fstream>
#include <iostream>
#include <memory>
#include <thread>

using namespace boost;

static void HandleClient(asio::ip::tcp::socket& sock) {
    try {
        asio::streambuf buf;
        asio::read_until(sock, buf, '\n');

        std::string request;
        getline(std::istream(&buf), request);

        std::ofstream log("server.log", std::ios_base::app | std::ios_base::out);
        log << "Request: " << request << std::endl;

        // Emulate request processing.
        int i = 0;
        while (i != 1000000)
            i++;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));

        // Sending response.
        std::string response = "Response\n";
        asio::write(sock, asio::buffer(response));
    } catch (std::system_error &e) {
        std::ofstream log("server.log", std::ios_base::app | std::ios_base::out);
        log << e.what() << " " << e.code() << ": " << e.code().message() << std::endl;
    }
}

class Acceptor {
  public:
    Acceptor(asio::io_service &ios, unsigned short port_num)
            : m_ios{ ios }, m_acceptor{ m_ios, asio::ip::tcp::endpoint{ asio::ip::address_v4::any(), port_num } } {
        m_acceptor.listen();
    }

    void Accept() {
        auto sock = std::make_shared<asio::ip::tcp::socket>(m_ios);

        m_acceptor.accept(*sock);

        std::thread([sock] { HandleClient(*sock); }).detach();
    }

  private:
    asio::io_service &m_ios;
    asio::ip::tcp::acceptor m_acceptor;
};

class Server {
  public:
    Server() : m_stop{ false } {}

    void Start(unsigned short port_num) {
        m_thread.reset(new std::thread([this, port_num]() { Run(port_num); }));
    }

    void Stop() {
        m_stop = true;
        m_thread->join();
    }

  private:
    void Run(unsigned short port_num) {
        Acceptor acc{ m_ios, port_num };

        while (!m_stop) {
            acc.Accept();
        }
    }

  private:
    std::unique_ptr<std::thread> m_thread;
    std::atomic<bool> m_stop;
    asio::io_service m_ios;
};

int main() {
    unsigned short port_num = 3333;

    try {
        Server srv;
        srv.Start(port_num);

        std::this_thread::sleep_for(std::chrono::seconds(60));

        srv.Stop();
    } catch (std::system_error &e) {
        std::ofstream log("server.log", std::ios_base::app | std::ios_base::out);
        log << e.what() << " " << e.code() << ": " << e.code().message() << std::endl;
    }
}
</code>```

Client.cpp

```<code>#include <boost/asio.hpp>
#include <fstream>
#include <iostream>

using namespace boost;

class SyncTCPClient {
  public:
    SyncTCPClient(const std::string &raw_ip_address, unsigned short port_num)
            : m_ep(asio::ip::address::from_string(raw_ip_address), port_num), m_sock(m_ios) {
        m_sock.open(m_ep.protocol());
    }
    ~SyncTCPClient() { close(); }

    void connect() { m_sock.connect(m_ep); }

    std::string emulateLongComputationOp(unsigned int duration_sec) {
        std::string request = "EMULATE_LONG_COMP_OP " + std::to_string(duration_sec) + "\n";
        sendRequest(request);
        return receiveResponse();
    }

  private:
    void close() {
        if (m_sock.is_open()) {
            std::ofstream log("client.log", std::ios_base::app | std::ios_base::out);
            log << "shutting down" << std::endl;
            m_sock.shutdown(asio::ip::tcp::socket::shutdown_both);
            log << "closing the socket" << std::endl;
            m_sock.close();
            log << "socket closed" << std::endl;
        }
    }

    void sendRequest(const std::string &request) { asio::write(m_sock, asio::buffer(request)); }

    std::string receiveResponse() {
        asio::streambuf buf;
        asio::read_until(m_sock, buf, '\n');

        std::string response;
        getline(std::istream(&buf), response);

        return response;
    }

  private:
    asio::io_service m_ios;
    asio::ip::tcp::endpoint m_ep;
    asio::ip::tcp::socket m_sock;
};

int main() {
    const std::string raw_ip_address = "127.0.0.1";
    const unsigned short port_num = 3333;

    try {
        SyncTCPClient client{ raw_ip_address, port_num };

        // Sync connect.
        client.connect();

        std::cout << "Sending request to the server...\n";
        std::string response = client.emulateLongComputationOp(10);

        std::cout << "Response received: " << response << std::endl;
    } catch (std::system_error &e) {
        std::ofstream log("client.log", std::ios_base::app | std::ios_base::out);
        log << e.what() << " " << e.code() << ": " << e.code().message() << std::endl;
        return e.code().value();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need a parallel synchronous TCP solution using ASIO. I'm trying to get the example code from these examples working: https://github.com/jvillasante/asio-network-programming-cookbook/tree/master/src (using the server in ch04: 02_Sync_parallel_tcp_server.cpp and the client in ch03: 01_Sync_tcp_client.cpp).

The only thing I changed is the logging to append to text files.

The problem is that while the server runs fine, the client dies after returning a single response from the server:

libc++abi.dylib: terminating with uncaught exception of type boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >: shutdown: Socket is not connected

Code for the server:

#include <boost/asio.hpp>
#include <atomic>
#include <memory>
#include <thread>
#include <iostream>
#include <fstream>

using namespace boost;

class Service {
public:
  Service() = default;

  void StartHandlingClient(std::shared_ptr<asio::ip::tcp::socket> sock) {
    std::thread th{[this, sock]() { HandleClient(sock); }};
    th.detach();
  }

private:
  void HandleClient(std::shared_ptr<asio::ip::tcp::socket> sock) {
    try {
      asio::streambuf request;
      asio::read_until(*sock.get(), request, '\n');

      std::istream is(&request);
      std::string line;
      std::getline(is, line);

      std::ofstream log("logfile2.txt", std::ios_base::app | std::ios_base::out);
      log << "Request: " << line << "\n" << std::flush;

      // Emulate request processing.
      int i = 0;
      while (i != 1000000) i++;
      std::this_thread::sleep_for(std::chrono::milliseconds(500));

      // Sending response.
      std::string response = "Response\n";
      asio::write(*sock.get(), asio::buffer(response));
    } catch (std::system_error& e) {
      std::ofstream log("logfile1.txt", std::ios_base::app | std::ios_base::out);
      log << "Error occurred! Error code = " << e.code().value() << ". Message: " << e.what() << "\n" << std::flush;
    }

    // Clean up
    delete this;
  }
};

class Acceptor {
public:
  Acceptor(asio::io_service& ios, unsigned short port_num)
  : m_ios{ios}, m_acceptor{m_ios, asio::ip::tcp::endpoint{asio::ip::address_v4::any(), port_num}} {
    m_acceptor.listen();
  }

  void Accept() {
    auto sock = std::make_shared<asio::ip::tcp::socket>(m_ios);

    m_acceptor.accept(*sock.get());

    (new Service)->StartHandlingClient(sock);
  }

private:
  asio::io_service& m_ios;
  asio::ip::tcp::acceptor m_acceptor;
};

class Server {
public:
  Server() : m_stop{false} {}

  void Start(unsigned short port_num) {
    m_thread.reset(new std::thread([this, port_num]() { Run(port_num); }));
  }

  void Stop() {
    m_stop.store(true);
    m_thread->join();
  }

private:
  void Run(unsigned short port_num) {
    Acceptor acc{m_ios, port_num};

    while (!m_stop.load()) {
      acc.Accept();
    }
  }

private:
  std::unique_ptr<std::thread> m_thread;
  std::atomic<bool> m_stop;
  asio::io_service m_ios;
};

int main() {
  unsigned short port_num = 3333;

  try {
    Server srv;
    srv.Start(port_num);

    std::this_thread::sleep_for(std::chrono::seconds(60));

    srv.Stop();
  } catch (std::system_error& e) {
      std::ofstream log("logfile1.txt", std::ios_base::app | std::ios_base::out);
      log << "Error occurred! Error code = " << e.code().value() << ". Message: " << e.what() << "\n" << std::flush;
  }

  return 0;
}

Code for the client:

#include <boost/asio.hpp>
#include <iostream>
#include <fstream>

using namespace boost;

class SyncTCPClient {
public:
  SyncTCPClient(const std::string& raw_ip_address, unsigned short port_num)
  : m_ep(asio::ip::address::from_string(raw_ip_address), port_num), m_sock(m_ios) {
    m_sock.open(m_ep.protocol());
  }
  ~SyncTCPClient() { close(); }

  void connect() { m_sock.connect(m_ep); }

  std::string emulateLongComputationOp(unsigned int duration_sec) {
    std::string request = "EMULATE_LONG_COMP_OP " + std::to_string(duration_sec) + "\n";
    sendRequest(request);
    return receiveResponse();
  }

private:
  void close() {
    if (m_sock.is_open()) {
      std::ofstream log("logfile1.txt", std::ios_base::app | std::ios_base::out);
      log << "shutting down\n" << std::flush;
      m_sock.shutdown(asio::ip::tcp::socket::shutdown_both);
      log << "closing the socket\n" << std::flush;
      m_sock.close();
      log << "socket closed\n" << std::flush;
    }
  }

  void sendRequest(const std::string& request) { asio::write(m_sock, asio::buffer(request)); }

  std::string receiveResponse() {
    asio::streambuf buf;
    asio::read_until(m_sock, buf, '\n');

    std::istream input(&buf);
    std::string response;
    std::getline(input, response);

    return response;
  }

private:
  asio::io_service m_ios;
  asio::ip::tcp::endpoint m_ep;
  asio::ip::tcp::socket m_sock;
};

int main() {
  const std::string raw_ip_address = "127.0.0.1";
  const unsigned short port_num = 3333;

  try {
    SyncTCPClient client{raw_ip_address, port_num};

    // Sync connect.
    client.connect();

    std::cout << "Sending request to the server...\n";
    std::string response = client.emulateLongComputationOp(10);

    std::cout << "Response received: " << response << "\n";
  } catch (std::system_error& e) {
      std::ofstream log("logfile1.txt", std::ios_base::app | std::ios_base::out);
      log << "Error occurred! Error code = " << e.code().value() << ". Message: " << e.what() << "\n" << std::flush;
    return e.code().value();
  }

  return 0;
}

Body:
I don't see a lot wrong, and I cannot reproduce the problem with the code shown.

Things I do see:

the thread procedure could be a static because it's stateless (delete this is a code smell)

the thread needn't be detached (using boost::thread_group::join_all would be much better)

you were writing to the same logfile from server as well as client; results are undefined

spelling .store() and .load() on an atomic<bool> is un-idiomatic

spelling out *sock.get() on any kind of smart pointer is unforgivably un-idiomatic

writing code().value() - swallowing the category - is a BAD thing to do, and e.what() is NOT the way to get the message (use e.code().message()).

If you need flush, you might as well use std::endl

There's really no reason to use a shared_ptr in c++14:

asio::ip::tcp::socket sock(m_ios);

m_acceptor.accept(sock);

std::thread([sock=std::move(sock)]() mutable { HandleClient(sock); }).detach();

In C++11 stick to:

auto sock = std::make_shared<asio::ip::tcp::socket>(m_ios);

m_acceptor.accept(*sock);

std::thread([sock] { HandleClient(*sock); }).detach();

This means HandleClient can just take a ip::tcp::socket& instead of a smart pointer.

INTEGRATING

Server.cpp

#include <atomic>
#include <boost/asio.hpp>
#include <fstream>
#include <iostream>
#include <memory>
#include <thread>

using namespace boost;

static void HandleClient(asio::ip::tcp::socket& sock) {
    try {
        asio::streambuf buf;
        asio::read_until(sock, buf, '\n');

        std::string request;
        getline(std::istream(&buf), request);

        std::ofstream log("server.log", std::ios_base::app | std::ios_base::out);
        log << "Request: " << request << std::endl;

        // Emulate request processing.
        int i = 0;
        while (i != 1000000)
            i++;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));

        // Sending response.
        std::string response = "Response\n";
        asio::write(sock, asio::buffer(response));
    } catch (std::system_error &e) {
        std::ofstream log("server.log", std::ios_base::app | std::ios_base::out);
        log << e.what() << " " << e.code() << ": " << e.code().message() << std::endl;
    }
}

class Acceptor {
  public:
    Acceptor(asio::io_service &ios, unsigned short port_num)
            : m_ios{ ios }, m_acceptor{ m_ios, asio::ip::tcp::endpoint{ asio::ip::address_v4::any(), port_num } } {
        m_acceptor.listen();
    }

    void Accept() {
        auto sock = std::make_shared<asio::ip::tcp::socket>(m_ios);

        m_acceptor.accept(*sock);

        std::thread([sock] { HandleClient(*sock); }).detach();
    }

  private:
    asio::io_service &m_ios;
    asio::ip::tcp::acceptor m_acceptor;
};

class Server {
  public:
    Server() : m_stop{ false } {}

    void Start(unsigned short port_num) {
        m_thread.reset(new std::thread([this, port_num]() { Run(port_num); }));
    }

    void Stop() {
        m_stop = true;
        m_thread->join();
    }

  private:
    void Run(unsigned short port_num) {
        Acceptor acc{ m_ios, port_num };

        while (!m_stop) {
            acc.Accept();
        }
    }

  private:
    std::unique_ptr<std::thread> m_thread;
    std::atomic<bool> m_stop;
    asio::io_service m_ios;
};

int main() {
    unsigned short port_num = 3333;

    try {
        Server srv;
        srv.Start(port_num);

        std::this_thread::sleep_for(std::chrono::seconds(60));

        srv.Stop();
    } catch (std::system_error &e) {
        std::ofstream log("server.log", std::ios_base::app | std::ios_base::out);
        log << e.what() << " " << e.code() << ": " << e.code().message() << std::endl;
    }
}

Client.cpp

#include <boost/asio.hpp>
#include <fstream>
#include <iostream>

using namespace boost;

class SyncTCPClient {
  public:
    SyncTCPClient(const std::string &raw_ip_address, unsigned short port_num)
            : m_ep(asio::ip::address::from_string(raw_ip_address), port_num), m_sock(m_ios) {
        m_sock.open(m_ep.protocol());
    }
    ~SyncTCPClient() { close(); }

    void connect() { m_sock.connect(m_ep); }

    std::string emulateLongComputationOp(unsigned int duration_sec) {
        std::string request = "EMULATE_LONG_COMP_OP " + std::to_string(duration_sec) + "\n";
        sendRequest(request);
        return receiveResponse();
    }

  private:
    void close() {
        if (m_sock.is_open()) {
            std::ofstream log("client.log", std::ios_base::app | std::ios_base::out);
            log << "shutting down" << std::endl;
            m_sock.shutdown(asio::ip::tcp::socket::shutdown_both);
            log << "closing the socket" << std::endl;
            m_sock.close();
            log << "socket closed" << std::endl;
        }
    }

    void sendRequest(const std::string &request) { asio::write(m_sock, asio::buffer(request)); }

    std::string receiveResponse() {
        asio::streambuf buf;
        asio::read_until(m_sock, buf, '\n');

        std::string response;
        getline(std::istream(&buf), response);

        return response;
    }

  private:
    asio::io_service m_ios;
    asio::ip::tcp::endpoint m_ep;
    asio::ip::tcp::socket m_sock;
};

int main() {
    const std::string raw_ip_address = "127.0.0.1";
    const unsigned short port_num = 3333;

    try {
        SyncTCPClient client{ raw_ip_address, port_num };

        // Sync connect.
        client.connect();

        std::cout << "Sending request to the server...\n";
        std::string response = client.emulateLongComputationOp(10);

        std::cout << "Response received: " << response << std::endl;
    } catch (std::system_error &e) {
        std::ofstream log("client.log", std::ios_base::app | std::ios_base::out);
        log << e.what() << " " << e.code() << ": " << e.code().message() << std::endl;
        return e.code().value();
    }
}


问:
How to make idea plugin in gradle generate proper project configuration for Kotlin?
I have configured my build.gradle to run gradle test and gradle run properly. However, IDEA does not show any run/test tasks after importing the configuration generated by gradle idea. It seems that these tasks are not included at ipr/iws at all.

Here is my build.gradle:

```<code>buildscript {
    ext.kotlin_version = '1.2.0'

    repositories {
        maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.dokka:dokka-gradle-plugin:$dokka_version"
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.2'
    }
}

apply plugin: 'kotlin'
apply plugin: 'org.jetbrains.dokka'
apply plugin: 'application'
apply plugin: 'org.junit.platform.gradle.plugin'
apply plugin: 'idea'

dokka {
    outputFormat = 'html'
    outputDirectory = "$buildDir/javadoc"
}

sourceSets {
    test.kotlin.srcDirs += 'src/test/kotlin'
}

junitPlatform {
    enableStandardTestTask true
}

defaultTasks 'run'
mainClassName = 'simpledb.server.Startup'

repositories {
    maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
}

dependencies {
        compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
        testCompile 'org.junit.jupiter:junit-jupiter-api:5.0.2'
        testRuntime (
            'org.junit.jupiter:junit-jupiter-engine:5.0.2',
            'org.junit.platform:junit-platform-launcher:1.0.2'
        )
        testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
}
</code>```

I was wondering is there any way to make generated project configurations include these tasks(run/test)? I have also heard people saying Don't use gradle idea, so is it impossible to use gradle idea to implement this?

答: It is simply not necessary in your case. Just open the build.gradle file with IDEA and everything should be smooth. The idea Gradle plugin is somewhat deprecated. Not officially, but it was created by Gradle team and is not actively developed to adapt to new IDEA versions and features and so on. So if you don't need special customizations, just open the build.gradle with IDEA and you should be good to go.

Body:
I have configured my build.gradle to run gradle test and gradle run properly. However, IDEA does not show any run/test tasks after importing the configuration generated by gradle idea. It seems that these tasks are not included at ipr/iws at all.

Here is my build.gradle:

buildscript {
    ext.kotlin_version = '1.2.0'

    repositories {
        maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.dokka:dokka-gradle-plugin:$dokka_version"
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.2'
    }
}

apply plugin: 'kotlin'
apply plugin: 'org.jetbrains.dokka'
apply plugin: 'application'
apply plugin: 'org.junit.platform.gradle.plugin'
apply plugin: 'idea'

dokka {
    outputFormat = 'html'
    outputDirectory = "$buildDir/javadoc"
}

sourceSets {
    test.kotlin.srcDirs += 'src/test/kotlin'
}

junitPlatform {
    enableStandardTestTask true
}

defaultTasks 'run'
mainClassName = 'simpledb.server.Startup'

repositories {
    maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
}

dependencies {
        compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
        testCompile 'org.junit.jupiter:junit-jupiter-api:5.0.2'
        testRuntime (
            'org.junit.jupiter:junit-jupiter-engine:5.0.2',
            'org.junit.platform:junit-platform-launcher:1.0.2'
        )
        testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
}

I was wondering is there any way to make generated project configurations include these tasks(run/test)? I have also heard people saying Don't use gradle idea, so is it impossible to use gradle idea to implement this?


问:
Polymorphism vs Inheritance
Suppose I have two classes: Animal and Dog. Dog is a subclass of Animal. I do the following code:

```<code>Animal a = new Dog();
</code>```

Now I can call methods of the Dog class through the a variable.

But my question is this: if I can call all of Animal's methods through the Dog objects (inheritance) than why should I use the polymorphism principle? I can just declare:

```<code>Dog d = new Dog();
</code>```

With this declaration can use all of Animal's methods and Dog methods. So why use polymorphism? Thank you very much for your answer.

答: inheritance is the dynamic polymorphism. I mean when you remove inheritance you can not override anymore.  </p>

Title: Polymorphism vs Inheritance

Body:
Suppose I have two classes: Animal and Dog. Dog is a subclass of Animal. I do the following code:

Animal a = new Dog();

Now I can call methods of the Dog class through the a variable.

But my question is this: if I can call all of Animal's methods through the Dog objects (inheritance) than why should I use the polymorphism principle? I can just declare:

Dog d = new Dog();

With this declaration can use all of Animal's methods and Dog methods. So why use polymorphism? Thank you very much for your answer.


问:
obtain hour from DateTime vector
I have a DateTime vector within a data.frame where the data frame is made up of 8760 observations representing hourly intervals throughout the year e.g.

```<code>2010-01-01 00:00
2010-01-01 01:00
2010-01-01 02:00
2010-01-01 03:00
</code>```

and so on.

I would like to create a data.frame which has the original DateTime vector as the first column and then the hourly values in the second column e.g.

```<code>2010-01-01 00:00          00:00
2010-01-01 01:00          01:00
</code>```

How can this be achieved?

答:
On a more general note, for anyone that comes here from google and maybe wants to group by hour:

The key here is: lubridate::hour(datetime)

p22 in the cran doc here: https://cran.r-project.org/web/packages/lubridate/lubridate.pdf

Title: obtain hour from DateTime vector

Body:
I have a DateTime vector within a data.frame where the data frame is made up of 8760 observations representing hourly intervals throughout the year e.g.

2010-01-01 00:00
2010-01-01 01:00
2010-01-01 02:00
2010-01-01 03:00

and so on.

I would like to create a data.frame which has the original DateTime vector as the first column and then the hourly values in the second column e.g.

2010-01-01 00:00          00:00
2010-01-01 01:00          01:00

How can this be achieved?


问:
Windows Forms: capturing MouseWheel
I have a Windows Form (working in C#.NET).

The form has a couple of panels top-side and some ComboBoxes and DataGridViews bottom-side.

I want to use the scroll events on the top-side panels, but if selecting a e.g. ComboBox the focus is lost. The panels contain various other controls.

How could I always receive the mouse wheel events when the mouse is over any of the panels ?
So far I tried to use the MouseEnter / MouseEnter events but with no luck.

答:
Every control has a mousewheel event that occurs when the mouse wheel moves while the control has focus.

Check this out for more info: Control.MouseWheel Event

ContentLicense: CC BY-SA 2.5

Title: Windows Forms: capturing MouseWheel


问:
Writing large number of records (bulk insert) to Access in .NET/C#
What is the best way to perform bulk inserts into an MS Access database from .NET?  Using ADO.NET, it is taking way over an hour to write out a large dataset.

Note that my original post, before I "refactored" it, had both the question and answer in the question part.  I took Igor Turman's suggestion and re-wrote it in two parts - the question above and followed by my answer.

答: Note the position of the DAO component here. This helps explain the efficiency improvements.</p>


问:
Error handling in bash/expect script
Pasted below is a bash script, combined with expect code, which:

connects to remote host via ssh, collects files and prepare tgz file;

copy tgz file from remote host to local machine;

connects to remote host via ssh again and remove previously created tgz file;

finally, extract tgz file on local machine.

Everything works, if passed arguments are valid (i.e., $host, $user, and $pass). If one of them is incorrect, script hangs. I wonder how to include some error handling (e.g., in $cmd1) to terminate script with message if username (or password) is incorrect?

Thanks in advance for any pointers.

```<code>#!/bin/bash
prog=$(basename $0)
NO_ARGS=0
E_OPTERROR=85

# Script invoked with no command-line args?
if [ $# -eq "$NO_ARGS" ]; then
  echo "Usage: $prog [-h host] [-u username] [-p password]"
  echo "       $prog -help for help."
  exit $E_OPTERROR
fi

showhelp() {
  echo "Usage: $prog [-h host] [-u username] [-p password]"
  echo " -h: host"
  echo " -u: username"
  echo " -p: password"
  echo " -help: this help message"
  exit 2
}

user=""
host=""
pass=""
now=$(date +"%m-%d-%Y")
dir="data_$now"
file="data.tgz"

while getopts "h:u:p:help" name; do
  case $name in
    h)
      host=$OPTARG
    ;;
    u)
      user=$OPTARG
    ;;
    p)
      pass=$OPTARG
    ;;
    help)
      showhelp $0
    ;;
  esac
done

if [ -d "$dir" ]; then
  rm -R $dir
  mkdir $dir
else
  mkdir $dir
fi

cmd1=$(expect << EOF
spawn ssh $user@$host
expect "password: "
send "$pass\n"
expect "$ "
send "cd /tmp\n"
expect "$ "
send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n"
expect "$ "
send "logout"
EOF)

cmd2=$(expect << EOF
spawn scp $user@$host:/tmp/$file $dir
expect "password: "
send "$pass\n"
expect "$ "
EOF)

CMD3=$(expect << EOF
spawn ssh $user@$host
expect "password: "
send "$pass\n"
expect "$ "
send "cd /tmp\n"
expect "$ "
send "rm $file\n"
expect "$ "
send "logout"
EOF)

echo "$cmd1"
echo "$cmd2"
echo "$cmd3"
cd $dir
tar -xzf $file
rm $file
count=$(ls -1 | wc -l | awk '{gsub(/^ +| +$/, "")}1')
cd ..
#clear
echo "All done. Extracted $count *.net files."
</code>```

答:
```<code>expect {
{
  "Permission denied, please try again." {
       send_user "Wrong password"
       }
  "$ " {
       send "cd /tmp\n"
       expect "$ "
       send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n"
       expect "$ "
       send "logout"
   }
</code>```

Here when we remove the command exit, expect should print "Wrong password" and than do the next part by sending "cd /tmp\n".......
is that correct than?

Title: Error handling in bash/expect script

Body:
Pasted below is a bash script, combined with expect code, which:

connects to remote host via ssh, collects files and prepare tgz file;

copy tgz file from remote host to local machine;

connects to remote host via ssh again and remove previously created tgz file;

finally, extract tgz file on local machine.

Everything works, if passed arguments are valid (i.e., $host, $user, and $pass). If one of them is incorrect, script hangs. I wonder how to include some error handling (e.g., in $cmd1) to terminate script with message if username (or password) is incorrect?

Thanks in advance for any pointers.

#!/bin/bash
prog=$(basename $0)
NO_ARGS=0
E_OPTERROR=85

# Script invoked with no command-line args?
if [ $# -eq "$NO_ARGS" ]; then
  echo "Usage: $prog [-h host] [-u username] [-p password]"
  echo "       $prog -help for help."
  exit $E_OPTERROR
fi

showhelp() {
  echo "Usage: $prog [-h host] [-u username] [-p password]"
  echo " -h: host"
  echo " -u: username"
  echo " -p: password"
  echo " -help: this help message"
  exit 2
}

user=""
host=""
pass=""
now=$(date +"%m-%d-%Y")
dir="data_$now"
file="data.tgz"

while getopts "h:u:p:help" name; do
  case $name in
    h)
      host=$OPTARG
    ;;
    u)
      user=$OPTARG
    ;;
    p)
      pass=$OPTARG
    ;;
    help)
      showhelp $0
    ;;
  esac
done

if [ -d "$dir" ]; then
  rm -R $dir
  mkdir $dir
else
  mkdir $dir
fi

cmd1=$(expect << EOF
spawn ssh $user@$host
expect "password: "
send "$pass\n"
expect "$ "
send "cd /tmp\n"
expect "$ "
send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n"
expect "$ "
send "logout"
EOF)

cmd2=$(expect << EOF
spawn scp $user@$host:/tmp/$file $dir
expect "password: "
send "$pass\n"
expect "$ "
EOF)

CMD3=$(expect << EOF
spawn ssh $user@$host
expect "password: "
send "$pass\n"
expect "$ "
send "cd /tmp\n"
expect "$ "
send "rm $file\n"
expect "$ "
send "logout"
EOF)

echo "$cmd1"
echo "$cmd2"
echo "$cmd3"
cd $dir
tar -xzf $file
rm $file
count=$(ls -1 | wc -l | awk '{gsub(/^ +| +$/, "")}1')
cd ..
#clear
echo "All done. Extracted $count *.net files."

Body:
expect {
{
  "Permission denied, please try again." {
       send_user "Wrong password"
       }
  "$ " {
       send "cd /tmp\n"
       expect "$ "
       send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n"
       expect "$ "
       send "logout"
   }

Here when we remove the command exit, expect should print "Wrong password" and than do the next part by sending "cd /tmp\n".......
is that correct than?


问:
How do I add an additional column to this dataframe to convert coordinates to Zip Code?
So I'm trying to add an additional column to my dataframe as it already has coordinates, but I need the zip code.

```<code>import pandas as pd
from geopy.geocoders import Nominatim

url3 = 'https://raw.githubusercontent.com/chrisc617/Data-Bootcamp'
url4 = '-Final-Project/master/NYC_Transit_Subway_Entrance_And_Exit_Data.csv'
url5 = url3+url4
trains = pd.read_csv(url5)
trains.columns

trains['Zip Code'] = (location = geolocator.reverse(trains['Station Location'])
print(location.address[-18:-13]))
</code>```

Is the above code not the best way to go about it?

答:
How about this:</p>

```<code>trains['Zip Code'] = trains['Station Location'].apply(lambda x: geolocator.reverse(x))
</code>```

Body:
So I'm trying to add an additional column to my dataframe as it already has coordinates, but I need the zip code.

import pandas as pd
from geopy.geocoders import Nominatim

url3 = 'https://raw.githubusercontent.com/chrisc617/Data-Bootcamp'
url4 = '-Final-Project/master/NYC_Transit_Subway_Entrance_And_Exit_Data.csv'
url5 = url3+url4
trains = pd.read_csv(url5)
trains.columns

trains['Zip Code'] = (location = geolocator.reverse(trains['Station Location'])
print(location.address[-18:-13]))

Is the above code not the best way to go about it?

Body:
How about this:

trains['Zip Code'] = trains['Station Location'].apply(lambda x: geolocator.reverse(x))


问:
how can I enforce english language in a git commit message?
Is it possible to enforce english in a commit message?

At the moment, git commit messages in our projects are a mix of 2 languages and the team keeps forgetting git messages good practices. Could we at least show a warning?

Thanks

答:
Well, you can use a pre-commit hook, to run a script, what validate your commit.

So if you can find a program, what can determine if it's valid English, then you can validate your commits.

Or you can use pull requests, and just reject any non English commit.


问:
How do i get a css html menu dropdown like this picture
How do i get a good or similar HTML/CSS drop down like this picture
http://i65.tinypic.com/2s8sc4j.png

I have this code in my style.php

/*----- Toggle Button -----*/

.toggle-nav {
  display: none;
}

/*----- Menu -----*/

@media screen and (min-width: 860px) {
  .menu {
    width: 100%;
    padding: 10px 18px;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.15);
    border-radius: 3px;
    background: #303030;
  }
}

.menu ul {
  display: inline-block;
}

.menu li {
  margin: 0px 50px 0px 0px;
  float: left;
  list-style: none;
  font-size: 17px;
}

.menu li:last-child {
  margin-right: 0px;
}

.menu a {
  text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.5);
  color: #777;
  transition: color linear 0.15s;
}

.menu a:hover,
.menu .current-item a {
  text-decoration: none;
  color: #66a992;
}

/*----- Search -----*/

.search-form {
  float: right;
  display: inline-block;
}

.search-form input {
  width: 200px;
  height: 30px;
  padding: 0px 8px;
  float: left;
  border-radius: 2px 0px 0px 2px;
  font-size: 13px;
}

.search-form button {
  height: 30px;
  padding: 0px 7px;
  float: right;
  border-radius: 0px 2px 2px 0px;
  background: #66a992;
  font-size: 13px;
  font-weight: 600;
  text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.3);
  color: #fff;
}

/*----- Responsive -----*/

@media screen and (max-width: 1150px) {
  .wrap {
    width: 90%;
  }
}

@media screen and (max-width: 970px) {
  .search-form input {
    width: 120px;
  }
}

@media screen and (max-width: 860px) {
  .menu {
    position: relative;
    display: inline-block;
  }
  .menu ul.active {
    display: none;
  }
  .menu ul {
    width: 100%;
    position: absolute;
    top: 120%;
    left: 0px;
    padding: 10px 18px;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.15);
    border-radius: 3px;
    background: #303030;
  }
  .menu ul:after {
    width: 0px;
    height: 0px;
    position: absolute;
    top: 0%;
    left: 22px;
    content: '';
    transform: translate(0%, -100%);
    border-left: 7px solid transparent;
    border-right: 7px solid transparent;
    border-bottom: 7px solid #303030;
  }
  .menu li {
    margin: 5px 0px 5px 0px;
    float: none;
    display: block;
  }
  .menu a {
    display: block;
  }
  .toggle-nav {
    padding: 20px;
    float: left;
    display: inline-block;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.15);
    border-radius: 3px;
    background: #303030;
    text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.5);
    color: #777;
    font-size: 20px;
    transition: color linear 0.15s;
  }
  .toggle-nav:hover,
  .toggle-nav.active {
    text-decoration: none;
    color: #66a992;
  }
  .search-form {
    margin: 12px 0px 0px 20px;
    float: left;
  }
  .search-form input {
    box-shadow: -1px 1px 2px rgba(0, 0, 0, 0.1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="menu">
  <ul class="active">
    <li class="current-item">Home</li>
    <li>My Work</li>
    <li>About Me</li>
    <li>Get in Touch</li>
    <li>Blog</li>
  </ul> ☰
  <form class="search-form">
    <input type="text">
    <button>Search</button>
  </form>
</nav></code>```

The results of my code look like:
http://i67.tinypic.com/qp1l5d.png

The drop down menu is not opening on click. Can I achieve it or get a similar CSS/HTML menu drop down like the picture above?
Big thanks for your time and contribution is my solutions

答:
My solution to get an effect like the photo attached would be to amend the .menu ul.active class giving it:

transition: all .5s; for smooth scrolling

overflow:hidden; so the menu items are hidden when no being toggled

height:0px; to give it a default height of nothing - *important

The I would created a new class called .drop and use JavaScript to toggle this new class on and off the ul. See both sets of amended code below and here is a JSFiddle link to the working solution - https://jsfiddle.net/2vqp39nd/2/

CSS Changes -

```<code>.menu ul.active {
    transition: all .5s;
    height:0px;
    overflow:hidden;
  }

  .drop {
  height:170px!important;
  /* Set this at required height */
}
</code>```

JavaScript Changes -

```<code>var ul = document.getElementsByClassName('active')[0],
  btn = document.getElementsByClassName('toggle-nav')[0];

  function dropDown () {
        ul.classList.toggle('drop');
    }

  btn.addEventListener('click',dropDown,false);
</code>```

Body:
How do i get a good or similar HTML/CSS drop down like this picture
http://i65.tinypic.com/2s8sc4j.png

I have this code in my style.php

/*----- Toggle Button -----*/

.toggle-nav {
  display: none;
}

/*----- Menu -----*/

@media screen and (min-width: 860px) {
  .menu {
    width: 100%;
    padding: 10px 18px;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.15);
    border-radius: 3px;
    background: #303030;
  }
}

.menu ul {
  display: inline-block;
}

.menu li {
  margin: 0px 50px 0px 0px;
  float: left;
  list-style: none;
  font-size: 17px;
}

.menu li:last-child {
  margin-right: 0px;
}

.menu a {
  text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.5);
  color: #777;
  transition: color linear 0.15s;
}

.menu a:hover,
.menu .current-item a {
  text-decoration: none;
  color: #66a992;
}

/*----- Search -----*/

.search-form {
  float: right;
  display: inline-block;
}

.search-form input {
  width: 200px;
  height: 30px;
  padding: 0px 8px;
  float: left;
  border-radius: 2px 0px 0px 2px;
  font-size: 13px;
}

.search-form button {
  height: 30px;
  padding: 0px 7px;
  float: right;
  border-radius: 0px 2px 2px 0px;
  background: #66a992;
  font-size: 13px;
  font-weight: 600;
  text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.3);
  color: #fff;
}

/*----- Responsive -----*/

@media screen and (max-width: 1150px) {
  .wrap {
    width: 90%;
  }
}

@media screen and (max-width: 970px) {
  .search-form input {
    width: 120px;
  }
}

@media screen and (max-width: 860px) {
  .menu {
    position: relative;
    display: inline-block;
  }
  .menu ul.active {
    display: none;
  }
  .menu ul {
    width: 100%;
    position: absolute;
    top: 120%;
    left: 0px;
    padding: 10px 18px;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.15);
    border-radius: 3px;
    background: #303030;
  }
  .menu ul:after {
    width: 0px;
    height: 0px;
    position: absolute;
    top: 0%;
    left: 22px;
    content: '';
    transform: translate(0%, -100%);
    border-left: 7px solid transparent;
    border-right: 7px solid transparent;
    border-bottom: 7px solid #303030;
  }
  .menu li {
    margin: 5px 0px 5px 0px;
    float: none;
    display: block;
  }
  .menu a {
    display: block;
  }
  .toggle-nav {
    padding: 20px;
    float: left;
    display: inline-block;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.15);
    border-radius: 3px;
    background: #303030;
    text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.5);
    color: #777;
    font-size: 20px;
    transition: color linear 0.15s;
  }
  .toggle-nav:hover,
  .toggle-nav.active {
    text-decoration: none;
    color: #66a992;
  }
  .search-form {
    margin: 12px 0px 0px 20px;
    float: left;
  }
  .search-form input {
    box-shadow: -1px 1px 2px rgba(0, 0, 0, 0.1);
  }
}

Home

My Work

About Me

Get in Touch

Blog

 ☰
  <form class="search-form">
    <input type="text">
    <button>Search</button>
  </form>

The results of my code look like:
http://i67.tinypic.com/qp1l5d.png

The drop down menu is not opening on click. Can I achieve it or get a similar CSS/HTML menu drop down like the picture above?
Big thanks for your time and contribution is my solutions

Body:
My solution to get an effect like the photo attached would be to amend the .menu ul.active class giving it:

transition: all .5s; for smooth scrolling

overflow:hidden; so the menu items are hidden when no being toggled

height:0px; to give it a default height of nothing - *important

The I would created a new class called .drop and use JavaScript to toggle this new class on and off the ul. See both sets of amended code below and here is a JSFiddle link to the working solution - https://jsfiddle.net/2vqp39nd/2/

CSS Changes -

.menu ul.active {
    transition: all .5s;
    height:0px;
    overflow:hidden;
  }

  .drop {
  height:170px!important;
  /* Set this at required height */
}

JavaScript Changes -

var ul = document.getElementsByClassName('active')[0],
  btn = document.getElementsByClassName('toggle-nav')[0];

  function dropDown () {
        ul.classList.toggle('drop');
    }

  btn.addEventListener('click',dropDown,false);


问:
SQL: How to make a replace on the field ''
I have a very but tricky question for you guys. So, listen I have a field with spaces and numbers in one of my table columns. The key part is transform the content in a decimal field. The drawback is basically that for some rows I could get something like:

```<code>    ' 1584.00 '
    ' 156546'
    '545.00 '
    '    '
</code>```

So, to clean up my column, I have done a LTRIM and RTRIM so spaces gone. So now for a couple of records where the record were just spaces the new content is ''. Finally I need to convert this result to a decimal.

Issue: The thing is that for field that contend just the spaces the new result is '' and I'm not able to apply a REPLACE on this because it's a blank and the code below doesn't work:

```<code>SELECT REPLACE('','','0')

-- Final current verison
SELECT CAST(COALESCE(REPLACE(REPLACE([Gross_Weight],' ','0'),',',''),'0') AS DECIMAL(13,3))
</code>```

How could I figure it out?

thanks so much

答:
I presume your data is in a table.
Lets call this table 'DATA' and the column 'VALUE'
Then you might use the below query

```<code>UPDATE DATA SET VALUE = 0 where VALUE = ''
</code>```

To select the value do the below

```<code>select case  ltrim(rtrim([Gross_Weight])) when ''
   THEN 0
   ELSE ltrim(rtrim([Gross_Weight])) END
</code>```

Let me know if i get the requirement wrong.

Body:
I have a very but tricky question for you guys. So, listen I have a field with spaces and numbers in one of my table columns. The key part is transform the content in a decimal field. The drawback is basically that for some rows I could get something like:

    ' 1584.00 '
    ' 156546'
    '545.00 '
    '    '

So, to clean up my column, I have done a LTRIM and RTRIM so spaces gone. So now for a couple of records where the record were just spaces the new content is ''. Finally I need to convert this result to a decimal.

Issue: The thing is that for field that contend just the spaces the new result is '' and I'm not able to apply a REPLACE on this because it's a blank and the code below doesn't work:

SELECT REPLACE('','','0')

-- Final current verison
SELECT CAST(COALESCE(REPLACE(REPLACE([Gross_Weight],' ','0'),',',''),'0') AS DECIMAL(13,3))

How could I figure it out?

thanks so much

Body:
I presume your data is in a table.
Lets call this table 'DATA' and the column 'VALUE'
Then you might use the below query

UPDATE DATA SET VALUE = 0 where VALUE = ''

To select the value do the below

select case  ltrim(rtrim([Gross_Weight])) when ''
   THEN 0
   ELSE ltrim(rtrim([Gross_Weight])) END

Let me know if i get the requirement wrong.


问:
How to add a where clause to a Hibernate @OneToMany explicit join table entity?
Given two entities:

Card

PurchaseProductGroup, which has a ppg_status column (field named as status on the entity) that can be 'A' (active) or 'D' (deleted)

These conceptually have a many-to-many relationship but an explicitly defined join table entity named PurchaseProductGroupCard is used (so an external ID can be assigned for each mapping). So both Card and PurchaseProductGroup have a @OneToMany relationship to PurchaseProductGroupCard, e.g. in Card there is the following:

```<code>@OneToMany(mappedBy = "card")
private Set<PurchaseProductGroupCard> purchaseProductGroups;
</code>```

This needs to be restricted so that purchaseProductGroups with a status of 'D' are excluded. One approach that seems to work is to put a @Where annotation just below the @OneToMany:

```<code>@Where(clause = "exists (select * from purchase_product_group ppg
                         where ppg.ppg_id = ppg_id AND ppg.ppg_status <> 'D')")
</code>```

...But is there a better way to do this? Would ideally prefer Hibernate to join the tables and have a clause like "purchaseProduct.status <> 'D'").

答:
I turned on SQL logging and examined the query output. For the above case it was this:

```<code>/* load one-to-many com.prepaytec.pacasso.common.model.Card.purchaseProductGroups */
select
    * /* the actual field list has been omitted for brevity */
from
    pacasso.purchaseprodgrp_card purchasepr0_
inner join
    pacasso.purchase_product_group purchasepr1_
        on purchasepr0_.ppg_id=purchasepr1_.ppg_id
where
    (
        exists (
            select
                *
            from
                purchase_product_group ppg
            where
                ppg.ppg_id = purchasepr0_.ppg_id
                AND ppg.ppg_status <> 'D'
        )
    )
    and purchasepr0_.crd_id=?
</code>```

So the necessary join is already included and it looks like all that would be needed is this:

```<code>@Where(clause = "ppg_status <> 'D'")
</code>```

However, it turns out that doesn't work as Hibernate prepends the wrong table alias:

```<code>where
    (
        purchasepr0_.ppg_status <> 'D'
    )
    and purchasepr0_.crd_id=?
</code>```

Unfortunately once an alias is assigned to a table, it isn't possible to use the original table name - so purchase_product_group.ppg_status <> 'D' wouldn't work. And I'm not aware of a way to determine the alias name used by Hibernate programmatically - so at present the choice seems to be either hard-code the alias name that is found to be used by Hibernate (i.e. purchasepr1_.ppg_status <> 'D') or to use the exists method described in the question.

UPDATE: On further investigation it turns out that hard-coding the alias names isn't always workable. Here is a criteria query where this wouldn't work:

```<code>/* criteria query */
select
    * /* the actual field list has been omitted for brevity */
from
    pacasso.merchant_acquirer this_
left outer join
    pacasso.purchaseprod_merchant_acquirer purchasepr2_
        on this_.mac_id=purchasepr2_.mac_id
        and (
            // This wouldn't work with any alias since the required
            // table is pacasso.purchase_product purchasepr3_, which
            // is joined below.
            purchasepr2_.ppr_status <> 'D'
        )
left outer join
    pacasso.purchase_product purchasepr3_
        on purchasepr2_.ppr_id=purchasepr3_.ppr_id
where
    this_.mac_code=?
    and this_.cst_id=?
</code>```

In the end I abandoned the @Where approach and used @Filter instead, which seems much better as it can accept HQL rather than database field names and when applied at the entity level will affect relationships (unlike @Where).

Body:
Given two entities:

Card

PurchaseProductGroup, which has a ppg_status column (field named as status on the entity) that can be 'A' (active) or 'D' (deleted)

These conceptually have a many-to-many relationship but an explicitly defined join table entity named PurchaseProductGroupCard is used (so an external ID can be assigned for each mapping). So both Card and PurchaseProductGroup have a @OneToMany relationship to PurchaseProductGroupCard, e.g. in Card there is the following:

@OneToMany(mappedBy = "card")
private Set<PurchaseProductGroupCard> purchaseProductGroups;

This needs to be restricted so that purchaseProductGroups with a status of 'D' are excluded. One approach that seems to work is to put a @Where annotation just below the @OneToMany:

@Where(clause = "exists (select * from purchase_product_group ppg
                         where ppg.ppg_id = ppg_id AND ppg.ppg_status <> 'D')")

...But is there a better way to do this? Would ideally prefer Hibernate to join the tables and have a clause like "purchaseProduct.status <> 'D'").

Body:
I turned on SQL logging and examined the query output. For the above case it was this:

/* load one-to-many com.prepaytec.pacasso.common.model.Card.purchaseProductGroups */
select
    * /* the actual field list has been omitted for brevity */
from
    pacasso.purchaseprodgrp_card purchasepr0_
inner join
    pacasso.purchase_product_group purchasepr1_
        on purchasepr0_.ppg_id=purchasepr1_.ppg_id
where
    (
        exists (
            select
                *
            from
                purchase_product_group ppg
            where
                ppg.ppg_id = purchasepr0_.ppg_id
                AND ppg.ppg_status <> 'D'
        )
    )
    and purchasepr0_.crd_id=?

So the necessary join is already included and it looks like all that would be needed is this:

@Where(clause = "ppg_status <> 'D'")

However, it turns out that doesn't work as Hibernate prepends the wrong table alias:

where
    (
        purchasepr0_.ppg_status <> 'D'
    )
    and purchasepr0_.crd_id=?

Unfortunately once an alias is assigned to a table, it isn't possible to use the original table name - so purchase_product_group.ppg_status <> 'D' wouldn't work. And I'm not aware of a way to determine the alias name used by Hibernate programmatically - so at present the choice seems to be either hard-code the alias name that is found to be used by Hibernate (i.e. purchasepr1_.ppg_status <> 'D') or to use the exists method described in the question.

UPDATE: On further investigation it turns out that hard-coding the alias names isn't always workable. Here is a criteria query where this wouldn't work:

/* criteria query */
select
    * /* the actual field list has been omitted for brevity */
from
    pacasso.merchant_acquirer this_
left outer join
    pacasso.purchaseprod_merchant_acquirer purchasepr2_
        on this_.mac_id=purchasepr2_.mac_id
        and (
            // This wouldn't work with any alias since the required
            // table is pacasso.purchase_product purchasepr3_, which
            // is joined below.
            purchasepr2_.ppr_status <> 'D'
        )
left outer join
    pacasso.purchase_product purchasepr3_
        on purchasepr2_.ppr_id=purchasepr3_.ppr_id
where
    this_.mac_code=?
    and this_.cst_id=?

In the end I abandoned the @Where approach and used @Filter instead, which seems much better as it can accept HQL rather than database field names and when applied at the entity level will affect relationships (unlike @Where).


问:
Make product purchasable when price is zero 0
I have some products that have a price of 0. By default woocommerce makes these product non-purchasable. I need customers to be able to select their quantity and add to cart for all products site wide.

I found this code snippet and thought it should work but it's not . What am i missing here?

```<code>add_filter( 'woocommerce_is_purchasable', 'wpa_109409_is_purchasable', 10, 2 );

function wpa_109409_is_purchasable( $purchasable, $product ){
    if( $product->get_price() == 0 )
        $purchasable = false;
    return $purchasable;
}
</code>```

答:
Without having been able to look at the entire sourcecode im not certain if this will work

but you could try this:

```<code>add_filter( 'woocommerce_is_purchasable', 'wpa_109409_is_purchasable', 10, 2 );

function wpa_109409_is_purchasable( $purchasable, $product ){
    if( $product->get_price() >= 0 )
        $purchasable = true;
    return $purchasable;
}
</code>```

Body:
I have some products that have a price of 0. By default woocommerce makes these product non-purchasable. I need customers to be able to select their quantity and add to cart for all products site wide.

I found this code snippet and thought it should work but it's not . What am i missing here?

add_filter( 'woocommerce_is_purchasable', 'wpa_109409_is_purchasable', 10, 2 );

function wpa_109409_is_purchasable( $purchasable, $product ){
    if( $product->get_price() == 0 )
        $purchasable = false;
    return $purchasable;
}

Body:
Without having been able to look at the entire sourcecode im not certain if this will work

but you could try this:

add_filter( 'woocommerce_is_purchasable', 'wpa_109409_is_purchasable', 10, 2 );

function wpa_109409_is_purchasable( $purchasable, $product ){
    if( $product->get_price() >= 0 )
        $purchasable = true;
    return $purchasable;
}


问:
Java equivalent of Perl's hash
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

```<code>$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}
</code>```

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

答:
I've been using a lot Perl hashes due to super flexibility and convenient. for instance, in Perl I can do the following:
      $hash{AREA_CODE}->{PHONE}->{STREET_ADDR}
  I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

The Java code which approximates the following Perl code:

```<code>my %hash;
$hash{AREA_CODE}{PHONE}{STREET_ADDR} = "221B Baker Street";
printf "Street address is %s\n", $hash{AREA_CODE}{PHONE}{STREET_ADDR};
</code>```

is

```<code>HashMap<String, HashMap<String, HashMap<String, String>>> hash =
    new HashMap<String, HashMap<String, HashMap<String, String>>>();

hash.put("AREA_CODE", new HashMap<String, HashMap<String, String>>());
hash.get("AREA_CODE").put("PHONE", new HashMap<String, String>());
hash.get("AREA_CODE").get("PHONE").put("STREET_ADDR", "221B Baker Street");

System.out.printf("Street address is %s\n",
    hash.get("AREA_CODE").get("PHONE").get("STREET_ADDR"));
</code>```

Isn’t that special? :)

I say ‘approximates’ for many reasons. One of these is that in Java you’ll be frustrated to the point of extreme apoplexy merely for wanting to then  do on the next line of Java the equivalent of this perfectly straightforward Perl code:

```<code>$hash{AREA_CODE}{PREFIX} = 800;
</code>```

If you want Perl’s flexibility and convenience in things like this, Java simply isn’t going to give it to you. Even worse, its partisans will often berate you for even expressing such a desire.

Title: Java equivalent of Perl's hash

Body:
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

Body:
I've been using a lot Perl hashes due to super flexibility and convenient. for instance, in Perl I can do the following:
      $hash{AREA_CODE}->{PHONE}->{STREET_ADDR}
  I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

The Java code which approximates the following Perl code:

my %hash;
$hash{AREA_CODE}{PHONE}{STREET_ADDR} = "221B Baker Street";
printf "Street address is %s\n", $hash{AREA_CODE}{PHONE}{STREET_ADDR};

is

HashMap<String, HashMap<String, HashMap<String, String>>> hash =
    new HashMap<String, HashMap<String, HashMap<String, String>>>();

hash.put("AREA_CODE", new HashMap<String, HashMap<String, String>>());
hash.get("AREA_CODE").put("PHONE", new HashMap<String, String>());
hash.get("AREA_CODE").get("PHONE").put("STREET_ADDR", "221B Baker Street");

System.out.printf("Street address is %s\n",
    hash.get("AREA_CODE").get("PHONE").get("STREET_ADDR"));

Isn’t that special? :)

I say ‘approximates’ for many reasons. One of these is that in Java you’ll be frustrated to the point of extreme apoplexy merely for wanting to then  do on the next line of Java the equivalent of this perfectly straightforward Perl code:

$hash{AREA_CODE}{PREFIX} = 800;

If you want Perl’s flexibility and convenience in things like this, Java simply isn’t going to give it to you. Even worse, its partisans will often berate you for even expressing such a desire.


问:
Error setting dynamic range name using row.count/column.count
This is a problem linked to the following original question: Cannot vlookup range after name change in VBA

My code is now successfully naming my ranges except in one case:

```<code>'Set range for Variance calculation
        StartCell = "$B$5"
        FinalColumn = wb.Sheets("Pivot Data 3 - To Use").Cells(5, Columns.Count).End(xlToLeft).Column - 1
        FinalRow = wb.Sheets("Pivot Data 3 - To Use").Cells(Rows.Count, "B").End(xlDown).Column

        With wb.Names("Variance")
                .RefersTo = "='Pivot Data 3 - To Use'!" & StartCell & ":" & FinalRow & FinalColumn
                .Visible = True
        End With
</code>```

All VBA is telling me is that there is a run time error. When I step through, the code resolves itself to an answer of:

```<code>.RefersTo="='Pivot Data 3 - To Use'!$B$5:$Z$47"
</code>```

but won't apply it to the named range. The code is identical (I copied and pasted) in form to all of the completed assignations so I'm stumped as to why the code falls over here e.g.

```<code>    'Set range name for Key analysis
        With wb.Names("KeyData")
            .RefersTo = "='Pivot Data 3 - To Use'!$A$5" & ":$CM$" & LearnerNumbers + 5
            .Visible = True
        End With
</code>```

This code works fine.

Any help in wrangling this is greatly appreciated!

Thanks,
Steph

答:
When trying to set RefersTo, it looks like the ending range is not actually a range but an integer value. Also it seems like FinalRow always refers to the bottom cell of column B. Was that the intention?

Not knowing how your sheet is setup I can't say for certain how you should approach changing this, but based on your code spinet I would modify by doing something like:

```<code>Dim sht As Worksheet
Dim rngEnd As Range

StartCell = "$B$5"
Set sht = wb.Sheets("Pivot Data 3 - To Use")

Set rngEnd = sht.Range(sht.Cells(5, Columns.Count).End(xlToLeft).Offset(0, -1), sht.Cells(Rows.Count, "B").End(xlDown))
With wb.Names("Variance")
    .RefersTo = "='" & sht.Name & "'!" & StartCell & ":" & rngEnd.Address
    .Visible = True
End With
</code>```

Body:
This is a problem linked to the following original question: Cannot vlookup range after name change in VBA

My code is now successfully naming my ranges except in one case:

'Set range for Variance calculation
        StartCell = "$B$5"
        FinalColumn = wb.Sheets("Pivot Data 3 - To Use").Cells(5, Columns.Count).End(xlToLeft).Column - 1
        FinalRow = wb.Sheets("Pivot Data 3 - To Use").Cells(Rows.Count, "B").End(xlDown).Column

        With wb.Names("Variance")
                .RefersTo = "='Pivot Data 3 - To Use'!" & StartCell & ":" & FinalRow & FinalColumn
                .Visible = True
        End With

All VBA is telling me is that there is a run time error. When I step through, the code resolves itself to an answer of:

.RefersTo="='Pivot Data 3 - To Use'!$B$5:$Z$47"

but won't apply it to the named range. The code is identical (I copied and pasted) in form to all of the completed assignations so I'm stumped as to why the code falls over here e.g.

    'Set range name for Key analysis
        With wb.Names("KeyData")
            .RefersTo = "='Pivot Data 3 - To Use'!$A$5" & ":$CM$" & LearnerNumbers + 5
            .Visible = True
        End With

This code works fine.

Any help in wrangling this is greatly appreciated!

Thanks,
Steph

Body:
When trying to set RefersTo, it looks like the ending range is not actually a range but an integer value. Also it seems like FinalRow always refers to the bottom cell of column B. Was that the intention?

Not knowing how your sheet is setup I can't say for certain how you should approach changing this, but based on your code spinet I would modify by doing something like:

Dim sht As Worksheet
Dim rngEnd As Range

StartCell = "$B$5"
Set sht = wb.Sheets("Pivot Data 3 - To Use")

Set rngEnd = sht.Range(sht.Cells(5, Columns.Count).End(xlToLeft).Offset(0, -1), sht.Cells(Rows.Count, "B").End(xlDown))
With wb.Names("Variance")
    .RefersTo = "='" & sht.Name & "'!" & StartCell & ":" & rngEnd.Address
    .Visible = True
End With


问:
Creating a SQLContext Dataset from an RDD containing arrays of Strings in Spark
So I have a variable data which is a RDD[Array[String]]. I want to iterate over it and compare adjacent elements. To do this I must create a dataset from the RDD.

I try the following, sc is my SparkContext:

```<code>import org.apache.spark.sql.SQLContext

val sqc = new SQLContext(sc)
val lines = sqc.createDataset(data)
</code>```

And I get the two following errors:

Error:(12, 34) Unable to find encoder for type stored in a Dataset.
  Primitive types (Int, String, etc) and Product types (case classes)
  are supported by importing sqlContext.implicits._  Support for
  serializing other types will be added in future releases.
      val lines = sqc.createDataset(data)

Error:(12, 34) not enough arguments for method createDataset:
  (implicit evidence$4:
  org.apache.spark.sql.Encoder[Array[String]])org.apache.spark.sql.Dataset[Array[String]].
  Unspecified value parameter evidence$4.
      val lines = sqc.createDataset(data)

Sure, I understand I need to pass an Encoder argument, however, what would it be in this case and how do I import Encoders? When I try myself it says that createDataset does not take that as argument.

There are similar questions, but they do not answer how to use the encoder argument. If my RDD is a RDD[String] it works perfectly fine, however in this case it is RDD[Array[String]].

答:
All of the comments in the question are trying to tell you the following things

You say you have RDD[Array[String]], which I create by doing the following

```<code>val rdd = sc.parallelize(Seq(Array("a", "b"), Array("d", "e"), Array("g", "f"), Array("e", "r")))   //rdd: org.apache.spark.rdd.RDD[Array[String]] = ParallelCollectionRDD[0] at parallelize at worksheetTest.sc4592:13
</code>```

Now converting the rdd to dataframe is to call .toDF but before that you need to import implicits._ of sqlContext as below

```<code>val sqc = new SQLContext(sc)
import sqc.implicits._
rdd.toDF().show(false)
</code>```

You should have dataframe as

```<code>+------+
|value |
+------+
|[a, b]|
|[d, e]|
|[g, f]|
|[e, r]|
+------+
</code>```

Isn't this all simple?

Body:
So I have a variable data which is a RDD[Array[String]]. I want to iterate over it and compare adjacent elements. To do this I must create a dataset from the RDD.

I try the following, sc is my SparkContext:

import org.apache.spark.sql.SQLContext

val sqc = new SQLContext(sc)
val lines = sqc.createDataset(data)

And I get the two following errors:

Error:(12, 34) Unable to find encoder for type stored in a Dataset.
  Primitive types (Int, String, etc) and Product types (case classes)
  are supported by importing sqlContext.implicits._  Support for
  serializing other types will be added in future releases.
      val lines = sqc.createDataset(data)

Error:(12, 34) not enough arguments for method createDataset:
  (implicit evidence$4:
  org.apache.spark.sql.Encoder[Array[String]])org.apache.spark.sql.Dataset[Array[String]].
  Unspecified value parameter evidence$4.
      val lines = sqc.createDataset(data)

Sure, I understand I need to pass an Encoder argument, however, what would it be in this case and how do I import Encoders? When I try myself it says that createDataset does not take that as argument.

There are similar questions, but they do not answer how to use the encoder argument. If my RDD is a RDD[String] it works perfectly fine, however in this case it is RDD[Array[String]].

Body:
All of the comments in the question are trying to tell you the following things

You say you have RDD[Array[String]], which I create by doing the following

val rdd = sc.parallelize(Seq(Array("a", "b"), Array("d", "e"), Array("g", "f"), Array("e", "r")))   //rdd: org.apache.spark.rdd.RDD[Array[String]] = ParallelCollectionRDD[0] at parallelize at worksheetTest.sc4592:13

Now converting the rdd to dataframe is to call .toDF but before that you need to import implicits._ of sqlContext as below

val sqc = new SQLContext(sc)
import sqc.implicits._
rdd.toDF().show(false)

You should have dataframe as

+------+
|value |
+------+
|[a, b]|
|[d, e]|
|[g, f]|
|[e, r]|
+------+

Isn't this all simple?


问:
Converting string to int in Turbo C
Good day! Can I ask how to convert a string to int in turbo C.
For example:

```<code>void comp()
{
    FILE *fp;
    int i,x;
    long int deci;
    char bin[8];
    char *str=0;
    char buf[1024];

    fp=fopen("C:\enc.txt","w");

    printf("Enter a text: ");
    scanf("%[^\n]",str);
    init(str);

    for(i=0;i<128;i++)
    {
        if(code[i])
        {
            printf("'%c': %s\n",i, code[i]);
        }
    }
</code>```

I'm making a binary code here with the use of string.

```<code>    encode(str, buf);
    deci=decimal(buf);
    printf("%li", deci);

    fprintf(fp,"%s",deci);

    fclose(fp);

}
</code>```

Here is the function decimal()

```<code>int decimal(long int decimal)
{
    int dc, power;
    power=1;
    ht=0;
    while(decimal>0)
    {
        dc+=decimal%10*power;
        decimal=decimal/10;
        power=power*2;
    }
    return dc;
}
</code>```

Thanks for the responses!

答:
I know, I'm little late, but it will definitely help others.

Use built-in function atoi which is available in stdlib.h

```<code>#include <stdlib.h>
    char a[2]="10";
    int b = atoi(a) + 5;
</code>```

Title: Converting string to int in Turbo C

Body:
Good day! Can I ask how to convert a string to int in turbo C.
For example:

void comp()
{
    FILE *fp;
    int i,x;
    long int deci;
    char bin[8];
    char *str=0;
    char buf[1024];

    fp=fopen("C:\enc.txt","w");

    printf("Enter a text: ");
    scanf("%[^\n]",str);
    init(str);

    for(i=0;i<128;i++)
    {
        if(code[i])
        {
            printf("'%c': %s\n",i, code[i]);
        }
    }

I'm making a binary code here with the use of string.

    encode(str, buf);
    deci=decimal(buf);
    printf("%li", deci);

    fprintf(fp,"%s",deci);

    fclose(fp);

}

Here is the function decimal()

int decimal(long int decimal)
{
    int dc, power;
    power=1;
    ht=0;
    while(decimal>0)
    {
        dc+=decimal%10*power;
        decimal=decimal/10;
        power=power*2;
    }
    return dc;
}

Thanks for the responses!

Body:
I know, I'm little late, but it will definitely help others.

Use built-in function atoi which is available in stdlib.h

#include <stdlib.h>
    char a[2]="10";
    int b = atoi(a) + 5;


问:
How to get data after post json
here is my PHP code

```<code>$response = array();

$user1 = array();
$user1['name'] = 'Tom';
$user1['age'] = '13';

$user2 = array();
$user2['name'] = 'Jack';
$user2['age'] = '20';

$response[] = $user1;
$response[] = $user2;

echo json_encode($response);
</code>```

and here is my .html file that use jquery to get data from PHP file like

```<code>$.post('file.php', {userid : '1234'}, function(data){
   alert(data) //problem here
}, 'json');
</code>```

the problem is how to get user1's name after I use $.post in that code.

Thank you :)

答:
I think you need JSON.parse

var response = JSON.parse(data)

Now response is your JSON object that has all the data.

Title: How to get data after post json

Body:
here is my PHP code

$response = array();

$user1 = array();
$user1['name'] = 'Tom';
$user1['age'] = '13';

$user2 = array();
$user2['name'] = 'Jack';
$user2['age'] = '20';

$response[] = $user1;
$response[] = $user2;

echo json_encode($response);

and here is my .html file that use jquery to get data from PHP file like

$.post('file.php', {userid : '1234'}, function(data){
   alert(data) //problem here
}, 'json');

the problem is how to get user1's name after I use $.post in that code.

Thank you :)


问:
Laravel mail: pass string instead of view
I want to send a confirmation e-mail using laravel.
The laravel Mail::send() function only seems to accept a path to a file on the system.
The problem is that my mailtemplates are stored in the database and not in a file on the system.

How can I pass plain content to the email?

Example:

```<code>$content = "Hi,welcome user!";

Mail::send($content,$data,function(){});
</code>```

答:
If you were using mailables. You can do something like this in the build method :

```<code>public function build()
{

    return $this->view('email')
        ->with(['html'=>'This is the message']);
}
</code>```

And you just go ahead and create the blade view email.blade.php in your resource folder.

Then in the blade you can reference your string using laravel blade syntax

      {{$html}}

```
<p>or</p>
<pre class="lang-html prettyprint-override"><code> <html>
    <body>
      {!!$html!!}
    </body>
 </html>
</code>```

If your raw text contains HTML mark up
I hope this works for those who have templates stored in the database and wants to take advantage of the Mailables class in Laravel.

Body:
I want to send a confirmation e-mail using laravel.
The laravel Mail::send() function only seems to accept a path to a file on the system.
The problem is that my mailtemplates are stored in the database and not in a file on the system.

How can I pass plain content to the email?

Example:

$content = "Hi,welcome user!";

Mail::send($content,$data,function(){});

Body:
If you were using mailables. You can do something like this in the build method :

public function build()
{

    return $this->view('email')
        ->with(['html'=>'This is the message']);
}

And you just go ahead and create the blade view email.blade.php in your resource folder.

Then in the blade you can reference your string using laravel blade syntax

 <html>
    <body>
      {{$html}}
    </body>
  </html>

or

 <html>
    <body>
      {!!$html!!}
    </body>
 </html>

If your raw text contains HTML mark up
I hope this works for those who have templates stored in the database and wants to take advantage of the Mailables class in Laravel.

ContentLicense: CC BY-SA 4.0


问:
Data to save in Yii not working
I tried to save these test data into the database if the record haven't exist yet. But when I try to create new record, it returns fail. I'm not sure what's wrong.

This is the code to check whether the registration id exist or not:

```<code>public static function getEventRegistration($registration_code)
{
    $model = EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
        if($model!==null)
        return $model;
}
</code>```

This is the code to save the new record:

```<code>public function actionEventReg()
{
    $tmps = HUB::getEventRegistration('999881');
    if(empty($tmps)){
        // echo 'record does not exist';

        //create new registration
        $object = new EventRegistration;
        $object->event_code = '206218';
        $object->event_vendor_code = 'bizzabo';
        $object->registration_code = '0123456';
        $object->full_name = 'test rifff';
        $object->first_name = 'test';
        $object->last_name = 'rifff';
        $object->email = 'rifhan@mymagic.my';
        $object->phone = '';
        $object->organization = '';
        $object->gender = '';
        $object->age_group = '';
        $object->where_found = '';
        $object->persona = '';
        $object->paid_fee = '';
        $object->is_attended = '';
        $object->date_registered = '';
        $object->date_payment = '';
        $object->json_original = '';
        $object->date_added = time();
        $object->date_modified = time();

        if($object->save()){
            $success = 'success';
        }else{
            $fail = 'fail';
        }
        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationNotExist-'.time();
        $junk->content = sprintf('successfully insert data: %s or (%s). With first name is %s and last name is %s', $success, $fail, $object->first_name, $object->last_name);
        $junk->save();
    }else{
        // echo 'record exist';

        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationExist-'.time();
        $junk->content = sprintf('called on: %s with first name is %s and last name is %s', Yii::app()->params['masterDomain'], $tmps->first_name, $tmps->last_name);
        $junk->save();
    }
}
</code>```

UPDATE:

I change the code like Yupik adviced to dump the error like below :

```<code>public function actionBizzaboCallback()
{
    $junk = new Junk;
    $junk->code = 'bizzabo-bizzaboCallback-'.time();

    $junk->content .= serialize($_POST);

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // fetch RAW input
        $json = file_get_contents('php://input');

        // decode json
        $objects = json_decode($json);

        // expecting valid json
        if (json_last_error() !== JSON_ERROR_NONE) {
            die(header('HTTP/1.0 415 Unsupported Media Type'));
        } else {
            // check if registration exist
            $tmps = HUB::getEventRegistrationByID($objects->details->items[0]->ticketId);

                if(empty($tmps)){
                    //1. echo 'record does not exist';

                    //2. create new registration
                    $object = new EventRegistration;
                    $object->event_code = $objects->eventId;
                    $object->event_vendor_code = 'bizzabo';
                    $object->registration_code = $objects->details->items[0]->ticketId;

                    $object->full_name = sprintf('%s %s', $objects->details->items[0]->registrationForm->firstName, $objects->details->items[0]->registrationForm->lastName);

                    $object->first_name = $objects->details->items[0]->registrationForm->firstName;
                    $object->last_name = $objects->details->items[0]->registrationForm->lastName;
                    $object->email = $objects->details->items[0]->registrationForm->email;

                    $object->phone = 'null';
                    // $object->phone = $objects->details->items[0]->registrationForm->mobileNumber;
                    $object->organization = 'null';
                    //$object->organization = $objects->details->items[0]->registrationForm->organisation__instit;

                    $object->gender = 'unknown';
                     if(isset($objects->details->items[0]->registrationForm->gender))
                     {
                        if(stristr($objects->details->items[0]->registrationForm->gender, 'female'))
                        {
                            $gender = 'female';
                        }
                        else
                        {
                            if(stristr($objects->details->items[0]->registrationForm->gender, 'male'))
                            {
                                $gender = 'male';
                            }
                        }
                    }

                    $object->age_group = $objects->details->items[0]->registrationForm->age_group;

                    $object->where_found = $objects->details->items[0]->registrationForm->how_did_you_hear_abo;

                    $object->persona = $objects->details->items[0]->registrationForm->type_of_person;

                    $object->paid_fee = $objects->details->items[0]->registrationForm->ticketPaid;

                    $object->date_registered = $objects->details->items[0]->registrationForm->created;

                    $object->date_payment = $objects->details->items[0]->registrationForm->created;

                    $object->json_original = $json;

                    $object->date_added = time();
                    $object->date_modified = time();

                    if($object->save()){
                        $success = 'success';
                    }else{
                        var_dump($object->getErrors());
                        $fail = 'fail';
                    }

                    //3. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationIntoDB-'.time();
                    $junk->content = sprintf('ticket id: %s does not exist. %s into database.', $objects->details->items[0]->ticketId, $fail);

                }else{
                    //1. echo 'record exist';

                    //2. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationExisted-'.time();
                    $junk->content = sprintf('ticket id: %s does exist. Did not update into database.',$objects->details->items[0]->ticketId);
                }
            $junk->content .= sprintf('Get error : %s ', $object->getErrors());
        }
    }
    $junk->save();
}
</code>```

But when I try to print $object->getErrors() in junk file, it displayed Array

答:
try check validation properly </p>

```<code>......
}else{

    $junk = new Junk;
    $junk->code = 'test-getRegistrationExist-'.time();
    $junk->content = sprintf('called on: %s with first name is %s and last name is %s', Yii::app()->params['masterDomain'], $tmps->first_name, $tmps->last_name);
     if ($junk->validate()) {
         $junk->save();
    } else {
        // validation failed: $errors is an array containing error messages
        var_dump( $junk->errors);
    }

}
</code>```

Title: Data to save in Yii not working

Body:
I tried to save these test data into the database if the record haven't exist yet. But when I try to create new record, it returns fail. I'm not sure what's wrong.

This is the code to check whether the registration id exist or not:

public static function getEventRegistration($registration_code)
{
    $model = EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
        if($model!==null)
        return $model;
}

This is the code to save the new record:

public function actionEventReg()
{
    $tmps = HUB::getEventRegistration('999881');
    if(empty($tmps)){
        // echo 'record does not exist';

        //create new registration
        $object = new EventRegistration;
        $object->event_code = '206218';
        $object->event_vendor_code = 'bizzabo';
        $object->registration_code = '0123456';
        $object->full_name = 'test rifff';
        $object->first_name = 'test';
        $object->last_name = 'rifff';
        $object->email = 'rifhan@mymagic.my';
        $object->phone = '';
        $object->organization = '';
        $object->gender = '';
        $object->age_group = '';
        $object->where_found = '';
        $object->persona = '';
        $object->paid_fee = '';
        $object->is_attended = '';
        $object->date_registered = '';
        $object->date_payment = '';
        $object->json_original = '';
        $object->date_added = time();
        $object->date_modified = time();

        if($object->save()){
            $success = 'success';
        }else{
            $fail = 'fail';
        }
        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationNotExist-'.time();
        $junk->content = sprintf('successfully insert data: %s or (%s). With first name is %s and last name is %s', $success, $fail, $object->first_name, $object->last_name);
        $junk->save();
    }else{
        // echo 'record exist';

        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationExist-'.time();
        $junk->content = sprintf('called on: %s with first name is %s and last name is %s', Yii::app()->params['masterDomain'], $tmps->first_name, $tmps->last_name);
        $junk->save();
    }
}

UPDATE:

I change the code like Yupik adviced to dump the error like below :

public function actionBizzaboCallback()
{
    $junk = new Junk;
    $junk->code = 'bizzabo-bizzaboCallback-'.time();

    $junk->content .= serialize($_POST);

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // fetch RAW input
        $json = file_get_contents('php://input');

        // decode json
        $objects = json_decode($json);

        // expecting valid json
        if (json_last_error() !== JSON_ERROR_NONE) {
            die(header('HTTP/1.0 415 Unsupported Media Type'));
        } else {
            // check if registration exist
            $tmps = HUB::getEventRegistrationByID($objects->details->items[0]->ticketId);

                if(empty($tmps)){
                    //1. echo 'record does not exist';

                    //2. create new registration
                    $object = new EventRegistration;
                    $object->event_code = $objects->eventId;
                    $object->event_vendor_code = 'bizzabo';
                    $object->registration_code = $objects->details->items[0]->ticketId;

                    $object->full_name = sprintf('%s %s', $objects->details->items[0]->registrationForm->firstName, $objects->details->items[0]->registrationForm->lastName);

                    $object->first_name = $objects->details->items[0]->registrationForm->firstName;
                    $object->last_name = $objects->details->items[0]->registrationForm->lastName;
                    $object->email = $objects->details->items[0]->registrationForm->email;

                    $object->phone = 'null';
                    // $object->phone = $objects->details->items[0]->registrationForm->mobileNumber;
                    $object->organization = 'null';
                    //$object->organization = $objects->details->items[0]->registrationForm->organisation__instit;

                    $object->gender = 'unknown';
                     if(isset($objects->details->items[0]->registrationForm->gender))
                     {
                        if(stristr($objects->details->items[0]->registrationForm->gender, 'female'))
                        {
                            $gender = 'female';
                        }
                        else
                        {
                            if(stristr($objects->details->items[0]->registrationForm->gender, 'male'))
                            {
                                $gender = 'male';
                            }
                        }
                    }

                    $object->age_group = $objects->details->items[0]->registrationForm->age_group;

                    $object->where_found = $objects->details->items[0]->registrationForm->how_did_you_hear_abo;

                    $object->persona = $objects->details->items[0]->registrationForm->type_of_person;

                    $object->paid_fee = $objects->details->items[0]->registrationForm->ticketPaid;

                    $object->date_registered = $objects->details->items[0]->registrationForm->created;

                    $object->date_payment = $objects->details->items[0]->registrationForm->created;

                    $object->json_original = $json;

                    $object->date_added = time();
                    $object->date_modified = time();

                    if($object->save()){
                        $success = 'success';
                    }else{
                        var_dump($object->getErrors());
                        $fail = 'fail';
                    }

                    //3. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationIntoDB-'.time();
                    $junk->content = sprintf('ticket id: %s does not exist. %s into database.', $objects->details->items[0]->ticketId, $fail);

                }else{
                    //1. echo 'record exist';

                    //2. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationExisted-'.time();
                    $junk->content = sprintf('ticket id: %s does exist. Did not update into database.',$objects->details->items[0]->ticketId);
                }
            $junk->content .= sprintf('Get error : %s ', $object->getErrors());
        }
    }
    $junk->save();
}

But when I try to print $object->getErrors() in junk file, it displayed Array

Body:
try check validation properly

......
}else{

    $junk = new Junk;
    $junk->code = 'test-getRegistrationExist-'.time();
    $junk->content = sprintf('called on: %s with first name is %s and last name is %s', Yii::app()->params['masterDomain'], $tmps->first_name, $tmps->last_name);
     if ($junk->validate()) {
         $junk->save();
    } else {
        // validation failed: $errors is an array containing error messages
        var_dump( $junk->errors);
    }

}


问:
What is the main difference between Inheritance and Polymorphism?
I was presented with this question in an end of module open book exam today and found myself lost. I was reading Head first Javaand both definitions seemed to be exactly the same. I was just wondering what the MAIN difference was for my own piece of mind. I know there are a number of similar questions to this but, none I have seen which provide a definitive answer.

答: inheritance is kind of polymorphism, Exactly in fact inheritance is the dynamic polymorphism. So, when you remove inheritance you can not override anymore.</p>


问:
How to send data from website to popup with executeScript?
Im getting data from website properly but how to send it to popup.js? I tried executeScript's callback but it doesnt work for me.

popup.js

```<code>function getData() {
    chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
        chrome.tabs.executeScript(tabs[0].id,{
            file: 'getdata.js'
        });
    });
}
document.getElementById('clickme').addEventListener('click', getData);

 function loadData() {
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
              chrome.tabs.update(tabs[0].id, {url: tabs[0].url});
                chrome.tabs.executeScript(tabs[0].id,{
                    file: 'loaddata.js'
              });
             });
          }

document.getElementById('clickme2').addEventListener('click', loadData);
</code>```

getdata.js

```<code>var div = document.querySelectorAll('div');
var array = [];
div.forEach(function(item) {
    item.getAttribute('data');
    array.push(item.getAttribute('data'));
});
console.log(array);
</code>```

loaddata.js

```<code>         var div = document.querySelectorAll('div');
              div.forEach(function(item, i){
                            item.setAttribute('data', array[i]);
                        });
</code>```

manifest.json

```<code>{
    "manifest_version": 2,
    "name": "aa",
    "description": "bb",
    "version": "1.0",
    "icons": {
        "48": "icon.png"
    },
    "permissions": ["tabs", "<all_urls>", "contentSettings", "contextMenus", "unlimitedStorage"],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "content_scripts": [
        {
            "js": ["jquery-3.2.1.min.js", "popup.js"]
        }
    }
}
</code>```

EDIT:
1. Getting data works with executeScript after adding array; at the end of getdata.js.

How to send an array; from popup.js/getdata.js to loaddata.js?

答:
According to the documentation,

"The result of the script is the last evaluated statement"

So, use the callback of executeScript, but instead of using console.log(array) in your getdata.js, try adding just a single line:

```<code>array;
</code>```

as the very last line.

Body:
Im getting data from website properly but how to send it to popup.js? I tried executeScript's callback but it doesnt work for me.

popup.js

function getData() {
    chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
        chrome.tabs.executeScript(tabs[0].id,{
            file: 'getdata.js'
        });
    });
}
document.getElementById('clickme').addEventListener('click', getData);

 function loadData() {
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
              chrome.tabs.update(tabs[0].id, {url: tabs[0].url});
                chrome.tabs.executeScript(tabs[0].id,{
                    file: 'loaddata.js'
              });
             });
          }

document.getElementById('clickme2').addEventListener('click', loadData);

getdata.js

var div = document.querySelectorAll('div');
var array = [];
div.forEach(function(item) {
    item.getAttribute('data');
    array.push(item.getAttribute('data'));
});
console.log(array);

loaddata.js

         var div = document.querySelectorAll('div');
              div.forEach(function(item, i){
                            item.setAttribute('data', array[i]);
                        });

manifest.json

{
    "manifest_version": 2,
    "name": "aa",
    "description": "bb",
    "version": "1.0",
    "icons": {
        "48": "icon.png"
    },
    "permissions": ["tabs", "<all_urls>", "contentSettings", "contextMenus", "unlimitedStorage"],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "content_scripts": [
        {
            "js": ["jquery-3.2.1.min.js", "popup.js"]
        }
    }
}

EDIT:
1. Getting data works with executeScript after adding array; at the end of getdata.js.

How to send an array; from popup.js/getdata.js to loaddata.js?

Body:
According to the documentation,

"The result of the script is the last evaluated statement"

So, use the callback of executeScript, but instead of using console.log(array) in your getdata.js, try adding just a single line:

array;

as the very last line.


问:
What's the difference between categories and tags in Jekyll?
Both of their elements can be accessed by for..in, and the way of adding categories and tags are the same. So, what's the difference between categories and tags in Jekyll?

答:
From the documentation:

Instead of placing posts inside of folders, you can specify one or more categories that the post belongs to. When the site is generated the post will act as though it had been set with these categories normally. Categories (plural key) can be specified as a YAML list or a space-separated string.

Similar to categories, one or multiple tags can be added to a post. Also like categories, tags can be specified as a YAML list or a space-separated string.

That only suggests similarities; it doesn't really explain the differences between categories and tags. This video tutorial suggests that:

the only difference between the two of them is that categories can be reflected in the permalinks of your posts.

It goes on to explain that

they can also be hierarchical in nature, but that means, for example, if you came up with a category of food you could come up with a category of cupcakes, which is sort of a subcategory to food. Tags, on the other hand, are flat. They're non-hierarchical in nature

and that

Jekyll really doesn't have any automated means of generating archive pages or content pages based off of those tags and categories.

Support for that kind of thing would be implemented in the theme you're using or you could do it yourself.