问:
How does boost::serialization allocate memory when deserializing through a pointer?
In short, I'd like to know how boost::serialization allocates memory for an object when deserializing through a pointer. Below, you'll find an example of my question, clearly illustrated alongside companion code. This code should be fully functional and compile fine, there are no errors, per se, just a question on how the code actually works.

```<code>#include <cstddef> // NULL
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

class non_default_constructor; // Forward declaration for boost serialization namespacing below

// In order to "teach" boost how to save and load your class with a non-default-constructor, you must override these functions
// in the boost::serialization namespace. Prototype them here.
namespace boost { namespace serialization {
    template<class Archive>
    inline void save_construct_data(Archive& ar, const non_default_constructor* ndc, const unsigned int version);
    template<class Archive>
    inline void load_construct_data(Archive& ar, non_default_constructor* ndc, const unsigned int version);
}}

// Here is the actual class definition with no default constructor
class non_default_constructor
{
public:
    explicit non_default_constructor(std::string initial)
    : some_initial_value{initial}, state{0}
    {

    }

    std::string get_initial_value() const { return some_initial_value; } // For save_construct_data

private:
    std::string some_initial_value;
    int state;

    // Notice that we only serialize state here, not the
    // some_initial_value passed into the ctor
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        std::cout << "serialize called" << std::endl;
        ar & state;
    }
};

// Define the save and load overides here.
namespace boost { namespace serialization {
    template<class Archive>
    inline void save_construct_data(Archive& ar, const non_default_constructor* ndc, const unsigned int version)
    {
        std::cout << "save_construct_data called." << std::endl;
        ar << ndc->get_initial_value();
    }
    template<class Archive>
    inline void load_construct_data(Archive& ar, non_default_constructor* ndc, const unsigned int version)
    {
        std::cout << "load_construct_data called." << std::endl;
        std::string some_initial_value;
        ar >> some_initial_value;

        // Use placement new to construct a non_default_constructor class at the address of ndc
        ::new(ndc)non_default_constructor(some_initial_value);
    }
}}

int main(int argc, char *argv[])
{

    // Now lets say that we want to save and load a non_default_constructor class through a pointer.

    non_default_constructor* my_non_default_constructor = new non_default_constructor{"initial value"};

    std::ofstream outputStream("non_default_constructor.dat");
    boost::archive::text_oarchive outputArchive(outputStream);
    outputArchive << my_non_default_constructor;

    outputStream.close();

    // The above is all fine and dandy. We've serialized an object through a pointer.
    // non_default_constructor will call save_construct_data then will call serialize()

    // The output archive file will look exactly like this:

    /*
        22 serialization::archive 17 0 1 0
        0 13 initial value 0
    */

    /*If I want to load that class back into an object at a later time
    I'd declare a pointer to a non_default_constructor */
    non_default_constructor* load_from_archive;

    // Notice load_from_archive was not initialized with any value. It doesn't make
    // sense to intialize it with a value, because we're trying to load from
    // a file, not create a whole new object with "new".

    std::ifstream inputStream("non_default_constructor.dat");
    boost::archive::text_iarchive inputArchive(inputStream);

    // <><><> HERE IS WHERE I'M CONFUSED <><><>
    inputArchive >> load_from_archive;

    // The above should call load_construct_data which will attempt to
    // construct a non_default_constructor object at the address of
    // load_from_archive, but HOW DOES IT KNOW HOW MUCH MEMORY A NON_DEFAULT_CONSTRUCTOR
    // class uses?? Placement new just constructs at the address, assuming
    // memory at the passed address has been allocated for construction.

    // So my question is this:
    // I want to verify that *something* is (or isn't) allocating memory for a non_default_constructor
    // class to be constructed at the address of load_from_archive.

    std::cout << load_from_archive->get_initial_value() << std::endl; // This works.

    return 0;

}
</code>```

Per the boost::serialization documentation when a class with a non-default constructor is to be (de)serialized, the load/save_construct_data is used, but I'm not actually seeing a place where memory is being allocated for the object to be loaded into, just where placement new is constructing an object at a memory address. But what allocated the memory at that address?

It's probably a misunderstanding with how this line works:

::new(ndc)non_default_constructor(some_initial_value);

but I'd like to know where my misunderstanding lies. This is my first question, so I apologize if I've made some sort of mistake on how I've asked my question. Thanks for your time.

答:
That's one excellent example program, with very apt comments. Let's dig in.

```<code>// In order to "teach" boost how to save and load your class with a
// non-default-constructor, you must override these functions in the
// boost::serialization namespace. Prototype them here.
</code>```

You don't have to. Any overload (not override) accessible via ADL suffices, apart from the in-class option.

Skipping to the meat of it:

```<code>// So my question is this: I want to verify that *something* is (or isn't)
// allocating memory for a non_default_constructor
// class to be constructed at the address of load_from_archive.
</code>```

Yes. The documentation states this. But it's a little bit trickier, because it's conditional. The reason is object tracking. Say, we serialize multiple pointers to the same object, they will get serialized once.

On deserialization, the objects will be represented in the archive stream with the object tracking-id. Only the first instance will lead to allocation.

See documentation.

Here's a simplified counter-example:

demonstrating ADL

demonstrating Object Tracking

removing all forward declarations (they're unnecessary due to template POI)

It serializes a vector with 10 copies of the pointer. I used unique_ptr to avoid leaking the instances (both the one manually created in main, as well as the one created by the deserialization).

Live On Coliru

```<code>#include <iomanip>
#include <iostream>
#include <fstream>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/vector.hpp>

namespace mylib {
    // Here is the actual class definition with no default constructor
    class non_default_constructor {
      public:
        explicit non_default_constructor(std::string initial)
                : some_initial_value{ initial }, state{ 0 } {}

        std::string get_initial_value() const {
            return some_initial_value;
        } // For save_construct_data

      private:
        std::string some_initial_value;
        int state;

        // Notice that we only serialize state here, not the some_initial_value
        // passed into the ctor
        friend class boost::serialization::access;
        template <class Archive> void serialize(Archive& ar, unsigned) {
            std::cout << "serialize called" << std::endl;
            ar& state;
        }
    };

    // Define the save and load overides here.
    template<class Archive>
    inline void save_construct_data(Archive& ar, const non_default_constructor* ndc, unsigned)
    {
        std::cout << "save_construct_data called." << std::endl;
        ar << ndc->get_initial_value();
    }
    template<class Archive>
    inline void load_construct_data(Archive& ar, non_default_constructor* ndc, unsigned)
    {
        std::cout << "load_construct_data called." << std::endl;
        std::string some_initial_value;
        ar >> some_initial_value;

        // Use placement new to construct a non_default_constructor class at the address of ndc
        ::new(ndc)non_default_constructor(some_initial_value);
    }
}

int main() {
    using NDC = mylib::non_default_constructor;
    auto owned = std::make_unique<NDC>("initial value");

    {
        std::ofstream outputStream("vector.dat");
        boost::archive::text_oarchive outputArchive(outputStream);

        // serialize 10 copues, for fun
        std::vector v(10, owned.get());
        outputArchive << v;
    }

    /*
        22 serialization::archive 17 0 0 10 0 1 1 0
        0 13 initial value 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
    */

    std::vector<NDC*> restore;

    {
        std::ifstream inputStream("vector.dat");
        boost::archive::text_iarchive inputArchive(inputStream);

        inputArchive >> restore;
    }

    std::unique_ptr<NDC> take_ownership(restore.front());
    for (auto& el : restore) {
        assert(el == take_ownership.get());
    }

    std::cout << "restored: " << restore.size() << " copies with " <<
        std::quoted(take_ownership->get_initial_value()) << "\n";
}
</code>```

Prints

```<code>save_construct_data called.
serialize called
load_construct_data called.
serialize called
restored: 10 copies with "initial value"
</code>```

The vector.dat file contains:

```<code>22 serialization::archive 17 0 0 10 0 1 1 0
0 13 initial value 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
</code>```

The Library Internals

You shouldn't really care, but you can of course read the source code. Predictably, it's way more involved than you'd naively expect, after all: this is C++.

The library deals with types that have overloaded operator new. In that case it calls T::operator new instead of the globale operator new. It always passes sizeof(T) as you correctly surmised.

The code lives in the exception-safe wrapper: detail/iserializer.hpp

```<code>struct heap_allocation {
    explicit heap_allocation() { m_p = invoke_new(); }
    ~heap_allocation() {
        if (0 != m_p)
            invoke_delete(m_p);
    }
    T* get() const { return m_p; }

    T* release() {
        T* p = m_p;
        m_p = 0;
        return p;
    }

  private:
    T* m_p;
};
</code>```

Yes, this code be simplified a lot with C++11 or later. Also, the NULL-guard in the destructor is redunant for compliant implementations of operator delete.

Now of course, invoke_new and invoke_delete are where it's at. Presenting condensed:

```<code>    static T* invoke_new() {
        typedef typename mpl::eval_if<boost::has_new_operator<T>,
                mpl::identity<has_new_operator>,
                mpl::identity<doesnt_have_new_operator>>::type typex;
        return typex::invoke_new();
    }
    static void invoke_delete(T* t) {
        typedef typename mpl::eval_if<boost::has_new_operator<T>,
                mpl::identity<has_new_operator>,
                mpl::identity<doesnt_have_new_operator>>::type typex;
        typex::invoke_delete(t);
    }
    struct has_new_operator {
        static T* invoke_new() { return static_cast<T*>((T::operator new)(sizeof(T))); }
        static void invoke_delete(T* t) { (operator delete)(t); }
    };
    struct doesnt_have_new_operator {
        static T* invoke_new() { return static_cast<T*>(operator new(sizeof(T))); }
        static void invoke_delete(T* t) { (operator delete)(t); }
    };
</code>```

There's some conditional compilation and verbose comments, so per-use the source code if you want the full picture.

Body:
In short, I'd like to know how boost::serialization allocates memory for an object when deserializing through a pointer. Below, you'll find an example of my question, clearly illustrated alongside companion code. This code should be fully functional and compile fine, there are no errors, per se, just a question on how the code actually works.

#include <cstddef> // NULL
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

class non_default_constructor; // Forward declaration for boost serialization namespacing below

// In order to "teach" boost how to save and load your class with a non-default-constructor, you must override these functions
// in the boost::serialization namespace. Prototype them here.
namespace boost { namespace serialization {
    template<class Archive>
    inline void save_construct_data(Archive& ar, const non_default_constructor* ndc, const unsigned int version);
    template<class Archive>
    inline void load_construct_data(Archive& ar, non_default_constructor* ndc, const unsigned int version);
}}

// Here is the actual class definition with no default constructor
class non_default_constructor
{
public:
    explicit non_default_constructor(std::string initial)
    : some_initial_value{initial}, state{0}
    {

    }

    std::string get_initial_value() const { return some_initial_value; } // For save_construct_data

private:
    std::string some_initial_value;
    int state;

    // Notice that we only serialize state here, not the
    // some_initial_value passed into the ctor
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        std::cout << "serialize called" << std::endl;
        ar & state;
    }
};

// Define the save and load overides here.
namespace boost { namespace serialization {
    template<class Archive>
    inline void save_construct_data(Archive& ar, const non_default_constructor* ndc, const unsigned int version)
    {
        std::cout << "save_construct_data called." << std::endl;
        ar << ndc->get_initial_value();
    }
    template<class Archive>
    inline void load_construct_data(Archive& ar, non_default_constructor* ndc, const unsigned int version)
    {
        std::cout << "load_construct_data called." << std::endl;
        std::string some_initial_value;
        ar >> some_initial_value;

        // Use placement new to construct a non_default_constructor class at the address of ndc
        ::new(ndc)non_default_constructor(some_initial_value);
    }
}}

int main(int argc, char *argv[])
{

    // Now lets say that we want to save and load a non_default_constructor class through a pointer.

    non_default_constructor* my_non_default_constructor = new non_default_constructor{"initial value"};

    std::ofstream outputStream("non_default_constructor.dat");
    boost::archive::text_oarchive outputArchive(outputStream);
    outputArchive << my_non_default_constructor;

    outputStream.close();

    // The above is all fine and dandy. We've serialized an object through a pointer.
    // non_default_constructor will call save_construct_data then will call serialize()

    // The output archive file will look exactly like this:

    /*
        22 serialization::archive 17 0 1 0
        0 13 initial value 0
    */

    /*If I want to load that class back into an object at a later time
    I'd declare a pointer to a non_default_constructor */
    non_default_constructor* load_from_archive;

    // Notice load_from_archive was not initialized with any value. It doesn't make
    // sense to intialize it with a value, because we're trying to load from
    // a file, not create a whole new object with "new".

    std::ifstream inputStream("non_default_constructor.dat");
    boost::archive::text_iarchive inputArchive(inputStream);

    // <><><> HERE IS WHERE I'M CONFUSED <><><>
    inputArchive >> load_from_archive;

    // The above should call load_construct_data which will attempt to
    // construct a non_default_constructor object at the address of
    // load_from_archive, but HOW DOES IT KNOW HOW MUCH MEMORY A NON_DEFAULT_CONSTRUCTOR
    // class uses?? Placement new just constructs at the address, assuming
    // memory at the passed address has been allocated for construction.

    // So my question is this:
    // I want to verify that *something* is (or isn't) allocating memory for a non_default_constructor
    // class to be constructed at the address of load_from_archive.

    std::cout << load_from_archive->get_initial_value() << std::endl; // This works.

    return 0;

}

Per the boost::serialization documentation when a class with a non-default constructor is to be (de)serialized, the load/save_construct_data is used, but I'm not actually seeing a place where memory is being allocated for the object to be loaded into, just where placement new is constructing an object at a memory address. But what allocated the memory at that address?

It's probably a misunderstanding with how this line works:

::new(ndc)non_default_constructor(some_initial_value);

but I'd like to know where my misunderstanding lies. This is my first question, so I apologize if I've made some sort of mistake on how I've asked my question. Thanks for your time.

Body:
That's one excellent example program, with very apt comments. Let's dig in.

// In order to "teach" boost how to save and load your class with a
// non-default-constructor, you must override these functions in the
// boost::serialization namespace. Prototype them here.

You don't have to. Any overload (not override) accessible via ADL suffices, apart from the in-class option.

Skipping to the meat of it:

// So my question is this: I want to verify that *something* is (or isn't)
// allocating memory for a non_default_constructor
// class to be constructed at the address of load_from_archive.

Yes. The documentation states this. But it's a little bit trickier, because it's conditional. The reason is object tracking. Say, we serialize multiple pointers to the same object, they will get serialized once.

On deserialization, the objects will be represented in the archive stream with the object tracking-id. Only the first instance will lead to allocation.

See documentation.

Here's a simplified counter-example:

demonstrating ADL

demonstrating Object Tracking

removing all forward declarations (they're unnecessary due to template POI)

It serializes a vector with 10 copies of the pointer. I used unique_ptr to avoid leaking the instances (both the one manually created in main, as well as the one created by the deserialization).

Live On Coliru

#include <iomanip>
#include <iostream>
#include <fstream>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/vector.hpp>

namespace mylib {
    // Here is the actual class definition with no default constructor
    class non_default_constructor {
      public:
        explicit non_default_constructor(std::string initial)
                : some_initial_value{ initial }, state{ 0 } {}

        std::string get_initial_value() const {
            return some_initial_value;
        } // For save_construct_data

      private:
        std::string some_initial_value;
        int state;

        // Notice that we only serialize state here, not the some_initial_value
        // passed into the ctor
        friend class boost::serialization::access;
        template <class Archive> void serialize(Archive& ar, unsigned) {
            std::cout << "serialize called" << std::endl;
            ar& state;
        }
    };

    // Define the save and load overides here.
    template<class Archive>
    inline void save_construct_data(Archive& ar, const non_default_constructor* ndc, unsigned)
    {
        std::cout << "save_construct_data called." << std::endl;
        ar << ndc->get_initial_value();
    }
    template<class Archive>
    inline void load_construct_data(Archive& ar, non_default_constructor* ndc, unsigned)
    {
        std::cout << "load_construct_data called." << std::endl;
        std::string some_initial_value;
        ar >> some_initial_value;

        // Use placement new to construct a non_default_constructor class at the address of ndc
        ::new(ndc)non_default_constructor(some_initial_value);
    }
}

int main() {
    using NDC = mylib::non_default_constructor;
    auto owned = std::make_unique<NDC>("initial value");

    {
        std::ofstream outputStream("vector.dat");
        boost::archive::text_oarchive outputArchive(outputStream);

        // serialize 10 copues, for fun
        std::vector v(10, owned.get());
        outputArchive << v;
    }

    /*
        22 serialization::archive 17 0 0 10 0 1 1 0
        0 13 initial value 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
    */

    std::vector<NDC*> restore;

    {
        std::ifstream inputStream("vector.dat");
        boost::archive::text_iarchive inputArchive(inputStream);

        inputArchive >> restore;
    }

    std::unique_ptr<NDC> take_ownership(restore.front());
    for (auto& el : restore) {
        assert(el == take_ownership.get());
    }

    std::cout << "restored: " << restore.size() << " copies with " <<
        std::quoted(take_ownership->get_initial_value()) << "\n";
}

Prints

save_construct_data called.
serialize called
load_construct_data called.
serialize called
restored: 10 copies with "initial value"

The vector.dat file contains:

22 serialization::archive 17 0 0 10 0 1 1 0
0 13 initial value 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0

The Library Internals

You shouldn't really care, but you can of course read the source code. Predictably, it's way more involved than you'd naively expect, after all: this is C++.

The library deals with types that have overloaded operator new. In that case it calls T::operator new instead of the globale operator new. It always passes sizeof(T) as you correctly surmised.

The code lives in the exception-safe wrapper: detail/iserializer.hpp

struct heap_allocation {
    explicit heap_allocation() { m_p = invoke_new(); }
    ~heap_allocation() {
        if (0 != m_p)
            invoke_delete(m_p);
    }
    T* get() const { return m_p; }

    T* release() {
        T* p = m_p;
        m_p = 0;
        return p;
    }

  private:
    T* m_p;
};

Yes, this code be simplified a lot with C++11 or later. Also, the NULL-guard in the destructor is redunant for compliant implementations of operator delete.

Now of course, invoke_new and invoke_delete are where it's at. Presenting condensed:

    static T* invoke_new() {
        typedef typename mpl::eval_if<boost::has_new_operator<T>,
                mpl::identity<has_new_operator>,
                mpl::identity<doesnt_have_new_operator>>::type typex;
        return typex::invoke_new();
    }
    static void invoke_delete(T* t) {
        typedef typename mpl::eval_if<boost::has_new_operator<T>,
                mpl::identity<has_new_operator>,
                mpl::identity<doesnt_have_new_operator>>::type typex;
        typex::invoke_delete(t);
    }
    struct has_new_operator {
        static T* invoke_new() { return static_cast<T*>((T::operator new)(sizeof(T))); }
        static void invoke_delete(T* t) { (operator delete)(t); }
    };
    struct doesnt_have_new_operator {
        static T* invoke_new() { return static_cast<T*>(operator new(sizeof(T))); }
        static void invoke_delete(T* t) { (operator delete)(t); }
    };

There's some conditional compilation and verbose comments, so per-use the source code if you want the full picture.


来源: stackexchange

问:
Using for loop to convert colnames in R
I am trying to use for loop c("2000", "2001",..., "2011") to rewrite the following code. Each data frame include variables "emp_01", "emp_02" and so on. To distinguish these variables, I would like to use suffixes "emp_01.2000", "emp_02.2000" and convert "fips" for merge. Could you tell me how to write for loop in this case?</p>

```<code>colnames(df_2000) <- paste(colnames(df_2000), "2000", sep = ".")
df_2000  <-  df_2000 %>%
   rename(fips = fips.2000)
colnames(df_2001) <- paste(colnames(df_2001), "2001", sep = ".")
df_2001  <-  df_2001 %>%
   rename(fips = fips.2001)
...
</code>```

答:
We can use mget to get the objects in a list and then  change the values

```<code>library(dplyr)
library(purrr)
library(stringr)
lst1 <- mget(ls(pattern = '^df_\\d{4}$')) %>%
       map(~ .x %>%
          rename_at(vars(starts_with('fips')), ~ str_remove(., '\\.\\d{4}$')))
</code>```

It is better to keep the objects in the list instead of updating the original objects.  But, if we need

```<code>list2env(lst1, .GlobalEnv)
</code>```

If we need to join all the list elements

```<code>reduce(lst1, full_join, by = 'fips')
</code>```

Or if we consider to join all the data.frame within the list with another dataset 'pop'

```<code>map(lst1, ~ full_join(.x, pop, by = 'fips'))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Using for loop to convert colnames in R

Body:
I am trying to use for loop c("2000", "2001",..., "2011") to rewrite the following code. Each data frame include variables "emp_01", "emp_02" and so on. To distinguish these variables, I would like to use suffixes "emp_01.2000", "emp_02.2000" and convert "fips" for merge. Could you tell me how to write for loop in this case?

colnames(df_2000) <- paste(colnames(df_2000), "2000", sep = ".")
df_2000  <-  df_2000 %>%
   rename(fips = fips.2000)
colnames(df_2001) <- paste(colnames(df_2001), "2001", sep = ".")
df_2001  <-  df_2001 %>%
   rename(fips = fips.2001)
...

Body:
We can use mget to get the objects in a list and then  change the values

library(dplyr)
library(purrr)
library(stringr)
lst1 <- mget(ls(pattern = '^df_\\d{4}$')) %>%
       map(~ .x %>%
          rename_at(vars(starts_with('fips')), ~ str_remove(., '\\.\\d{4}$')))

It is better to keep the objects in the list instead of updating the original objects.  But, if we need

list2env(lst1, .GlobalEnv)

If we need to join all the list elements

reduce(lst1, full_join, by = 'fips')

Or if we consider to join all the data.frame within the list with another dataset 'pop'

map(lst1, ~ full_join(.x, pop, by = 'fips'))


问:
Android OpenGL Coordinates Question
I am trying to understand the basic concepts around the co-ordinates system in OpenGL so I have been making a test application from guides online.

Presently I have drawn a simple Square to the screen, using simple Co-ordinates of:

```<code>          -1.0f,  1.0f, 0.0f,  // 0, Top Left
          -1.0f, -1.0f, 0.0f,  // 1, Bottom Left
           1.0f, -1.0f, 0.0f,  // 2, Bottom Right
           1.0f,  1.0f, 0.0f,  // 3, Top Right
</code>```

In my application I run the following code:

```<code>     GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f, 100.0f);
</code>```

My basic understanding here is that the code is setting the viewing port angle to 45 degrees and the width to height ratio of the window size.

Another thing I am doing is setting the viewing position as -4 units on the Z axis:gl.glTranslatef(0, 0, -4);

This is what the result looks like in Landscape...

And in Portrait...

My questions are:

How does the co-ordinate system work, how many Pixels does one unit represent? How does changing the orientation and width to height ratio effect the equation?

If I wanted to draw a square the size of the screen, with a View Port of 45 degrees and a Viewing position of z-4... how does one figure out the required width and height in units?

答:
I'll try to answer the best I can.

There wouldn't be any reason to change the width to height ratio or 45 degree angle. Doing it the way you have it keeps the things from being stretched horizontally or vertically in an unusual way. Because you are using a perspective view, you have 3D space with depth as apposed to an Orthographic view where there is no depth. In doing glTranslatef(0,0,-4) what you've actually done is changed the MODELVIEW Matix, moving it 4 in the negative z direction, presumably before actually drawing the square. By default, the "camera" is sitting at 0,0,0 with Y (up) as the upward direction.

You may be able to translate 3D space to pixels, but with a Perspective view type, I'm not at all sure you'd really want or need to. A 2D Orthographic view would be a different story, though, as many people use OpenGL for 2D games as well. Wanting a square exactly the size of the screen, Orthographic is probably the way to go, and you should be able to with a few Google searches be able to figure out your pixel density to 2d space comparison.

ContentLicense: CC BY-SA 3.0

Title: Android OpenGL Coordinates Question

Body:
I am trying to understand the basic concepts around the co-ordinates system in OpenGL so I have been making a test application from guides online.

Presently I have drawn a simple Square to the screen, using simple Co-ordinates of:

          -1.0f,  1.0f, 0.0f,  // 0, Top Left
          -1.0f, -1.0f, 0.0f,  // 1, Bottom Left
           1.0f, -1.0f, 0.0f,  // 2, Bottom Right
           1.0f,  1.0f, 0.0f,  // 3, Top Right

In my application I run the following code:

     GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f, 100.0f);

My basic understanding here is that the code is setting the viewing port angle to 45 degrees and the width to height ratio of the window size.

Another thing I am doing is setting the viewing position as -4 units on the Z axis:gl.glTranslatef(0, 0, -4);

This is what the result looks like in Landscape...

And in Portrait...

My questions are:

How does the co-ordinate system work, how many Pixels does one unit represent? How does changing the orientation and width to height ratio effect the equation?

If I wanted to draw a square the size of the screen, with a View Port of 45 degrees and a Viewing position of z-4... how does one figure out the required width and height in units?


问:
Move mails to folders with the sender's name
It is possible to create a rule which, for a sender, moves all the mails to the folder of your choice (for example, it creates a folder with the name of the sender).

If I want that for all the expeditors, I need to repeat the rule creation for each sender.

What I'd wish would be a macro "meta-rule" for each sender to have a folder with their name with the corresponding mails sorted.

I tried to start from the topic Outlook template rule to sort mails among directories.

I wrote this:

```<code>Sub RulesForFolders(m As MailItem)
Dim fldr As Outlook.Folder
For Each fldr In GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders
    if fldr.Name Like m.SenderName Then m.MoveTo(SenderName)
    else folders.add(m.SenderName)
Next
Set fldr = Nothing
End Sub
</code>```

答:
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
'
' If desperate declare as variant

Private Sub RulesForFolders(m As mailItem)

Dim targetFldr As folder
Dim myRoot As folder

Dim i As Long

Set myRoot = Session.GetDefaultFolder(olFolderInbox)
Debug.Print m.senderName

' This is often misused.
On Error Resume Next

' If folder exists the error is bypassed
' This is a rare beneficial use of On Error Resume Next
myRoot.folders.Add m.senderName

' Consider it mandatory to return to normal error handling
On Error GoTo 0

Set targetFldr = myRoot.folders(m.senderName)
m.Move targetFldr

End Sub

Private Sub RulesForFolders_test()

' Code requiring a parameter cannot run independently

Dim selItem As Object

' first select a mailitem
Set selItem = ActiveExplorer.Selection(1)

If selItem.Class = olMail Then
    RulesForFolders ActiveExplorer.Selection(1)
End If

End Sub
```

Body:
It is possible to create a rule which, for a sender, moves all the mails to the folder of your choice (for example, it creates a folder with the name of the sender).

If I want that for all the expeditors, I need to repeat the rule creation for each sender.

What I'd wish would be a macro "meta-rule" for each sender to have a folder with their name with the corresponding mails sorted.

I tried to start from the topic Outlook template rule to sort mails among directories.

I wrote this:

Sub RulesForFolders(m As MailItem)
Dim fldr As Outlook.Folder
For Each fldr In GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders
    if fldr.Name Like m.SenderName Then m.MoveTo(SenderName)
    else folders.add(m.SenderName)
Next
Set fldr = Nothing
End Sub


问:
WEVTUtil Filter from a source
I have been trying to filter the Application log from WEVTUtil in order to view specific log. However, in filtering for event id 1036, there are two separate publishers.
I want to be able to just get the events from MsiInstaller, but cannot for the life of me figure out how to and I can't seem to find anything on this.

```<code>wevtutil qe Application "/q:*[System [(EventID=1036)]] /f:text
</code>```

This is working for me, but it is not showing me the events from MsiInstaller alone. How should I go about this.

答:
A PowerShell alternative is Get-WinEvent.

Example:

Get-WinEvent -FilterHashtable @{LogName="Application";ID=1033;ProviderName='MsiInstaller'}
```

You can set the log name and Event ID as necessary.

Title: WEVTUtil Filter from a source

Body:
I have been trying to filter the Application log from WEVTUtil in order to view specific log. However, in filtering for event id 1036, there are two separate publishers.
I want to be able to just get the events from MsiInstaller, but cannot for the life of me figure out how to and I can't seem to find anything on this.

wevtutil qe Application "/q:*[System [(EventID=1036)]] /f:text

This is working for me, but it is not showing me the events from MsiInstaller alone. How should I go about this.

Body:
A PowerShell alternative is Get-WinEvent.

Example:

Get-WinEvent -FilterHashtable @{LogName="Application";ID=1033;ProviderName='MsiInstaller'}

You can set the log name and Event ID as necessary.


问:
How do I stop local kentico project from taking up port localhost:8080
I installed Kentico and have been going through the tutorial. But I needed to work on another project and when trying to do so I was unable to as the Kentico project seems to be running on the localhost:8080 port.

I would like to restore localhost:8080 back to the way it was.

This is the error that I get when opening localhost:8080
localhost error screenshot

I have tried to enable directory browsing and trying to stop the process running on localhost:8080 but they did not work.

Any help would be much appreciated if anyone has any suggestions or has had to deal with something like this before.

答:
As per the error snapshot (HTTP Error 403.14- Forbidden), it looks like its a access issue for your respective website virtual directory.

To overcome this problem you need to provide IIS user permission and the current system user permission to the kentico website folder and also make sure the path of your project in IIS pointing to Kentico Website solution until root folder where you have a web.config file.

How to give folder permission you can check on this reference link
IIS7 folder permissions for web application

Thanks and Regards

Nikhila Pocha


问:
working of fork in c language
Now I have a problem in understanding the working of fork() system call.
I write a code which is following :

```<code>#include<stdio.h>
int main()
{
    int a, b;
    b=fork();

    printf("\n the value of b = %d",b);
}
</code>```

The output of  this code is following :

Now I don't understand why the output is like this ?

After that i just add a line to my  code and output is completely different.
my code is following:

```<code>int main()
{
    int a, b;
    b=fork();
</code>```

When i run the code the output is following
 2389my name is manish

```<code> the value of b = 0
</code>```

Now I'm totally confused about the working of fork() call.

My question are following:

How fork() works?

Where the control goes after the fork() call?

Can any body explain why the outputs of codes written in problem?

Why the output of b occurring at different places means in first code
the output of b = 2260 is just before the output b = 0 while the value of b = 2389 is not just before the b = 0?

Please explain me the working of fork in the code written in the problem so that I can learn it properly .

答:
Fork creates a copy of your current process.

Both the original and the copy continue executing from the point at which fork() was called.

Because your code is executed twice, your print statements are also evaluated twice. In the copied process, the value of b is 0. In the original process, the value of b is the process ID of the copied process.

Once your processes start running concurrently, they will be scheduled independently by your operating system and thus you have no guarantees about when they will actually be run.

Title: working of fork in c language

Body:
Now I have a problem in understanding the working of fork() system call.
I write a code which is following :

#include<stdio.h>
int main()
{
    int a, b;
    b=fork();

    printf("\n the value of b = %d",b);
}

The output of  this code is following :

Now I don't understand why the output is like this ?

After that i just add a line to my  code and output is completely different.
my code is following:

int main()
{
    int a, b;
    b=fork();

When i run the code the output is following
 2389my name is manish

 the value of b = 0

Now I'm totally confused about the working of fork() call.

My question are following:

How fork() works?

Where the control goes after the fork() call?

Can any body explain why the outputs of codes written in problem?

Why the output of b occurring at different places means in first code
the output of b = 2260 is just before the output b = 0 while the value of b = 2389 is not just before the b = 0?

Please explain me the working of fork in the code written in the problem so that I can learn it properly .


Title: Sliding Window operations across groups in Spark DataFrame with multiple columns

Body:
I have a DataFrame as below:

scala> Seq(("2020-05-21","x",1),("2020-05-21","y",2),("2020-05-22","x",3),("2020-05-22","y",4),("2020-05-23","x",5), ("2020-05-23","y",6)).toDF("dt","A","B")
+----------+---+---+
|        dt|  A|  B|
+----------+---+---+
|2020-05-21|  x|  1|
|2020-05-21|  y|  2|
|2020-05-22|  x|  3|
|2020-05-22|  y|  4|
|2020-05-23|  x|  5|
|2020-05-23|  y|  6|
+----------+---+---+

I am trying to find, for the past 2 days(including current day) the sum of B grouped by A.

In other words: group by A & dt(only current & previous dt) find moving sum of B.

Expected Output:

+----------+---+---+----+
|        dt|  A|  B| sum|
+----------+---+---+----+
|2020-05-21|  x|  1|   1|
|2020-05-21|  y|  2|   2|
|2020-05-22|  x|  3|   4|  // (1 + 3) (i.e: for dt = May 21 & 22, A = x)
|2020-05-22|  y|  4|   6|  // (4 + 2) (i.e: for dt = May 21 & 22, A = y)
|2020-05-23|  x|  5|   8|  // (5 + 3) (i.e: for dt = May 22 & 23, A = x)
|2020-05-23|  y|  6|  10|  // (6 + 4) (i.e: for dt = May 22 & 23, A = y)
+----------+---+---+----+

Tried Window functions with .rowsBetween() like:

res0.withColumn("sum", sum($"B").over(Window.partitionBy($"dt",$"A").rowsBetween(-1,0)))

but this approach will not work as grouping both dt & A will result in only 1 row per group.

Body:
Try this..

val windowFn = Window.partitionBy($"A").orderBy($"dt".asc)
   newDF.withColumn("dummy", lag($"B",1,0).over(windowFn)).withColumn("sum", $"dummy" + $"B").drop($"dummy").orderBy($"dt".asc).show

+----------+---+---+---+
|        dt|  A|  B|sum|
+----------+---+---+---+
|2020-05-21|  x|  1|  1|
|2020-05-21|  y|  2|  2|
|2020-05-22|  x|  3|  4|
|2020-05-22|  y|  4|  6|
|2020-05-23|  x|  5|  8|
|2020-05-23|  y|  6| 10|
+----------+---+---+---+

If any tricky part in your questions , please highlight in bold. that will help to find quickly


问:
Script tag not rendering synchronously
this is the code im working with

```<code><body>

  <script type="text/javascript" src = "http://localhost:3000/common_assets/navbar.js"></script>

  <script type="text/javascript" src = "http://localhost:3000//index.js"></script>

  <h1>MonkaHmm...</h1>

</body>

</code>```

both the scripts render html and they both work the problem is the second script is always rendered last
so the MonkaHmm... comes in at the middle of the page.

this is the code thats in the second script tag

```<code>async function cardData(){
    var response = await fetch('http://localhost:3000/Board_Members.json');
    var carddata =  await response.json();

    carddata.forEach(function(membercard){
      var member_cards = document.createElement("div");
      var code = `
        <div class="member_cards card-4">
          <img class = "img_member" src="http://localhost:3000/IMAGES/jonipic.jpg">
          <div class="description">
            <h5>${membercard.name}</h5>
            <h5>${membercard.title}</h5>
            ${membercard.description}
          </div>

        </div>
        <link rel="stylesheet" type="text/css" href="http://localhost:3000/index.css">
`
      member_cards.innerHTML = code;
      document.body.appendChild(member_cards);
    });
}

cardData();

</code>```

i have a feeling this is happening because of the fetch but its in an async/await function so i thought it would act synchronously but to be honest i have no clue. HELP my fellow pepega coders

答:
When you call cardData() it does invoke the async function and return a promise.  The browser doesn't wait for the response to continue rendering the page.

You could create the member_cards div or a placeholder and append it before you do your async calls and add your cards to it when you get the response.

Title: Script tag not rendering synchronously

Body:
this is the code im working with

MonkaHmm...

both the scripts render html and they both work the problem is the second script is always rendered last
so the MonkaHmm... comes in at the middle of the page.

this is the code thats in the second script tag

async function cardData(){
    var response = await fetch('http://localhost:3000/Board_Members.json');
    var carddata =  await response.json();

    carddata.forEach(function(membercard){
      var member_cards = document.createElement("div");
      var code = `

${membercard.name}

${membercard.title}

            ${membercard.description}

        <link rel="stylesheet" type="text/css" href="http://localhost:3000/index.css">
`
      member_cards.innerHTML = code;
      document.body.appendChild(member_cards);
    });
}

cardData();

i have a feeling this is happening because of the fetch but its in an async/await function so i thought it would act synchronously but to be honest i have no clue. HELP my fellow pepega coders


问:
Passing variables to a page with AJAX and returning those variables in PHP
I'm trying to do something I would think would be really simple:  Pass form data to a PHP page with AJAX, and get the result of the PHP back.

Edited to Add:  As written right now, it only returns successfully sporadically, rather than every time it's run, for some reason.

Edited to Add (05/30/2020):

I was able to get it working such as it is by changing the ajax like this:

```<code><script>
                    $(document).ready(function(){

                        $("#button").click(function(){

                            var DDD_Number=$("#DDD_Number").val();
                            var Manager_Review=$("#Manager_Review").val();
                            var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review;
                            $.ajax({
                                type: "GET",
                                url:'showme.php' + dataTosend,
                                data:dataTosend,
                                async: false,
                              success:function(data){
                                    document.getElementById('txtresponse').innerHTML = "Success.";
                                    document.getElementById('thisworks').innerHTML = data;
                                },
                                error: function(data){
                                   document.getElementById('txtresponse').innerHTML = "failure.";
                               }
                            });
                        });
                    });
            </script>
</code>```

Now I have to work on serializing the form, because it's actually multiple rows I have to pass.  I don't know if I need that as a second question, though.

This is my main page:

```<code><html>
        <head>
            <script src="Scripts/jquery.min.js"></script>
            <script src="Scripts/jquery-2.1.3.min.js"></script>
            <script type="text/javascript" src="Scripts/jquery.plugin.min.js"></script>
            <script type="text/javascript" src="Scripts/jquery.datepick.min.js"></script>
            <script>
                    $(document).ready(function(){

                        $("#button").click(function(){
                            var DDD_Number=$("#DDD_Number").val();
                            var Manager_Review=$("Manager_Review").val();
                            var dataTosend='DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review;
                            $.ajax({
                                type: "POST",
                                url:'showme.php',
                                data:dataTosend,
                                async: true,
                               success:function(data){
                                   document.getElementById('txtresponse').innerHTML = "Success.";
                                   document.getElementById('thisworks').innerHTML = "Successful.";

                               },
                                error: function(data){
                                    console.log(data);
                                   document.getElementById('txtresponse').innerHTML = "failure.";
                                   console.log(data);
                               }
                            });
                        });
                    });
            </script>
        </head>
    <body>
        <form id="dddform" method="post">
            <input type="text" id="DDD_Number" name="DDD_Number"><br>
            <input type="text" id="Manager_Review" name="Manager_Review"><br>
            <button id="button" name="Submit">Click Me</button>
        </form>
        <div id="txtresponse"></div>
        <div id="thisworks"><?php if(!isset($_POST['Submit'])){echo $Manager_Review;} ?></div>

            </div>
    </body>
</html>
</code>```

This is showme.php:

```<code><?php

$Manager_Review_Date = $_POST['Manager_Review'];

echo $Manager_Review_Date;

?>
<script language = 'Javascript'>
    document.getElementById('thisworks').innerHTML = '<?php echo $Manager_Review_Date; ?>';
</script>
</code>```

The call is made successfully.  (The "Success"and "Successful" messages appear), but I can't get the value of $Manager_Review_Date to appear in the "thisworks" DIV.

Any pointers?  I'm fairly new to AJAX (if you couldn't tell from my code).

答:
Your php should be:

```<code><?php
$Manager_Review_Date = $_POST['Manager_Review'];
echo $Manager_Review_Date;
// NO javascript here
</code>```

And the output of this script is in data variable of success callback:

```<code>success:function(data){
    document.getElementById('txtresponse').innerHTML = "Success.";
    document.getElementById('thisworks').innerHTML = data;
},
</code>```

Body:
I'm trying to do something I would think would be really simple:  Pass form data to a PHP page with AJAX, and get the result of the PHP back.

Edited to Add:  As written right now, it only returns successfully sporadically, rather than every time it's run, for some reason.

Edited to Add (05/30/2020):

I was able to get it working such as it is by changing the ajax like this:

Now I have to work on serializing the form, because it's actually multiple rows I have to pass.  I don't know if I need that as a second question, though.

This is my main page:

        <form id="dddform" method="post">
            <input type="text" id="DDD_Number" name="DDD_Number">

            <input type="text" id="Manager_Review" name="Manager_Review">

            <button id="button" name="Submit">Click Me</button>
        </form>

<?php if(!isset($_POST['Submit'])){echo $Manager_Review;} ?>

This is showme.php:

<?php

$Manager_Review_Date = $_POST['Manager_Review'];

echo $Manager_Review_Date;

?>

The call is made successfully.  (The "Success"and "Successful" messages appear), but I can't get the value of $Manager_Review_Date to appear in the "thisworks" DIV.

Any pointers?  I'm fairly new to AJAX (if you couldn't tell from my code).

Body:
Your php should be:

<?php
$Manager_Review_Date = $_POST['Manager_Review'];
echo $Manager_Review_Date;
// NO javascript here

And the output of this script is in data variable of success callback:

success:function(data){
    document.getElementById('txtresponse').innerHTML = "Success.";
    document.getElementById('thisworks').innerHTML = data;
},


问:
Unable to save file as parquet due to error "Files with more than one child are not supported"?
Iḿ using python the anaconda distribution with pyarrow installed. At first, I had a dataset of 166 columns, during my first iteration over the data I had to decompose a lot into dummy variables so it went up to 915 columns, and in the refinement phase, I had to bin some data, therefore, growing to 1880 columns.

Since 915 I was unable to save the file as HDF, so I move into parquet, then during the last phase parquet is failing on me with the legend ArrowNotImplementedError: Fields with more than one child are not supported.

Fortunately, I was able to write it as CSV, but this is taking almost 3gb of space in my drive I would like to know the meaning of this error. columns are so simple either they are categories or binary (numeric) that is all. I have some missing values but iḿ using XGBOOST to train so there is no problem there.

Does anyone know why suddenly by just increasing the number of columns parquet fails to save my file? I have done describe(), info(), and many other operations with no problem, I have even train the xgboost model without saving the data but it takes to long to aggregate all those columns.

data.to_parquet("../data/5_all_data.parquet") => didn't not worked

```<code>ArrowNotImplementedError: Fields with more than one child are not supported.
</code>```

data.to_hdf("../data/5_all_data.h5", key="data") => didn't not worked

```<code>NotImplementedError: Cannot store a category dtype in a HDF5 dataset that uses format="fixed". Use format="table".
</code>```

data.to_csv("../data/5_all_data.csv") => did worked

data.info()

```<code><class 'pandas.core.frame.DataFrame'>
Int64Index: 605847 entries, 630776 to 1049122
Data columns (total 1880 columns):

dtypes: category(118), float64(88), int64(38), uint8(1636)
memory usage: 1.6 GB
</code>```

any help please

答: The problem is the error msg is not helpful here. The real problem IN MY CASE is that there are 2 columns with the exact same name. After changing versions up and down and changing columns types and a bunch of other stuff, all I had to do was rename the columns and I can save into parquet in any version of the package.</p>

Body:
Iḿ using python the anaconda distribution with pyarrow installed. At first, I had a dataset of 166 columns, during my first iteration over the data I had to decompose a lot into dummy variables so it went up to 915 columns, and in the refinement phase, I had to bin some data, therefore, growing to 1880 columns.

Since 915 I was unable to save the file as HDF, so I move into parquet, then during the last phase parquet is failing on me with the legend ArrowNotImplementedError: Fields with more than one child are not supported.

Fortunately, I was able to write it as CSV, but this is taking almost 3gb of space in my drive I would like to know the meaning of this error. columns are so simple either they are categories or binary (numeric) that is all. I have some missing values but iḿ using XGBOOST to train so there is no problem there.

Does anyone know why suddenly by just increasing the number of columns parquet fails to save my file? I have done describe(), info(), and many other operations with no problem, I have even train the xgboost model without saving the data but it takes to long to aggregate all those columns.

data.to_parquet("../data/5_all_data.parquet") => didn't not worked

ArrowNotImplementedError: Fields with more than one child are not supported.

data.to_hdf("../data/5_all_data.h5", key="data") => didn't not worked

NotImplementedError: Cannot store a category dtype in a HDF5 dataset that uses format="fixed". Use format="table".

data.to_csv("../data/5_all_data.csv") => did worked

data.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 605847 entries, 630776 to 1049122
Data columns (total 1880 columns):

dtypes: category(118), float64(88), int64(38), uint8(1636)
memory usage: 1.6 GB

any help please


问:
HTML5 Cache (Manifest) Network Section
i am wondering whats the use of the network section of the HTML5 Cache Manifest?

from offline resource in firefox

The online whitelist may contain zero
  or more URIs of resources that the web
  application will need to access off
  the server rather than the offline
  cache. This lets the browser's
  security model protect the user from
  potential security breaches by
  limiting access only to approved
  resources

i wonder why is this required. won't files not listed in the explicit section of the cache manifest not be cached anyway?

答:
I understand (from reading Dive Into HTML5) that when an application with a manifest attempts to request files from a different domain, it may only do so if they are listed in the NETWORK section. Anything not listed in the network section will appear to be unreachable, even when online. This may be what that quote means by "protect(ing) the user from potential security breaches by limiting access only to approved resources" -- you may make a web application offline to seal it off from the rest of the web and prevent cross-site scripting.

It seems like some weird rules. And it doesn't look like there's much difference between a local file listed in NETWORK and a file not listed at all. (As you say, I don't get why you need to list something in NETWORK to ensure it is requested each time; surely anything not explicitly cached will be requested every time.)

Also I have noticed on Chrome (but not Firefox) that files explicitly listed in NETWORK do not fall back to the offline FALLBACK URLs when offline; they just result in an error. That could just be a quirk of Chrome though.

ContentLicense: CC BY-SA 2.5

Title: HTML5 Cache (Manifest) Network Section


问:
Need to add Spaces at certain Indexes
So this is data i have,

```<code>s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]
</code>```

These are the index position where i need to add spaces,

```<code>d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'
</code>```

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction
```

<p>and so on.....</p>

<p>I have calculated the indexes by doing this,</p>

```s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)
```

<p>When I individually try and add the space using the index, I get an output,</p>

```d[0:s[0]] + ' ' + d[s[0]:]
```

<p>I get the following, which is correct</p>

<pre class="lang-none prettyprint-override"><code>'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube
</code>```

But, when I try and iterate over the indexes, i get List out of Range

```<code>temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range
</code>```

答:
You can do everything in one go using regular expressions, without having to calculate your list of indices first.

First, we separate the short forms and long forms parts, then we add spaces between the words in the long forms.

We get your data in a more structured form than what you want:

```<code>import re

d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

lst = re.findall(r'([A-Z]+)((?:[A-Z][a-z]+)+)', d)
# [('CC', 'CarbonCopy'),
#  ('CAI', 'ComputerAidedInstruction'), ...

lst = [(abbr, re.sub(r'([a-z])(?=[A-Z])', r'\1 ', long)) for abbr, long in lst]
print(lst)
# [('CC', 'Carbon Copy'),
#  ('CAI', 'Computer Aided Instruction'), ...
</code>```

If you really want everything together in a single string, losing that structure:

```<code>joined = ' '.join([item for tup in lst for item in tup])
print(joined)
# CC Carbon Copy CAI Computer Aided Instruction CDMA Code Division Multiple Access ...
</code>```

Title: Need to add Spaces at certain Indexes

Body:
So this is data i have,

s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]

These are the index position where i need to add spaces,

d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction

and so on.....

I have calculated the indexes by doing this,

s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)

When I individually try and add the space using the index, I get an output,

d[0:s[0]] + ' ' + d[s[0]:]

I get the following, which is correct

'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube

But, when I try and iterate over the indexes, i get List out of Range

temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range

Body:
You can do everything in one go using regular expressions, without having to calculate your list of indices first.

First, we separate the short forms and long forms parts, then we add spaces between the words in the long forms.

We get your data in a more structured form than what you want:

import re

d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

lst = re.findall(r'([A-Z]+)((?:[A-Z][a-z]+)+)', d)
# [('CC', 'CarbonCopy'),
#  ('CAI', 'ComputerAidedInstruction'), ...

lst = [(abbr, re.sub(r'([a-z])(?=[A-Z])', r'\1 ', long)) for abbr, long in lst]
print(lst)
# [('CC', 'Carbon Copy'),
#  ('CAI', 'Computer Aided Instruction'), ...

If you really want everything together in a single string, losing that structure:

joined = ' '.join([item for tup in lst for item in tup])
print(joined)
# CC Carbon Copy CAI Computer Aided Instruction CDMA Code Division Multiple Access ...


问:
Filtering patient data - how to return bool/string for patients taking two different medications?
I have a very large data set that contains patient-level information on drug names. I am wanting to find patients that are taking certain combinations of drugs but I am having difficulties finding a simple method without creating two subset dataframes and mapping them back to the original dataframe using R.

Here is a fake patient dataframe in R

```<code>df <- data.frame(pt_id=["p1","p2","p3","p4","p1","p2","p3","p4"],
                 drug=["d1","d1","d1","d1","d2","d2","d3","d3"])
show(df)
##      pt_id     drug
## 1       p1       d1
## 2       p2       d1
## 3       p3       d1
## 4       p4       d1
## 5       p1       d2
## 6       p2       d2
## 7       p3       d3
## 8       p4       d3
</code>```

How do I get the following?

```<code>##      pt_id     drug   drug_combo
## 1       p1       d1         TRUE
## 2       p2       d1         TRUE
## 3       p3       d1        FALSE
## 4       p4       d1        FALSE
## 5       p1       d2         TRUE
## 6       p2       d2         TRUE
## 7       p3       d3        FALSE
## 8       p4       d3        FALSE
</code>```

Where only patients taking "d1" and "d2" (i.e. "p1" and "p2" in this example) are returned TRUE or a per-specified string like "on_d1_d2"

Thank you in advance!

答:
We can use

```<code>library(dplyr)
df %>%
   group_by(pt_id) %>%
   mutate(drug_combo = sum(c('d1', 'd2') %in% drug) == 2)
# A tibble: 8 x 3
# Groups:   pt_id [4]
#  pt_id drug  drug_combo
#  <chr> <chr> <lgl>
#1 p1    d1    TRUE
#2 p2    d1    TRUE
#3 p3    d1    FALSE
#4 p4    d1    FALSE
#5 p1    d2    TRUE
#6 p2    d2    TRUE
#7 p3    d3    FALSE
#8 p4    d3    FALSE
</code>```

Or with data.table

```<code>library(data.table)
setDT(df)[, drug_combo := sum(c('d1', 'd2') %in% drug) == 2, pt_id]
</code>```

Body:
I have a very large data set that contains patient-level information on drug names. I am wanting to find patients that are taking certain combinations of drugs but I am having difficulties finding a simple method without creating two subset dataframes and mapping them back to the original dataframe using R.

Here is a fake patient dataframe in R

df <- data.frame(pt_id=["p1","p2","p3","p4","p1","p2","p3","p4"],
                 drug=["d1","d1","d1","d1","d2","d2","d3","d3"])
show(df)
##      pt_id     drug
## 1       p1       d1
## 2       p2       d1
## 3       p3       d1
## 4       p4       d1
## 5       p1       d2
## 6       p2       d2
## 7       p3       d3
## 8       p4       d3

How do I get the following?

##      pt_id     drug   drug_combo
## 1       p1       d1         TRUE
## 2       p2       d1         TRUE
## 3       p3       d1        FALSE
## 4       p4       d1        FALSE
## 5       p1       d2         TRUE
## 6       p2       d2         TRUE
## 7       p3       d3        FALSE
## 8       p4       d3        FALSE

Where only patients taking "d1" and "d2" (i.e. "p1" and "p2" in this example) are returned TRUE or a per-specified string like "on_d1_d2"

Thank you in advance!

Body:
We can use

library(dplyr)
df %>%
   group_by(pt_id) %>%
   mutate(drug_combo = sum(c('d1', 'd2') %in% drug) == 2)
# A tibble: 8 x 3
# Groups:   pt_id [4]
#  pt_id drug  drug_combo
#  <chr> <chr> <lgl>
#1 p1    d1    TRUE
#2 p2    d1    TRUE
#3 p3    d1    FALSE
#4 p4    d1    FALSE
#5 p1    d2    TRUE
#6 p2    d2    TRUE
#7 p3    d3    FALSE
#8 p4    d3    FALSE

Or with data.table

library(data.table)
setDT(df)[, drug_combo := sum(c('d1', 'd2') %in% drug) == 2, pt_id]


问:
JavaScript losing "this" context, function inside class function
```<code>class b {
  constructor(){
    this.name = 'bar'
  }
  b1(){
    console.log('here: ', this.name);
    function c() {
      console.log('inside c: ', this.name)
    }
    c();
  }
}

let a = new b;
a.b1();

//output:
// here:  bar
// inside c:  undefined

</code>```

In this case, when calling a.b1(), in the scope of function b1, the this context is bind to a. But when executing function c inside function b1, why the this context is lost? this suppose in the closure of function c ?

I know how to make it work (arrow function). Just wondering why.

答:
Function c() is not part of the class so you would need to use Function.prototype.call() to pass in the class context as this or use arrow functions to declare it

class b {
  constructor(){
    this.name = 'bar'
  }
  b1(){
    console.log('here: ', this.name);
    function c() {
      console.log('inside c: ', this.name)
    }
    c.call(this);
  }
}

let a = new b;
a.b1();```

Body:
class b {
  constructor(){
    this.name = 'bar'
  }
  b1(){
    console.log('here: ', this.name);
    function c() {
      console.log('inside c: ', this.name)
    }
    c();
  }
}

let a = new b;
a.b1();

//output:
// here:  bar
// inside c:  undefined

In this case, when calling a.b1(), in the scope of function b1, the this context is bind to a. But when executing function c inside function b1, why the this context is lost? this suppose in the closure of function c ?

I know how to make it work (arrow function). Just wondering why.


问:
i can't use (point_distance) to kill any enemy nearset my hero GMK
I have a problem with a code in the Game Maker program
I make a little game that has a path that the enemies walk on and put heroes on his side and when the enemy approaches him he turns to him and he shoots him
I am using this code

```<code>var ex, ey;
ex = instance_nearest(x, y, enemy).x;
ey = instance_nearest(x, y, enemy).y;

if point_distance(x, y, ex, ey) < 150
{
     image_angle = point_direction(x, y, enemy.x, enemy.y);
}
</code>```

The code works well, but the problem is that my heroes only go to the first enemy when they come close to them and do not go to the rest even when the first enemy is out of range
What is the solution, please
Photo for illustration
 Heroes ignore the nearby enemy and only head for the first enemy to appear in the game

答:
I think the answer gave by YellowAfterlife solved the problem. But not sure if the reason of the problem was clear, then I want to complement by explain that the problem happened because the code in "point_direction" is referencing the object instead of the instance.

The object is the template that the created instance is based of, if you want to manipulate or get information you should reference the instance. If you only have one instance of that object, it will work referencing the object directly, but after more were created, it will return the index of only one of them (maybe the first created).

About instances: every object that you drag to the room will became an instance of that object or when you create an instance from the code, like calling "instance_create_layer(x, y, "instance_layer", obj_Bullet)", this function will return  the reference/index of the new instance created.

When the function "instance_nearest" is called it receives the player instance position (x and y) and the object of the instances that you want to check if it's near to the player, for example, the enemy object. The function will check all instances that was created from the informed object and will returns the index/reference of the instance nearest to the player. In the original code when calling the point_direction, was used the object enemy instead of the instance returned by instance_nearest function.

The object will always return the same index of some instance, causing the problem reported, that the player instance always point to the same enemy instance (coincidentally, the first instance created)

You can use the object if want to manipulate all instances at once, like this: "with(o_player) y++;". This code will make all instances of that object move down together.

Body:
I have a problem with a code in the Game Maker program
I make a little game that has a path that the enemies walk on and put heroes on his side and when the enemy approaches him he turns to him and he shoots him
I am using this code

var ex, ey;
ex = instance_nearest(x, y, enemy).x;
ey = instance_nearest(x, y, enemy).y;

if point_distance(x, y, ex, ey) < 150
{
     image_angle = point_direction(x, y, enemy.x, enemy.y);
}

The code works well, but the problem is that my heroes only go to the first enemy when they come close to them and do not go to the rest even when the first enemy is out of range
What is the solution, please
Photo for illustration
 Heroes ignore the nearby enemy and only head for the first enemy to appear in the game


问:
What is the "right" way to avoid Aliasing (e.g. when adding an element of a container to itself) in C++?
```<code>std::vector<int> a;
a.push_back(1);
a.push_back(a[0]);
</code>```

I just learned that the code above can be very dangerous.

(If it's not obvious why, you're not alone... it wasn't obvious to me either.)

My questions:

What is the "standard" way of dealing with it? Making a new variable and then assigning it immediately to something afterward seems a bit weird to me. Is there a better way of dealing with it?

How do you train yourself to watch out for aliasing issues like this? What pattern(s) do you look for? I have no idea to recognize this situation; I only learned about aliasing when I learned about the restrict keyword in C, and only now do I understand what the issue really is.

Edit:

I'd love to accept an answer, but it doesn't seem like part (2) of the question has been answered. I'm wondering what strategies people use to locate aliasing mistakes in code they have written.

One strategy I've come up with so far is to avoid passing in the same value for in two parameters. (In this case, one parameter is implicit and one explicit.)

Are there any other easy things to notice and watch out for?

答:
I guess this would be safe:</p>

```<code>std::vector<int> a(1);
a.push_back(1);
a.push_back(int(a[0]));
</code>```

Body:
std::vector<int> a;
a.push_back(1);
a.push_back(a[0]);

I just learned that the code above can be very dangerous.

(If it's not obvious why, you're not alone... it wasn't obvious to me either.)

My questions:

What is the "standard" way of dealing with it? Making a new variable and then assigning it immediately to something afterward seems a bit weird to me. Is there a better way of dealing with it?

How do you train yourself to watch out for aliasing issues like this? What pattern(s) do you look for? I have no idea to recognize this situation; I only learned about aliasing when I learned about the restrict keyword in C, and only now do I understand what the issue really is.

Edit:

I'd love to accept an answer, but it doesn't seem like part (2) of the question has been answered. I'm wondering what strategies people use to locate aliasing mistakes in code they have written.

One strategy I've come up with so far is to avoid passing in the same value for in two parameters. (In this case, one parameter is implicit and one explicit.)

Are there any other easy things to notice and watch out for?

Body:
I guess this would be safe:

std::vector<int> a(1);
a.push_back(1);
a.push_back(int(a[0]));


问:
How to use setw(x) in a toString method in c++ and put it in a variable or suggestions?
I have a Book class, and I want to implement a toString method in c++, using setw(x), to format in a properly mode.

I want to print something like that:

```<code>> cout<<setw(10)<<book.title<<setw(10)<<book.author;
</code>```

but in a toString method:

```<code>string toString(){
 string buff;
 ....
 return buff; }
</code>```

Thanks!

答:
Use std::ostringstream, eg:

```<code>#include <sstream>

string toString() const {
    std::ostringstream buff;
    buff << std::setw(10) << title << std::setw(10) << author;
    return buff.str();
}
</code>```

```<code>cout << book.toString()
</code>```

Body:
I have a Book class, and I want to implement a toString method in c++, using setw(x), to format in a properly mode.

I want to print something like that:

> cout<<setw(10)<<book.title<<setw(10)<<book.author;

but in a toString method:

string toString(){
 string buff;
 ....
 return buff; }

Thanks!

Body:
Use std::ostringstream, eg:

#include <sstream>

string toString() const {
    std::ostringstream buff;
    buff << std::setw(10) << title << std::setw(10) << author;
    return buff.str();
}

cout << book.toString()


答:
this isn't obtained from closure unless you use an arrow function, instead it as received by how the function is called.

Since c is called directly, this here refers to undefined.

You can declare c to be an arrow function to get this from the enclosing scope

class b {
      constructor(){
        this.name = 'bar'
      }
      b1(){
        console.log('here: ', this.name);
        const c = ()  => {
          console.log('inside c: ', this.name)
        }
        c();
      }
    }

    let a = new b;
    a.b1();```

Title: JavaScript losing "this" context, function inside class function


问:
How to print different variables in one plot in R
So I have some 2-factor-variables (1,0) and an age variable (numeric), I have done a cluster analysis and I want to plot the different variables in X axis, something like this:

I have tried using ggplot but I just cant get what I am looking for.

So I have the following:

```<code>visit <- rbinom(20, 1, 0.5)
death <- rbinom(20, 1, 0.5)
gender <- rbinom(20, 1, 0.5)
age <- sample(1:50,20,replace=F)
cluster <- letters[1:5]
df <- data.frame(visit,death,gender,age,cluster)
</code>```

And I want to plot a graph in which in colored line represents the cluster based on the above variables.

答:
You can do this by simply specifying color in aes() and using geom_line(). I initially thought this might be a duplicate, but didn't see any real candidates after a quick search. I will say that I think you would benefit by reading up on some ggplot2 basics, such as by going through this guide (for example).

So, here's how you could produce such a plot:

```<code>library(ggplot2)
ggplot(data = df, mapping = aes(x = death, y = age, color = cluster)) +
    geom_line()
</code>```

Data

```<code>set.seed(42) ## Set seed for reproducibility
visit <- rbinom(20, 1, 0.5)
death <- rbinom(20, 1, 0.5)
gender <- rbinom(20, 1, 0.5)
age <- sample(1:50,20,replace=F)
cluster <- letters[1:5]
df <- data.frame(visit,death,gender,age,cluster)
</code>```

Body:
So I have some 2-factor-variables (1,0) and an age variable (numeric), I have done a cluster analysis and I want to plot the different variables in X axis, something like this:

I have tried using ggplot but I just cant get what I am looking for.

So I have the following:

visit <- rbinom(20, 1, 0.5)
death <- rbinom(20, 1, 0.5)
gender <- rbinom(20, 1, 0.5)
age <- sample(1:50,20,replace=F)
cluster <- letters[1:5]
df <- data.frame(visit,death,gender,age,cluster)

And I want to plot a graph in which in colored line represents the cluster based on the above variables.

Body:
You can do this by simply specifying color in aes() and using geom_line(). I initially thought this might be a duplicate, but didn't see any real candidates after a quick search. I will say that I think you would benefit by reading up on some ggplot2 basics, such as by going through this guide (for example).

So, here's how you could produce such a plot:

library(ggplot2)
ggplot(data = df, mapping = aes(x = death, y = age, color = cluster)) +
    geom_line()

Data

set.seed(42) ## Set seed for reproducibility
visit <- rbinom(20, 1, 0.5)
death <- rbinom(20, 1, 0.5)
gender <- rbinom(20, 1, 0.5)
age <- sample(1:50,20,replace=F)
cluster <- letters[1:5]
df <- data.frame(visit,death,gender,age,cluster)


问:
firebase messaging onCreate not called
I'm facing an issue with FirebaseMessaging class.

```<code>public class FirebaseService extends FirebaseMessagingService {

    private static final String TAG = FirebaseService.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        GlobalApp.logDebug(TAG, "Firebase Service started");
    }
}
</code>```

The onCreate is not called.
I don't receive any notifications

I'm using implementation 'com.google.firebase:firebase-messaging:20.2.0'

The google documentation is not clear when that service starts.

This is my manifest :

```<code><service
            android:name=".common.google.FirebaseService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"
            android:directBootAware="true">
            <intent-filter android:priority="-500">
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
</code>```

Any idea ?

Thanks

答:
Thanks to @azizbekian

```<code><service
            android:name=".common.google.FirebaseService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"
            android:directBootAware="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
</code>```

I just had to remove the android:priority="-500"...

Facepalm..

Title: firebase messaging onCreate not called

Body:
I'm facing an issue with FirebaseMessaging class.

public class FirebaseService extends FirebaseMessagingService {

    private static final String TAG = FirebaseService.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        GlobalApp.logDebug(TAG, "Firebase Service started");
    }
}

The onCreate is not called.
I don't receive any notifications

I'm using implementation 'com.google.firebase:firebase-messaging:20.2.0'

The google documentation is not clear when that service starts.

This is my manifest :

<service
            android:name=".common.google.FirebaseService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"
            android:directBootAware="true">
            <intent-filter android:priority="-500">
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

Any idea ?

Thanks

Body:
Thanks to @azizbekian

<service
            android:name=".common.google.FirebaseService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"
            android:directBootAware="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

I just had to remove the android:priority="-500"...

Facepalm..


问:
reactjs: setState being called twice in a function called once? why?
EDIT: since the code snip does not reproduce the bug - here is a link to the github repo: (code is far FAR from complete)

https://github.com/altruios/clicker-game

I have run it on two computers now - both with the same behavior the code snip doesn't show.

//interestingly enough, this works just fine, where the same code I run locally has the doubling.
//when I comment out ALL other code except for this code I STILL get the error locally
//at this point the only difference is import export of components... here they are in one file.
//below is original code from file (
/*
FILE::::Clicker.js

import React from 'react';

function Clicker(props)
 {
 return(

  {props.name}
  <button
   name={props.name}
   onClick={props.HandleClick}
   data-target={props.subjectsOfIncrease}>
    {props.name} {props.value}

  </button>

  )
}

export default Clicker;

FILE:: Resouce.js

import React from 'react';
function Resource(props)
 {
 return(

  {props.name} and  {props.amount || 0}

  )
}

export default Resource;

*/
//besides the import/export and seprate files - code is the same. it works in here, does not work locally on my machine.

const gameData = {
  clickerData: [{
    name: "grey",
    subjectsOfIncrease: ["grey"],
    isUnlocked: true,
    value: 1
  }],
  resourceData: [{
    name: "grey",
    resouceMax: 100,
    isUnlocked: true,
    changePerTick: 0,
    counterTillStopped: 100,
    amount: 0
  }]
}
class App extends React.Component {
    constructor() {
      super();
      this.state = {
        resources: gameData.resourceData,
        clickers: gameData.clickerData
      };
      this.gainResource = this.gainResource.bind(this);
    }
    gainResource(event) {
      console.count("gain button");
      const name = event.target.name;
      this.setState((prevState) => {
        const newResources = prevState.resources.map(resource => {
          if (resource.name === name) {
            resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
          }
          return resource;
        });
        console.log(prevState.resources.find(item => item.name === name).amount, "old");
        console.log(newResources.find(item => item.name === name).amount, "new");
        return {
          resources: newResources
        }
      });
    }
    render() {
      const resources = this.state.resources.map(resourceData => {
          return (
            <Resource
              name = {resourceData.name}
              resouceMax = {resourceData.resourceMax}
              isUnlocked = {resourceData.isUnlocked}
              changePerTick = {resourceData.changePerTick}
              counterTillStopped = {resourceData.countTillStopped}
              amount = {resourceData.amount}
              key = {resourceData.name}
            />
          )
      })

      const clickers = this.state.clickers.map(clickerData => {
          return (
            <Clicker
              name = {clickerData.name}
              HandleClick = {this.gainResource}
              value = {clickerData.amount}
              key = {clickerData.name}
            />
          )
    })

    return (

            {resources}
           {clickers}

   )
 }
}
function Resource(props) {
      return
  {props.name} and {props.amount || 0}

}

function Clicker(props) {
      return (

 {props.name}
          <button name = {props.name}  onClick = {props.HandleClick}>
            {props.name} {props.value}
          </button>

     )
}
const root = document.getElementById('root');
ReactDOM.render(  <App / >,root );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

so I'm building a clicker game to learn react, and something I don't understand why this code is behaving the way it does:

in the main app I have this function:

```<code>
  gainResource(event)
    {
    console.count("gain button");
    const name = event.target.name;
    this.setState( (prevState)=>
      {
      const newResources =  prevState.resources.map(resource=>
        {
        if(resource.name === name)
          {
          resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
        }
        return resource;
      });
      console.log(prevState.resources.find(item=>item.name===name).amount, "old");
      console.log(newResources.find(item=>item.name===name).amount, "new");
      return {resources: newResources}
    });
  }
</code>```

that console.count runs a single time... but I get 2 'old and new' pairs. as if setState is running twice in this function which only runs once?

the console.output is:

```<code>App.js:64 gain button: 1
App.js:76 1 "old"
App.js:77 1 "new"
App.js:76 2 "old"
App.js:77 2 "new"
</code>```

so it looks like the function is running once. but the set state is being run twice?

the symptoms are that it counts up by 2. but also the initial state of amount is 0, not 1, as seen in the gamedata.json

```<code>    resourceData:
        [
            {
            name:"grey",
            resouceMax:100,
            isUnlocked:true,
            changePerTick:0,
            counterTillStopped:100,
            amount:0
            },{etc},{},{}],
        clickerData:
        [
            {
            name:"grey",
            subjectsOfIncrease:["grey"],
            isUnlocked:true,
            value:1
           },{etc},{},{}]

</code>```

i don't think the rest of the code I'm about to most is relevant to this behavior, but I don't know react yet, so I don't know what I'm missing: but this is how I'm generating the clicker button:

```<code>const clickers = this.state.clickers.map(clickerData=>
      {
      return(
        <Clicker
          name={clickerData.name}
          HandleClick = {this.gainResource}
          value = {clickerData.amount}
          key={clickerData.name}

        />

        )
    })

</code>```

and in the clicker.js functional component I'm just returning this:

```<code>        <div>
        {props.name}
        <button name={props.name} onClick={props.HandleClick}>
                {props.name} {props.value}
        </button>
        </div>

</code>```

the function is bound to this in the constructor... I don't understand why this is running setState twice inside a function that's called once.

I've also tried:

```<code>
        <div>
        {props.name}
        <button name={props.name} onClick={()=>props.HandleClick}> //anon function results in no output
                {props.name} {props.value}
        </button>
        </div>
</code>```

答:
As long as you didn't provide us a runnable example I've one doubt about what could be happened and let's see if it works.

What I can see is in the gainResource function and specially in this line resource.amount = Number(resource.amount) + 1 you're trying to update the state without using setState which is not recommended by React Documentation

Please instead try first to assign a const myRessource = ressource  then return myRessource instead.

```<code>  gainResource(event)
    {
    console.count("gain button");
    const name = event.target.name;
    this.setState( (prevState)=>
      {
      const newResources =  prevState.resources.map(resource=>
        {
       const myRessource = ressource;
        if(myRessource.name === name)
          {
          myRessource.amount = Number(myRessource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
        }
        return myRessource;
      });
      console.log(prevState.resources.find(item=>item.name===name).amount, "old");
      console.log(newResources.find(item=>item.name===name).amount, "new");
      return {resources: newResources}
    });
  }
</code>```

Body:
EDIT: since the code snip does not reproduce the bug - here is a link to the github repo: (code is far FAR from complete)

https://github.com/altruios/clicker-game

I have run it on two computers now - both with the same behavior the code snip doesn't show.

//interestingly enough, this works just fine, where the same code I run locally has the doubling.
//when I comment out ALL other code except for this code I STILL get the error locally
//at this point the only difference is import export of components... here they are in one file.
//below is original code from file (
/*
FILE::::Clicker.js

import React from 'react';

function Clicker(props)
 {
 return(

  {props.name}
  <button
   name={props.name}
   onClick={props.HandleClick}
   data-target={props.subjectsOfIncrease}>
    {props.name} {props.value}

  </button>

  )
}

export default Clicker;

FILE:: Resouce.js

import React from 'react';
function Resource(props)
 {
 return(

  {props.name} and  {props.amount || 0}

  )
}

export default Resource;

*/
//besides the import/export and seprate files - code is the same. it works in here, does not work locally on my machine.

const gameData = {
  clickerData: [{
    name: "grey",
    subjectsOfIncrease: ["grey"],
    isUnlocked: true,
    value: 1
  }],
  resourceData: [{
    name: "grey",
    resouceMax: 100,
    isUnlocked: true,
    changePerTick: 0,
    counterTillStopped: 100,
    amount: 0
  }]
}
class App extends React.Component {
    constructor() {
      super();
      this.state = {
        resources: gameData.resourceData,
        clickers: gameData.clickerData
      };
      this.gainResource = this.gainResource.bind(this);
    }
    gainResource(event) {
      console.count("gain button");
      const name = event.target.name;
      this.setState((prevState) => {
        const newResources = prevState.resources.map(resource => {
          if (resource.name === name) {
            resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
          }
          return resource;
        });
        console.log(prevState.resources.find(item => item.name === name).amount, "old");
        console.log(newResources.find(item => item.name === name).amount, "new");
        return {
          resources: newResources
        }
      });
    }
    render() {
      const resources = this.state.resources.map(resourceData => {
          return (
            <Resource
              name = {resourceData.name}
              resouceMax = {resourceData.resourceMax}
              isUnlocked = {resourceData.isUnlocked}
              changePerTick = {resourceData.changePerTick}
              counterTillStopped = {resourceData.countTillStopped}
              amount = {resourceData.amount}
              key = {resourceData.name}
            />
          )
      })

      const clickers = this.state.clickers.map(clickerData => {
          return (
            <Clicker
              name = {clickerData.name}
              HandleClick = {this.gainResource}
              value = {clickerData.amount}
              key = {clickerData.name}
            />
          )
    })

    return (

            {resources}
           {clickers}

   )
 }
}
function Resource(props) {
      return
  {props.name} and {props.amount || 0}

}

function Clicker(props) {
      return (

 {props.name}
          <button name = {props.name}  onClick = {props.HandleClick}>
            {props.name} {props.value}
          </button>

     )
}
const root = document.getElementById('root');
ReactDOM.render(  <App / >,root );

so I'm building a clicker game to learn react, and something I don't understand why this code is behaving the way it does:

in the main app I have this function:

  gainResource(event)
    {
    console.count("gain button");
    const name = event.target.name;
    this.setState( (prevState)=>
      {
      const newResources =  prevState.resources.map(resource=>
        {
        if(resource.name === name)
          {
          resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
        }
        return resource;
      });
      console.log(prevState.resources.find(item=>item.name===name).amount, "old");
      console.log(newResources.find(item=>item.name===name).amount, "new");
      return {resources: newResources}
    });
  }

that console.count runs a single time... but I get 2 'old and new' pairs. as if setState is running twice in this function which only runs once?

the console.output is:

App.js:64 gain button: 1
App.js:76 1 "old"
App.js:77 1 "new"
App.js:76 2 "old"
App.js:77 2 "new"

so it looks like the function is running once. but the set state is being run twice?

the symptoms are that it counts up by 2. but also the initial state of amount is 0, not 1, as seen in the gamedata.json

    resourceData:
        [
            {
            name:"grey",
            resouceMax:100,
            isUnlocked:true,
            changePerTick:0,
            counterTillStopped:100,
            amount:0
            },{etc},{},{}],
        clickerData:
        [
            {
            name:"grey",
            subjectsOfIncrease:["grey"],
            isUnlocked:true,
            value:1
           },{etc},{},{}]

i don't think the rest of the code I'm about to most is relevant to this behavior, but I don't know react yet, so I don't know what I'm missing: but this is how I'm generating the clicker button:

const clickers = this.state.clickers.map(clickerData=>
      {
      return(
        <Clicker
          name={clickerData.name}
          HandleClick = {this.gainResource}
          value = {clickerData.amount}
          key={clickerData.name}

        />

        )
    })

and in the clicker.js functional component I'm just returning this:

        {props.name}
        <button name={props.name} onClick={props.HandleClick}>
                {props.name} {props.value}
        </button>

the function is bound to this in the constructor... I don't understand why this is running setState twice inside a function that's called once.

I've also tried:

        {props.name}
        <button name={props.name} onClick={()=>props.HandleClick}> //anon function results in no output
                {props.name} {props.value}
        </button>

Body:
As long as you didn't provide us a runnable example I've one doubt about what could be happened and let's see if it works.

What I can see is in the gainResource function and specially in this line resource.amount = Number(resource.amount) + 1 you're trying to update the state without using setState which is not recommended by React Documentation

Please instead try first to assign a const myRessource = ressource  then return myRessource instead.

  gainResource(event)
    {
    console.count("gain button");
    const name = event.target.name;
    this.setState( (prevState)=>
      {
      const newResources =  prevState.resources.map(resource=>
        {
       const myRessource = ressource;
        if(myRessource.name === name)
          {
          myRessource.amount = Number(myRessource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
        }
        return myRessource;
      });
      console.log(prevState.resources.find(item=>item.name===name).amount, "old");
      console.log(newResources.find(item=>item.name===name).amount, "new");
      return {resources: newResources}
    });
  }


答:
I'm just winging this, so please don't consider it gospel, but would this work?</p>

```<code>a.push_back(1);
a.push_back(&(new int(a[0])));
</code>```

Title: What is the "right" way to avoid Aliasing (e.g. when adding an element of a container to itself) in C++?

Body:
I'm just winging this, so please don't consider it gospel, but would this work?

a.push_back(1);
a.push_back(&(new int(a[0])));


问:
Node JS preventin users from deleting other user's products
I have a REST API built with Node JS and I'm currently using MongoDB as my database. I want to prevent the users from deleting another user's products and for this I checked if the userId from the decoded token is the same as the product userId.

Product schema

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

const productSchema = mongoose.Schema(
  {
    _id: mongoose.Schema.Types.ObjectId,
    userId: mongoose.Schema.Types.ObjectId,
    name: { type: String, required: true },
    price: { type: Number, required: true },
    productImage: { type: String, required: false },
    category: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Category",
      required: true
    },
    gender: { type: String, required: true }
  },
  { timestamps: { createdAt: "created_at" } }
);

module.exports = mongoose.model("Product", productSchema);

</code>```

The delete product method:

```<code>  const id = req.params.productId;
  Product.findById({ _id: id }).then((product) => {
    if (product.userId != req.user._id) {
      return res.status(401).json("Not authorized");
    } else {
      Product.deleteOne({ _id: id })
        .exec()
        .then(() => {
          return res.status(200).json({
            message: "Product deleted succesfully",
          });
        })
        .catch((err) => {
          console.log(err);
          return res.status(500).json({
            error: err,
          });
        });
    }
  });
};
</code>```

As you guys see first I'm searching executing the findByID method to access the userId property of the product, then I'm comparing the userId from the response with the userId from the decoded token.

I don't think my method is very efficient since it's running both findById and deleteOne methods.

Can you help me with finding a better solution for this?

答:
as Guy Incognito mentioned, what you are trying to do is an OK thing and you may want to keep it this way in case you want to send a 404 status stating the product they are trying to remove does not exist.

however, if you are trying to do it with only one request

Product.deleteOne({ _id: id, userId: req.user._id })
```

hope it helps!

Body:
I have a REST API built with Node JS and I'm currently using MongoDB as my database. I want to prevent the users from deleting another user's products and for this I checked if the userId from the decoded token is the same as the product userId.

Product schema

const mongoose = require("mongoose");

const productSchema = mongoose.Schema(
  {
    _id: mongoose.Schema.Types.ObjectId,
    userId: mongoose.Schema.Types.ObjectId,
    name: { type: String, required: true },
    price: { type: Number, required: true },
    productImage: { type: String, required: false },
    category: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Category",
      required: true
    },
    gender: { type: String, required: true }
  },
  { timestamps: { createdAt: "created_at" } }
);

module.exports = mongoose.model("Product", productSchema);

The delete product method:

  const id = req.params.productId;
  Product.findById({ _id: id }).then((product) => {
    if (product.userId != req.user._id) {
      return res.status(401).json("Not authorized");
    } else {
      Product.deleteOne({ _id: id })
        .exec()
        .then(() => {
          return res.status(200).json({
            message: "Product deleted succesfully",
          });
        })
        .catch((err) => {
          console.log(err);
          return res.status(500).json({
            error: err,
          });
        });
    }
  });
};

As you guys see first I'm searching executing the findByID method to access the userId property of the product, then I'm comparing the userId from the response with the userId from the decoded token.

I don't think my method is very efficient since it's running both findById and deleteOne methods.

Can you help me with finding a better solution for this?

Body:
as Guy Incognito mentioned, what you are trying to do is an OK thing and you may want to keep it this way in case you want to send a 404 status stating the product they are trying to remove does not exist.

however, if you are trying to do it with only one request

Product.deleteOne({ _id: id, userId: req.user._id })

hope it helps!