问:
What is contained in code/internal sections of JCMD?
Dimensioning a docker container for a JVM based service is tricky (as we all know). I'm pretty sure we have slightly under-dimensioned a container and want to clear up a few questions I have relating to specific jcmd (Native Memory Tracker) outputs that we see when monitoring.

Questions:

Are Direct Byte Buffers included in "Internal" as reported by jcmd?

What else apart from code cache is in "Code" as reported by jcmd?

Is there a good way to limit the "Code" section as reported by jcmd. I read https://docs.oracle.com/javase/8/embedded/develop-apps-platforms/codecache.htm but this only covers the code cache limits and it is suggested to leave the JVM default as is.

JCMD output is here.

Direct Byte Buffers JMX properties are here.

Some background details:

The Setup:

Spring boot based application

JVM Options:

-server -Xms1792m -Xmx1792m -XX:MetaspaceSize=128M -
XX:MaxMetaspaceSize=192M -XX:+UseG1GC -XX:+UseStringDeduplication -
XX:MaxDirectMemorySize=256m -XX:NativeMemoryTracking=detail

Docker container 2500MiB running in AWS/EC2

答:
Are Direct Byte Buffers included in "Internal" as reported by jcmd?

(updated)
ByteBuffer.allocateDirect internally calls Unsafe.allocateMemory which is counted by NMT in the Internal section (denoted by mtInternal constant).

On the contrary, MappedByteBuffers (obtained by FileChannel.map) are not reflected in NMT report, though they definitely may affect the amount of memory used by the process from OS perspective.

What else apart from code cache is in "Code" as reported by jcmd?

Auxiliary VM structures for maintaining compiled code and generated runtime stubs: hashtables, code strings, adapter fingerprints etc. They all are rather small comparing to the CodeCache itself. These structures make up 'malloc' part in the report while the CodeCache goes into 'mmap' part.

Is there a good way to limit the "Code" section as reported by jcmd.

Turning off tiered compilation (-XX:-TieredCompilation)
is likely to reduce the amount of memory used by "Code", just because there will be a lot less generated code. But make sure you understand what tiered compilation is and what performance impact it may have.


来源: stackexchange

问:
When using DrivePicker get the webcontent link
On a form I put a DrivePicker widget/button. This button opens my Google Drive and I can select an image. To show this image in an Image widget I need the webcontent link instead of the file URL link. The file URL link won't work.

By the property editor of the DrivePicker widget I put the following code at onDocumentSelect part.

```<code>varId = result.docs[0].id;
widget.datasource.item.strArtikelAfbeeldingId = result.docs[0].id;
widget.datasource.item.strArtikelAfbeeldingUrl = Drive.Files.get(varId).webContentLink;
</code>```

Unfortunately I get no webcontentlink and got the following error message

Drive is not defined
  at pageTabelArtikelen.Form1.Form1Body.DrivePicker1.onDocumentSelect:3:50

How can I get a webcontentlink of a selected image when using DrivePicker widget?

答:
You need to run a server function from the client to use Drive. So you can still run this function for the onDocumentSelect event, but you would want to declare a server function such as getFileWebContent() and then change your event code to:

Client

```<code>var Id = widget.selectedDocId;
    google.script.run
      .withSuccessHandler(function() {
      //do something here with the returned link from server;
      })
      .withFailureHandler(function() {
      //optional failure handler;
      })
      .getFileWebContent(Id);
</code>```

Server

```<code>function getFileWebContent(Id) {
  var link = Drive.Files.get(Id).WebContentLink;
  return link;
}
</code>```

It would be more ideal to run the server code in the model onCreate event which is a server function. In this case your model can have a field for the file id and in your onCreate event you would run

```<code>var link = Drive.Files.get(record.FileId).webContentLink;
record.WebLink = link;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
On a form I put a DrivePicker widget/button. This button opens my Google Drive and I can select an image. To show this image in an Image widget I need the webcontent link instead of the file URL link. The file URL link won't work.

By the property editor of the DrivePicker widget I put the following code at onDocumentSelect part.

varId = result.docs[0].id;
widget.datasource.item.strArtikelAfbeeldingId = result.docs[0].id;
widget.datasource.item.strArtikelAfbeeldingUrl = Drive.Files.get(varId).webContentLink;

Unfortunately I get no webcontentlink and got the following error message

Drive is not defined
  at pageTabelArtikelen.Form1.Form1Body.DrivePicker1.onDocumentSelect:3:50

How can I get a webcontentlink of a selected image when using DrivePicker widget?

Body:
You need to run a server function from the client to use Drive. So you can still run this function for the onDocumentSelect event, but you would want to declare a server function such as getFileWebContent() and then change your event code to:

Client

var Id = widget.selectedDocId;
    google.script.run
      .withSuccessHandler(function() {
      //do something here with the returned link from server;
      })
      .withFailureHandler(function() {
      //optional failure handler;
      })
      .getFileWebContent(Id);

Server

function getFileWebContent(Id) {
  var link = Drive.Files.get(Id).WebContentLink;
  return link;
}

It would be more ideal to run the server code in the model onCreate event which is a server function. In this case your model can have a field for the file id and in your onCreate event you would run

var link = Drive.Files.get(record.FileId).webContentLink;
record.WebLink = link;

ContentLicense: CC BY-SA 3.0


问:
FFImageLoading: Unhandled Exception: System.TypeLoadException: Could not load list of method overrides occurred
When trying to init FFImage (in my application):

```<code>CachedImageRenderer.Init();
</code>```

I get the mysterious error:

```<code>Unhandled Exception:  System.TypeLoadException: Could not load list of method overrides occurred
</code>```

I can get the FFImage sample app to run okay. I have the dependencies all in order as far as I can tell.

答:
I'm an author of this library. I forgot to raise Xamarin.Forms dependency to 2.4.x version (planned for next release).

If using Xamarin.Forms < 2.4 you want to use v2.2.25-legacy prerelease package version. I stripped fast renderer out of it.

https://github.com/luberda-molinet/FFImageLoading/issues/814#issuecomment-344677274

Body:
When trying to init FFImage (in my application):

CachedImageRenderer.Init();

I get the mysterious error:

Unhandled Exception:  System.TypeLoadException: Could not load list of method overrides occurred

I can get the FFImage sample app to run okay. I have the dependencies all in order as far as I can tell.


问:
Questions about operator overloading
I have two questions about operator overloading.

For an iterator type, how is operator-> overloaded? What value should it return assuming that it is an iterator for a collection of class T objects?

Why does operator++() return by class T& while operator++(int) return by class T? I understand these two represent prefix increment and postfix increment. But why the difference in return value?

EDIT: For Alf. Code is not complete though functioning. Any suggestions for improvement are welcome.

```<code>#ifndef DHASH_H
#define DHASH_H

//#include <vector>
#include <memory>
#include <exception>
#include <new>
#include <algorithm>
#include <functional>

namespace MCol
{
    template <typename KEY, typename VALUE, typename HASH_FUNCTION, typename KEY_COMP = std::equal_to<KEY> >
        class hash_container
        {
            private:
                struct entry
                {
                    KEY _k;
                    VALUE _v;

                    entry(const KEY& k, const VALUE& v)
                        :_k(k), _v(v)
                    {}

                    entry& operator=(const entry& e)
                    {
                        this->_k = e._k;
                        this->_v = e._v;
                    }
                };

            private:
                struct bucket
                {
                    entry* a_Entries;
                    size_t sz_EntryCount;

                    bucket()
                    {
                        sz_EntryCount = 0;
                        a_Entries = NULL;
                    }

                    ~bucket()
                    {
                        for(size_t szI = 0; szI < sz_EntryCount; ++szI)
                        {
                            a_Entries[szI].~entry();
                        }
                        free(a_Entries);
                    }

                    //Grow by 1. (Perhaps later try block increment. But wikipedia suggests that there is little difference between the two)
                    inline bool insert(const KEY& k, const VALUE& v) throw (std::bad_alloc)
                    {
                        if(find(k) != NULL)
                        {
                            return false;
                        }
                        a_Entries = static_cast<entry*>(realloc(a_Entries, sizeof(entry)*(++sz_EntryCount)));
                        if(a_Entries == NULL)
                        {
                            throw std::bad_alloc();
                        }

                        new (&a_Entries[sz_EntryCount - 1]) entry(k, v);
                        return true;
                    }

                    //Find entry, swap with last valid entry, remove if necessary.
                    inline bool erase(const KEY& k) throw(std::bad_alloc)
                    {
                        //Forwards or backwards? My guess is backwards is better.
                        entry* pE = a_Entries;
                        while(pE != a_Entries + sz_EntryCount)
                        {
                            if(pE->_k == k)
                            {
                                break;
                            }
                            ++pE;
                        }

                        if(pE == a_Entries + sz_EntryCount)
                        {
                            return false;
                        }

                        //We don't need to swap if the entry is the only one in the bucket or if it is the last one.
                        entry* pLast = a_Entries + sz_EntryCount - 1;
                        if((sz_EntryCount > 1) && (pE != pLast))
                        {
                            pE = pLast;
                        }

                        a_Entries = static_cast<entry*>(realloc(a_Entries, sizeof(entry)*(--sz_EntryCount)));
                        if(a_Entries == NULL && sz_EntryCount > 0)
                        {
                            throw std::bad_alloc();
                        }

                        return true;
                    }

                    inline entry* find(const KEY& k) throw()
                    {
                        //Better implement a search policy.
                        entry* pE = a_Entries;
                        while(pE != a_Entries + sz_EntryCount)
                        {
                            if(pE->_k == k)
                            {
                                break;
                            }
                            ++pE;
                        }

                        if(pE == a_Entries + sz_EntryCount)
                        {
                            return NULL;
                        }

                        return pE;
                    }
                };

                HASH_FUNCTION& _hf;
                KEY_COMP _kc;

                size_t sz_TableSize;
                double d_MultFactor;                                            //Recalculate this as 1/sz_TableSize everytime sz_TableSize changes.
                size_t sz_NextResizeLimit;
                size_t sz_EntryCount;
                double d_ExpectedLoadFactor;
                double d_CurrentLoadFactor;

                //If the load factor is relatively high (say >0.5 assuming sizeof(entry) == 2*sizeof(size_t)), it is more space efficient to keep a straight bucket array. But if the load factor is low, memory consumption would be lower if a pointer array of Entries is used here. But, because we would not be much concerned with a little additional memory being used when there are few entries, I think array of bucket objects is better. Further, it bypasses a pointer lookup. May have to reconsider is a situation where multiple hash tables are used (Perhaps as an array).
                bucket* a_Buckets;

                hash_container(const hash_container&);
                hash_container& operator=(const hash_container&);

                inline void calculateMultFactor() throw()
                {
                    d_MultFactor = 1.0f/static_cast<double>(sz_TableSize + 1);
                    //sz_NextResizeLimit = static_cast<size_t>(d_ExpectedLoadFactor*sz_TableSize);
                    //Have a look at this.
                    //TODO
                }

                void resize(size_t szNewSize) throw(std::bad_alloc)
                {
                    if(szNewSize == 0)
                    {
                        szNewSize = 1;
                    }
                    size_t szOldSize = sz_TableSize;
                    for(size_t szI = szNewSize; szI < szOldSize; ++szI)
                    {
                        a_Buckets[szI].~bucket();
                    }

                    a_Buckets = static_cast<bucket*>(realloc(a_Buckets, sizeof(bucket)*szNewSize));
                    if(a_Buckets == NULL)
                    {
                        throw std::bad_alloc();
                    }
                    //Unnecessary at the moment. But, just in case that bucket changes.
                    for(size_t szI = szOldSize; szI < szNewSize; ++szI)
                    {
                         new (&a_Buckets[szI]) bucket();
                    }

                    sz_TableSize = szNewSize;
                    calculateMultFactor();
                }

                inline bucket* get_bucket(const KEY& k) throw()
                {
                    return a_Buckets + _hf(k, sz_TableSize);
                }

                inline bool need_resizing() const throw()
                {

                }
            public:
                //typedef iterator void*;
                //typedef const_iterator void*;

                //iterator Insert(KEY& k, VALUE& v);
                //VALUE& Find(Key& k);
                //const VALUE& Find(Key& k);
                //iterator Find(KEY k);
                //const_iterator Find(KEY k);
                //void Delete(KEY& k);
                //void Delete(iterator it);
                //void Delete(const_iterator it);
                class iterator
                {
                    private:
                        entry* p_Entry;
                        bucket* p_Bucket;

                        friend class bucket;

                    public:
                        iterator(entry* pEntry)
                            :p_Entry(pEntry)
                        {
                        }

                        iterator()
                        {
                            p_Entry = NULL;
                        }

                        iterator(const iterator& it)
                        {
                            this->p_Entry = it.p_Entry;
                        }

                        inline VALUE& operator*() const
                        {
                            return p_Entry->_v;
                        }

                        inline bool operator==(const iterator& it) const
                        {
                            return this->p_Entry == it.p_Entry;
                        }

                        inline bool operator!=(const iterator& it) const
                        {
                            return !(*this == it);
                        }

                        inline iterator& operator=(const iterator& it)
                        {
                            this->p_Entry = it.p_Entry;
                        }

                        inline VALUE* operator->() const
                        {
                            return &p_Entry->_v;
                        }

                        inline iterator operator++()
                        {
                            return *this;
                        }

                        inline iterator& operator++(int)
                        {
                            //WRONG!!!
                            //TODO : Change this.
                            return *this;
                        }
                };

            private:
                iterator _EndIt;

            public:
                hash_container(HASH_FUNCTION& hf, size_t szTableSize = 1024, double dLoadFactor = 0.7f, KEY_COMP kc = KEY_COMP())throw(std::bad_alloc)
                    :_hf(hf), sz_TableSize(szTableSize), d_ExpectedLoadFactor(dLoadFactor), _kc(kc)
                {
                    if(d_ExpectedLoadFactor < 0.1f)
                    {
                        d_ExpectedLoadFactor = 0.1f;
                    }

                    a_Buckets = NULL;
                    sz_TableSize = 0;
                    if(szTableSize == 0)
                    {
                        szTableSize = 1;
                    }
                    resize(szTableSize);
                    d_CurrentLoadFactor = 0.0f;
                    sz_EntryCount = 0;

                    _EndIt = iterator(NULL);
                }

                virtual ~hash_container()
                {
                    for(size_t szI = 0; szI < sz_TableSize; ++szI)
                    {
                        a_Buckets[szI].~bucket();
                    }
                }

                inline iterator find(const KEY& k) throw()
                {
                    bucket* pBucket = get_bucket(k);
                    return pBucket->find(k);
                }

                inline bool insert(const KEY& k, const VALUE& v) throw(std::bad_alloc)
                {
                    bucket* pBucket = get_bucket(k);
                    bool bRet = false;
                    try
                    {
                        bRet = pBucket->insert(k, v);
                    }
                    catch(std::bad_alloc& e)
                    {
                        //What now?
                        throw e;
                    }
                    if(bRet == true)
                    {
                        ++sz_EntryCount;
                    }
                    return bRet;
                }

                inline VALUE& operator[](const KEY& k) throw(std::bad_alloc)
                {
                    bucket* pBucket = get_bucket(k);

                }

                inline bool erase(const KEY& k) throw(std::bad_alloc)
                {
                    bucket* pBucket =  get_bucket(k);
                    bool bRet = false;
                    try
                    {
                        bRet = pBucket->erase(k);
                    }
                    catch(std::bad_alloc& e)
                    {
                        throw e;
                    }
                    if(bRet == true)
                    {
                        --sz_EntryCount;
                    }
                    return bRet;
                }

                inline iterator end() const
                {
                    return _EndIt;
                }

                inline size_t size() const
                {
                    return sz_EntryCount;
                }

                inline size_t table_size() const
                {
                    return sz_TableSize;
                }

                inline double current_load_factor() const
                {
                    return d_MultFactor*static_cast<double>(sz_EntryCount);
                }

                inline double expected_load_factor() const
                {
                    return d_ExpectedLoadFactor;
                }
        };
}

#endif
</code>```

答:
operator-> should return a pointer to type T (ie. T*).

Postfix increment has to return a copy of the value, since it performs the increment but before the value has been used. Prefix increment can simply return *this after incrementing.

Simple implementations may look like this:

```<code>T T::operator++(int)
{
    T temp = *this;
    ++*this;
    return temp;
}

T& T::operator++()
{
    this->value += 1;
    return *this;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Questions about operator overloading

Body:
I have two questions about operator overloading.

For an iterator type, how is operator-> overloaded? What value should it return assuming that it is an iterator for a collection of class T objects?

Why does operator++() return by class T& while operator++(int) return by class T? I understand these two represent prefix increment and postfix increment. But why the difference in return value?

EDIT: For Alf. Code is not complete though functioning. Any suggestions for improvement are welcome.

#ifndef DHASH_H
#define DHASH_H

//#include <vector>
#include <memory>
#include <exception>
#include <new>
#include <algorithm>
#include <functional>

namespace MCol
{
    template <typename KEY, typename VALUE, typename HASH_FUNCTION, typename KEY_COMP = std::equal_to<KEY> >
        class hash_container
        {
            private:
                struct entry
                {
                    KEY _k;
                    VALUE _v;

                    entry(const KEY& k, const VALUE& v)
                        :_k(k), _v(v)
                    {}

                    entry& operator=(const entry& e)
                    {
                        this->_k = e._k;
                        this->_v = e._v;
                    }
                };

            private:
                struct bucket
                {
                    entry* a_Entries;
                    size_t sz_EntryCount;

                    bucket()
                    {
                        sz_EntryCount = 0;
                        a_Entries = NULL;
                    }

                    ~bucket()
                    {
                        for(size_t szI = 0; szI < sz_EntryCount; ++szI)
                        {
                            a_Entries[szI].~entry();
                        }
                        free(a_Entries);
                    }

                    //Grow by 1. (Perhaps later try block increment. But wikipedia suggests that there is little difference between the two)
                    inline bool insert(const KEY& k, const VALUE& v) throw (std::bad_alloc)
                    {
                        if(find(k) != NULL)
                        {
                            return false;
                        }
                        a_Entries = static_cast<entry*>(realloc(a_Entries, sizeof(entry)*(++sz_EntryCount)));
                        if(a_Entries == NULL)
                        {
                            throw std::bad_alloc();
                        }

                        new (&a_Entries[sz_EntryCount - 1]) entry(k, v);
                        return true;
                    }

                    //Find entry, swap with last valid entry, remove if necessary.
                    inline bool erase(const KEY& k) throw(std::bad_alloc)
                    {
                        //Forwards or backwards? My guess is backwards is better.
                        entry* pE = a_Entries;
                        while(pE != a_Entries + sz_EntryCount)
                        {
                            if(pE->_k == k)
                            {
                                break;
                            }
                            ++pE;
                        }

                        if(pE == a_Entries + sz_EntryCount)
                        {
                            return false;
                        }

                        //We don't need to swap if the entry is the only one in the bucket or if it is the last one.
                        entry* pLast = a_Entries + sz_EntryCount - 1;
                        if((sz_EntryCount > 1) && (pE != pLast))
                        {
                            pE = pLast;
                        }

                        a_Entries = static_cast<entry*>(realloc(a_Entries, sizeof(entry)*(--sz_EntryCount)));
                        if(a_Entries == NULL && sz_EntryCount > 0)
                        {
                            throw std::bad_alloc();
                        }

                        return true;
                    }

                    inline entry* find(const KEY& k) throw()
                    {
                        //Better implement a search policy.
                        entry* pE = a_Entries;
                        while(pE != a_Entries + sz_EntryCount)
                        {
                            if(pE->_k == k)
                            {
                                break;
                            }
                            ++pE;
                        }

                        if(pE == a_Entries + sz_EntryCount)
                        {
                            return NULL;
                        }

                        return pE;
                    }
                };

                HASH_FUNCTION& _hf;
                KEY_COMP _kc;

                size_t sz_TableSize;
                double d_MultFactor;                                            //Recalculate this as 1/sz_TableSize everytime sz_TableSize changes.
                size_t sz_NextResizeLimit;
                size_t sz_EntryCount;
                double d_ExpectedLoadFactor;
                double d_CurrentLoadFactor;

                //If the load factor is relatively high (say >0.5 assuming sizeof(entry) == 2*sizeof(size_t)), it is more space efficient to keep a straight bucket array. But if the load factor is low, memory consumption would be lower if a pointer array of Entries is used here. But, because we would not be much concerned with a little additional memory being used when there are few entries, I think array of bucket objects is better. Further, it bypasses a pointer lookup. May have to reconsider is a situation where multiple hash tables are used (Perhaps as an array).
                bucket* a_Buckets;

                hash_container(const hash_container&);
                hash_container& operator=(const hash_container&);

                inline void calculateMultFactor() throw()
                {
                    d_MultFactor = 1.0f/static_cast<double>(sz_TableSize + 1);
                    //sz_NextResizeLimit = static_cast<size_t>(d_ExpectedLoadFactor*sz_TableSize);
                    //Have a look at this.
                    //TODO
                }

                void resize(size_t szNewSize) throw(std::bad_alloc)
                {
                    if(szNewSize == 0)
                    {
                        szNewSize = 1;
                    }
                    size_t szOldSize = sz_TableSize;
                    for(size_t szI = szNewSize; szI < szOldSize; ++szI)
                    {
                        a_Buckets[szI].~bucket();
                    }

                    a_Buckets = static_cast<bucket*>(realloc(a_Buckets, sizeof(bucket)*szNewSize));
                    if(a_Buckets == NULL)
                    {
                        throw std::bad_alloc();
                    }
                    //Unnecessary at the moment. But, just in case that bucket changes.
                    for(size_t szI = szOldSize; szI < szNewSize; ++szI)
                    {
                         new (&a_Buckets[szI]) bucket();
                    }

                    sz_TableSize = szNewSize;
                    calculateMultFactor();
                }

                inline bucket* get_bucket(const KEY& k) throw()
                {
                    return a_Buckets + _hf(k, sz_TableSize);
                }

                inline bool need_resizing() const throw()
                {

                }
            public:
                //typedef iterator void*;
                //typedef const_iterator void*;

                //iterator Insert(KEY& k, VALUE& v);
                //VALUE& Find(Key& k);
                //const VALUE& Find(Key& k);
                //iterator Find(KEY k);
                //const_iterator Find(KEY k);
                //void Delete(KEY& k);
                //void Delete(iterator it);
                //void Delete(const_iterator it);
                class iterator
                {
                    private:
                        entry* p_Entry;
                        bucket* p_Bucket;

                        friend class bucket;

                    public:
                        iterator(entry* pEntry)
                            :p_Entry(pEntry)
                        {
                        }

                        iterator()
                        {
                            p_Entry = NULL;
                        }

                        iterator(const iterator& it)
                        {
                            this->p_Entry = it.p_Entry;
                        }

                        inline VALUE& operator*() const
                        {
                            return p_Entry->_v;
                        }

                        inline bool operator==(const iterator& it) const
                        {
                            return this->p_Entry == it.p_Entry;
                        }

                        inline bool operator!=(const iterator& it) const
                        {
                            return !(*this == it);
                        }

                        inline iterator& operator=(const iterator& it)
                        {
                            this->p_Entry = it.p_Entry;
                        }

                        inline VALUE* operator->() const
                        {
                            return &p_Entry->_v;
                        }

                        inline iterator operator++()
                        {
                            return *this;
                        }

                        inline iterator& operator++(int)
                        {
                            //WRONG!!!
                            //TODO : Change this.
                            return *this;
                        }
                };

            private:
                iterator _EndIt;

            public:
                hash_container(HASH_FUNCTION& hf, size_t szTableSize = 1024, double dLoadFactor = 0.7f, KEY_COMP kc = KEY_COMP())throw(std::bad_alloc)
                    :_hf(hf), sz_TableSize(szTableSize), d_ExpectedLoadFactor(dLoadFactor), _kc(kc)
                {
                    if(d_ExpectedLoadFactor < 0.1f)
                    {
                        d_ExpectedLoadFactor = 0.1f;
                    }

                    a_Buckets = NULL;
                    sz_TableSize = 0;
                    if(szTableSize == 0)
                    {
                        szTableSize = 1;
                    }
                    resize(szTableSize);
                    d_CurrentLoadFactor = 0.0f;
                    sz_EntryCount = 0;

                    _EndIt = iterator(NULL);
                }

                virtual ~hash_container()
                {
                    for(size_t szI = 0; szI < sz_TableSize; ++szI)
                    {
                        a_Buckets[szI].~bucket();
                    }
                }

                inline iterator find(const KEY& k) throw()
                {
                    bucket* pBucket = get_bucket(k);
                    return pBucket->find(k);
                }

                inline bool insert(const KEY& k, const VALUE& v) throw(std::bad_alloc)
                {
                    bucket* pBucket = get_bucket(k);
                    bool bRet = false;
                    try
                    {
                        bRet = pBucket->insert(k, v);
                    }
                    catch(std::bad_alloc& e)
                    {
                        //What now?
                        throw e;
                    }
                    if(bRet == true)
                    {
                        ++sz_EntryCount;
                    }
                    return bRet;
                }

                inline VALUE& operator[](const KEY& k) throw(std::bad_alloc)
                {
                    bucket* pBucket = get_bucket(k);

                }

                inline bool erase(const KEY& k) throw(std::bad_alloc)
                {
                    bucket* pBucket =  get_bucket(k);
                    bool bRet = false;
                    try
                    {
                        bRet = pBucket->erase(k);
                    }
                    catch(std::bad_alloc& e)
                    {
                        throw e;
                    }
                    if(bRet == true)
                    {
                        --sz_EntryCount;
                    }
                    return bRet;
                }

                inline iterator end() const
                {
                    return _EndIt;
                }

                inline size_t size() const
                {
                    return sz_EntryCount;
                }

                inline size_t table_size() const
                {
                    return sz_TableSize;
                }

                inline double current_load_factor() const
                {
                    return d_MultFactor*static_cast<double>(sz_EntryCount);
                }

                inline double expected_load_factor() const
                {
                    return d_ExpectedLoadFactor;
                }
        };
}

#endif

Body:
operator-> should return a pointer to type T (ie. T*).

Postfix increment has to return a copy of the value, since it performs the increment but before the value has been used. Prefix increment can simply return *this after incrementing.

Simple implementations may look like this:

T T::operator++(int)
{
    T temp = *this;
    ++*this;
    return temp;
}

T& T::operator++()
{
    this->value += 1;
    return *this;
}


问:
How to assert url was called from javascript using rspec and capybara

Scenario:

We use capybara integration tests to test that our frontend plumbing (javascript) is connected properly.

Sometimes all we need to validate the test is:

has content rendered properly on the page

has the js called the correct url open interaction

Problem:

Item 1 above is easy. However, with item 2 I can't seem to find an easy way to say:

Assert that url was called from js in browser.

Example:

```<code>it "should call coorect url with correct query string" do
  visit widgets_path

  # THIS IS WHAT I NEED TO KNOW
  expect(something).to receive(:some_method).with(url: "my/test/url", params: {per_page: 2})

  # In other words, I don't want the controller action to run. I don't care about the result since the controller is being tested elsewhere.
  # I just need to know that the correct URL was called with the correct params.

  within 'ul.pagination' do
    click_on '2'
  end
end
</code>```

I've tried mocking the controller action, but there's no way to inspect the params. Or is there? Without inspecting the params, how can I know if the correct stuff was sent? All I know it's the correct route, which isn't enough.

If I could inspect the params then this would be solved... but otherwise?

答:
Capybara integration tests intentionally don't support that. They are end-to-end blackbox tests, shouldn't generally be mocked, and really only support checking for things visible to the user in the browser. In your example case that would mean expecting on whatever visible change is caused by the JS call to the specific URL. Something like</p>

```<code>expect(page).to have_css('div.widget', count: 2)
</code>```

Body:
Scenario:

We use capybara integration tests to test that our frontend plumbing (javascript) is connected properly.

Sometimes all we need to validate the test is:

has content rendered properly on the page

has the js called the correct url open interaction

Problem:

Item 1 above is easy. However, with item 2 I can't seem to find an easy way to say:

Assert that url was called from js in browser.

Example:

it "should call coorect url with correct query string" do
  visit widgets_path

  # THIS IS WHAT I NEED TO KNOW
  expect(something).to receive(:some_method).with(url: "my/test/url", params: {per_page: 2})

  # In other words, I don't want the controller action to run. I don't care about the result since the controller is being tested elsewhere.
  # I just need to know that the correct URL was called with the correct params.

  within 'ul.pagination' do
    click_on '2'
  end
end

I've tried mocking the controller action, but there's no way to inspect the params. Or is there? Without inspecting the params, how can I know if the correct stuff was sent? All I know it's the correct route, which isn't enough.

If I could inspect the params then this would be solved... but otherwise?

Body:
Capybara integration tests intentionally don't support that. They are end-to-end blackbox tests, shouldn't generally be mocked, and really only support checking for things visible to the user in the browser. In your example case that would mean expecting on whatever visible change is caused by the JS call to the specific URL. Something like

expect(page).to have_css('div.widget', count: 2)


问:
Running total on an array of numbers classic asp
I have an array a=Array(1,2,3,4,5,6,7,8,9,10)

I need to add 1+2+3 then 2+3+4 then 3+4+5 and so on until 8+9+10

Or in other words first item plus second item plus third item then second item plus third item plus fourth item and so on

How can I do it in classic asp, here is my attempt. or one of the attempts.

```<code>            Dim p, m, a, t
            a = array(0,1,2,3,4,5,6,7,8,9,10,11,12,12,13,14)
            t = 0
            p = 0
            m = 0
            For x = m To 14
                p = p + 1
                if p < 4 then
                    t = t + a(x)
                end if
                if p = 3 then
                    m = 0
                    p = 0
                    ReDim Preserve arr(UBound(a) - 1)
                    response.Write t & "<br />"
                end if
            Next
</code>```

My plan was to add 4 items, then reset the starting index when it hit the 4th item (that is m = 0) and at this point also get rid of the first item from the array so when it starts again the second item becomes the first item.

答:
I think you're making things more complicated than they need to be. (Either that, or you've oversimplified the question in an effort to remove the identifying details.)</p>

```<code>For i = 0 to UBound(a) - 2
    t = a(i) + a(i+1) + a(i+2)
    Response.Write a(i) & " + " & a(i+1) & " + " & a(i+2) & " = " & t & "<br>"
Next
</code>```

Body:
I have an array a=Array(1,2,3,4,5,6,7,8,9,10)

I need to add 1+2+3 then 2+3+4 then 3+4+5 and so on until 8+9+10

Or in other words first item plus second item plus third item then second item plus third item plus fourth item and so on

How can I do it in classic asp, here is my attempt. or one of the attempts.

            Dim p, m, a, t
            a = array(0,1,2,3,4,5,6,7,8,9,10,11,12,12,13,14)
            t = 0
            p = 0
            m = 0
            For x = m To 14
                p = p + 1
                if p < 4 then
                    t = t + a(x)
                end if
                if p = 3 then
                    m = 0
                    p = 0
                    ReDim Preserve arr(UBound(a) - 1)
                    response.Write t & "
"
                end if
            Next

My plan was to add 4 items, then reset the starting index when it hit the 4th item (that is m = 0) and at this point also get rid of the first item from the array so when it starts again the second item becomes the first item.

Body:
I think you're making things more complicated than they need to be. (Either that, or you've oversimplified the question in an effort to remove the identifying details.)

For i = 0 to UBound(a) - 2
    t = a(i) + a(i+1) + a(i+2)
    Response.Write a(i) & " + " & a(i+1) & " + " & a(i+2) & " = " & t & "<br>"
Next


问:
Given a login name (windows or SQL Server) how can I determine the database user name for a given login using TSQL
If I have a SQL Server login name (windows or SQL Server) how can I determine the database user name for a given login using TSQL. </p>

答:
Within the db context:</p>

```<code>select L.name [Login], U.name [User] from
    sys.server_principals L
inner join
    sys.database_principals U
on
    L.sid = U.sid
WHERE
    L.name = 'LittleBobbyTables'
</code>```

Body:
Within the db context:

select L.name [Login], U.name [User] from
    sys.server_principals L
inner join
    sys.database_principals U
on
    L.sid = U.sid
WHERE
    L.name = 'LittleBobbyTables'


问:
Display only a single state with counties from a full US counties map
Is it possible to display a single state from a full US counties map?

I know I can get each states shape file and counties and create the topojson, but I'd rather work with one file if thats possible.

For example take Mike Bostock's full US county map.
US Counties Map
Would it be possible to show just NY from this?

I haven't seen any examples showing that type of functionality.

答:
I know this is a very late answer. However, it might be helpful for other people in the future.

This is an example of how to extract one state from the USA map file:

```<code><!DOCTYPE html>
<meta charset="utf-8">
<style>

path {
        fill: lightgray;
        stroke: #000000;
        stroke-width: 1.5;
        }

path:hover {
        fill:orange;
        cursor:pointer;
      }

#state-borders {
  fill: white;
  stroke: #000000;
  stroke-width: 10.5px;
  stroke-linejoin: round;
  stroke-linecap: round;
  pointer-events: none;
}

</style>
<body>
  <script src="http://d3js.org/d3.v4.min.js" charset="utf-8"></script>
  <script src="https://d3js.org/topojson.v1.min.js"></script>
<script>

var width = 960,
    height = 500,
    centered;

var projection =  d3.geoAlbersUsa()
    .scale(1370)
    .translate([width / 2, height / 2]);

var path = d3.geoPath()
    .projection(projection);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json("us-counties-github.json",function(json){
  console.log(json);

    svg.selectAll("path")
       .attr("id", "state_fips")
       .data(topojson.feature(json, json.objects.collection).features.filter(function(d) { return d.properties.state_fips == 36; }))
       .enter()
       .append("path")
       .attr("d", path)
       .attr("stroke","white")
       .attr("fill", "gray");

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

*I downloaded the dataset from https://raw.githubusercontent.com/deldersveld/topojson/master/countries/united-states/us-albers-counties.json "the counties are included in this file".

Body:
I know this is a very late answer. However, it might be helpful for other people in the future.

This is an example of how to extract one state from the USA map file:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

path {
        fill: lightgray;
        stroke: #000000;
        stroke-width: 1.5;
        }

path:hover {
        fill:orange;
        cursor:pointer;
      }

#state-borders {
  fill: white;
  stroke: #000000;
  stroke-width: 10.5px;
  stroke-linejoin: round;
  stroke-linecap: round;
  pointer-events: none;
}

</style>
<body>
  <script src="http://d3js.org/d3.v4.min.js" charset="utf-8"></script>
  <script src="https://d3js.org/topojson.v1.min.js"></script>
<script>

var width = 960,
    height = 500,
    centered;

var projection =  d3.geoAlbersUsa()
    .scale(1370)
    .translate([width / 2, height / 2]);

var path = d3.geoPath()
    .projection(projection);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json("us-counties-github.json",function(json){
  console.log(json);

    svg.selectAll("path")
       .attr("id", "state_fips")
       .data(topojson.feature(json, json.objects.collection).features.filter(function(d) { return d.properties.state_fips == 36; }))
       .enter()
       .append("path")
       .attr("d", path)
       .attr("stroke","white")
       .attr("fill", "gray");

    });
</script>

*I downloaded the dataset from https://raw.githubusercontent.com/deldersveld/topojson/master/countries/united-states/us-albers-counties.json "the counties are included in this file".


问:
Angular 4 data binding concept
I am creating an Angular app and need some help with the data binding.

I have a Dashboard where I have different Widgets. Every Widget has a name and a date.
To configure/change this settings I have created a Sidebar that can be shown.
I am using a router to display the dashboard view. And the sidebar is not a children of the dashboard it is outside of the router.

When I click on the settings button on a Widget the Sidebar should open and should be able to show and change the settings of this Widget and than the Widget should run an update function.

I have already tried to work with a shared service but I dont think that this is the best solution because I have multiple Widgets each with different settings object.

答: You cannot use Event Emitters since there is no relationship between two components, so ideal way would be to use is Shared Service.</p>

Title: Angular 4 data binding concept


问:
How to Filter Nested Array Object in DynamoDB
I am very beginner to AWS DynamoDB, I want to scan the DynamoDB with SENDTO.emailAddress = "first@first.com" as FilterExpression.

The DB Structure looks like this

```<code>{
    ID
    NAME
    MESSAGE
    SENDTO[
        {
            name
            emailAddress
        }
    ]
}
</code>```

A Sample Data

```<code>{
    ID: 1,
    NAME: "HELLO",
    MESSAGE: "HELLO WORLD!",
    SENDTO: [
        {
            name: "First",
            emailAddress: "first@first.com"
        },
        {
            name: "Second",
            emailAddress: "second@first.com"
        }
    ]
}
</code>```

I want to retrieve document that match emailAddress. I tried to scan with filter expression and here is my code to retrieve the data. I am using AWS Javascript SDK.

```<code>let params = {
    TableName : "email",
    FilterExpression: "SENDTO.emailAddress = :emailAddress",
    ExpressionAttributeValues: {
        ":emailAddress": "first@first.com",
    }
}

let result = await ctx.docClient.scan(params).promise();
</code>```

答:
In order to find the item by sendto attribute, you need to know both name and emailAddress attribute value. DynamoDB can't find the data by just one of the attributes in an object (i.e. email attribute value alone).

CONTAINS function can be used to find the data in List data type.

CONTAINS is supported for lists: When evaluating "a CONTAINS b", "a"
  can be a list; however, "b" cannot be a set, a map, or a list.

Sample code using Contains:-

```<code>var params = {
    TableName: "email",
    FilterExpression: "contains (SENDTO, :sendToVal)",
    ExpressionAttributeValues: {
        ":sendToVal": {
            "name" : "First",
            "emailAddress" : "first@first.com"
        }
    }
};
</code>```

If you don't know the value of name and emailAddress attribute, you may need to remodel the data to fulfill your use case.

Body:
I am very beginner to AWS DynamoDB, I want to scan the DynamoDB with SENDTO.emailAddress = "first@first.com" as FilterExpression.

The DB Structure looks like this

{
    ID
    NAME
    MESSAGE
    SENDTO[
        {
            name
            emailAddress
        }
    ]
}

A Sample Data

{
    ID: 1,
    NAME: "HELLO",
    MESSAGE: "HELLO WORLD!",
    SENDTO: [
        {
            name: "First",
            emailAddress: "first@first.com"
        },
        {
            name: "Second",
            emailAddress: "second@first.com"
        }
    ]
}

I want to retrieve document that match emailAddress. I tried to scan with filter expression and here is my code to retrieve the data. I am using AWS Javascript SDK.

let params = {
    TableName : "email",
    FilterExpression: "SENDTO.emailAddress = :emailAddress",
    ExpressionAttributeValues: {
        ":emailAddress": "first@first.com",
    }
}

let result = await ctx.docClient.scan(params).promise();

Body:
In order to find the item by sendto attribute, you need to know both name and emailAddress attribute value. DynamoDB can't find the data by just one of the attributes in an object (i.e. email attribute value alone).

CONTAINS function can be used to find the data in List data type.

CONTAINS is supported for lists: When evaluating "a CONTAINS b", "a"
  can be a list; however, "b" cannot be a set, a map, or a list.

Sample code using Contains:-

var params = {
    TableName: "email",
    FilterExpression: "contains (SENDTO, :sendToVal)",
    ExpressionAttributeValues: {
        ":sendToVal": {
            "name" : "First",
            "emailAddress" : "first@first.com"
        }
    }
};

If you don't know the value of name and emailAddress attribute, you may need to remodel the data to fulfill your use case.


问:
Reading dictionary from file in Python
I have a huge base of lockers assigned to people in a file with this structure:

```<code>'paul':'locker.01'
'robert':'locker.02'
'julia':'locker.03'
'rosalind':'locker.04'
</code>```

I need to create a script which will read this file as a dictionary like so:

```<code>{'paul':locker.01
'robert':locker.02
'julia':locker.03
'rosalind':locker.04}
</code>```

So far I've created this script but I'm stuck. Anyone have done this before?

```<code>f = open('C:/file.txt', 'r')
for i in f.readlines():
    i = i[0:-1]
    print(i)
</code>```

答:
Just do:

```<code>result = {}
with open('thefile.txt') as my_file:
    for line in my_file:
        name, locker_number = line.replace("'", "").split(':')
        result[name] = locker_number
print(result)
</code>```

Note that doing this is probably not a good approach. What if there are two Peter, three Julias?

So maybe this is better for you:

```<code>result = {}
with open('thefile.txt') as my_file:
    for line in my_file:
        name, locker_number = line.replace("'", "").split(':')
        if not name in result:
            result[name] = [locker_number]
        else:
            result[name].append(locker_number)

print(result)

for name in result:
    result[name] = ', '.join(result[name])  # will return a string of comma separated lockers.

print(result)
</code>```

This would create a list of locker numbers assigned to that name.

Title: Reading dictionary from file in Python

Body:
I have a huge base of lockers assigned to people in a file with this structure:

'paul':'locker.01'
'robert':'locker.02'
'julia':'locker.03'
'rosalind':'locker.04'

I need to create a script which will read this file as a dictionary like so:

{'paul':locker.01
'robert':locker.02
'julia':locker.03
'rosalind':locker.04}

So far I've created this script but I'm stuck. Anyone have done this before?

f = open('C:/file.txt', 'r')
for i in f.readlines():
    i = i[0:-1]
    print(i)

Body:
Just do:

result = {}
with open('thefile.txt') as my_file:
    for line in my_file:
        name, locker_number = line.replace("'", "").split(':')
        result[name] = locker_number
print(result)

Note that doing this is probably not a good approach. What if there are two Peter, three Julias?

So maybe this is better for you:

result = {}
with open('thefile.txt') as my_file:
    for line in my_file:
        name, locker_number = line.replace("'", "").split(':')
        if not name in result:
            result[name] = [locker_number]
        else:
            result[name].append(locker_number)

print(result)

for name in result:
    result[name] = ', '.join(result[name])  # will return a string of comma separated lockers.

print(result)

This would create a list of locker numbers assigned to that name.


问:
New versioning NSNotificationCenter in reactive swift
I would like to know below lines of code I mentioned NSNotificationCenter in swift 3.0 can be converted into RxSwif/RxCocoa</p>

```<code>let imageDataDict:[String: UIImage] = ["image": image]

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

// handle notification
func showSpinningWheel(notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
</code>```

答:
I'm assuming you are asking how to do this in ReactiveCocoa.
In ReactiveCocoa, all extensions are available via the .reactive member:

```<code>extension Notification.Name {
  static let myNotification = Notification.Name("myNotification")
}

NotificationCenter.default.reactive.notifications(forName: .myNotification)
  .take(duringLifetimeOf: self)
  .observeValues {
    if let image = $0.userInfo?["image"] as? UIImage {
      // do something with your image
    }
}

NotificationCenter.default.post(name: .myNotification, object: nil, userInfo: ["image": image])
</code>```

Edit: Thanks @jjoelson for mentioning disposal of the observation.

Body:
I would like to know below lines of code I mentioned NSNotificationCenter in swift 3.0 can be converted into RxSwif/RxCocoa

let imageDataDict:[String: UIImage] = ["image": image]

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

// handle notification
func showSpinningWheel(notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}

Body:
I'm assuming you are asking how to do this in ReactiveCocoa.
In ReactiveCocoa, all extensions are available via the .reactive member:

extension Notification.Name {
  static let myNotification = Notification.Name("myNotification")
}

NotificationCenter.default.reactive.notifications(forName: .myNotification)
  .take(duringLifetimeOf: self)
  .observeValues {
    if let image = $0.userInfo?["image"] as? UIImage {
      // do something with your image
    }
}

NotificationCenter.default.post(name: .myNotification, object: nil, userInfo: ["image": image])

Edit: Thanks @jjoelson for mentioning disposal of the observation.


问:
How to properly stub a function return value?

Premise: JS ES6, NodeJS

Testing Framework: TAP

Mocking Library: testdouble.js

I am attempting to mock the return value for the method of my class and keep receiving this error:

not ok Unsatisfied verification on test double.    Wanted:     - called with (true).    But there were no invocations of the test double.

Here is my testing code:

```<code>// Imports for unit testing
const tap = require('tap');
const Subject = require('../src/iTunesClient.js');
const td = require('testdouble');

let reqJson;

// Ensure the iTunes class methods are called
tap.test('iTunesClient class methods function as intended', (t) => {
  t.beforeEach((ready) => {
    reqJson = td.replace('../src/reqJson.js');
    ready();
  });

  t.afterEach((ready) => {
    td.reset();
    ready();
  });

  t.test('iTunesClient.getData', (assert) => {
    const callback = td.function();
    const subject = new Subject();
    subject.setTerm('abc 123');
    subject.setURL();

    td.when(reqJson.get(td.callback)).thenCallback(true);

    subject.getData(callback);

    td.verify(callback(true));
    assert.end();
  });

  t.end();
});
</code>```

Specifically, this line is related to my issue:

```<code>td.verify(callback(true));
</code>```

How can I fake the callback value of true for reqJson.get()? Right now, Subject.geData() is a method of the iTunesClient class which calls another file, reqJson.js, to use its exported get() method.

答:
It's a little hard to tell from your example, but it looks like you're requiring iTunesClient before you call td.replace. In this case, the real reqJson module will be required and cached on line 3.

You need to call td.replace early enough to avoid this, e.g. in between requiring tap and iTunesClient.

Body:
Premise: JS ES6, NodeJS

Testing Framework: TAP

Mocking Library: testdouble.js

I am attempting to mock the return value for the method of my class and keep receiving this error:

not ok Unsatisfied verification on test double.    Wanted:     - called with (true).    But there were no invocations of the test double.

Here is my testing code:

// Imports for unit testing
const tap = require('tap');
const Subject = require('../src/iTunesClient.js');
const td = require('testdouble');

let reqJson;

// Ensure the iTunes class methods are called
tap.test('iTunesClient class methods function as intended', (t) => {
  t.beforeEach((ready) => {
    reqJson = td.replace('../src/reqJson.js');
    ready();
  });

  t.afterEach((ready) => {
    td.reset();
    ready();
  });

  t.test('iTunesClient.getData', (assert) => {
    const callback = td.function();
    const subject = new Subject();
    subject.setTerm('abc 123');
    subject.setURL();

    td.when(reqJson.get(td.callback)).thenCallback(true);

    subject.getData(callback);

    td.verify(callback(true));
    assert.end();
  });

  t.end();
});

Specifically, this line is related to my issue:

td.verify(callback(true));

How can I fake the callback value of true for reqJson.get()? Right now, Subject.geData() is a method of the iTunesClient class which calls another file, reqJson.js, to use its exported get() method.


问:
Implementing component require property in Angular 1.5 components
I am having no joy with implementing require: {} property as part of an angular component. Allow me to demonstrate with an example I have.

This is the component/directive that supposed to fetch a list of judgements. Nothing very fancy, just a simple factory call.

```<code>// judgements.component.js
function JudgementsController(GetJudgements) {
    var ctrl = this;

    ctrl.Get = function () {
        GetJudgements.get().$promise.then(
            function (data) {
                ctrl.Judgements = data.judgements;
            }, function (error) {
                // show error message
            });
    }

    ctrl.$onInit = function () {
        ctrl.Get();
    };
}

angular
    .module('App')
    //.component('cJudgements', {
    //    controller: JudgementsController,
    //});
    .directive('cJudgements', function () {
        return {
            scope: true,
            controller: 'JudgementsController',
            //bindToController: true,
        };
    });
</code>```

I am trying to implement component require property to give me access to ctrl.Judgements from the above component/directive as follows:

```<code>// list.component.js
function ListController(GetList, GetJudgements) {
    var ctrl = this;
    ctrl.list = [];

    ctrl.Get = function () {
        GetList.get().$promise.then(
            function (data) {
                ctrl.list = data.list;
            }, function (error) {
                // show error message
            });
    };

    //ctrl.GetJudgements = function () {
    //    GetJudgements.get().$promise.then(
    //        function (data) {
    //            ctrl.Judgements = data.judgements;
    //        }, function (error) {
    //            // show error message
    //        });
    //}

    ctrl.$onInit = function () {
        ctrl.Get();
        //ctrl.GetJudgements();
    };
}

angular
    .module('App')
    .component('cTheList', {
        bindings: {
            listid: '<',
        },
        controller: ListController,
        controllerAs: 'ctrl',
        require: {
            jCtrl: 'cJudgements',
        },
        template: `
            <c-list-item ng-repeat="item in ctrl.list"
                         item="item"
                         judgements="ctrl.Judgements"></c-list-item>
           <!--
           obviously the reference to judgements here needs to change
           or even better to be moved into require of cListItem component
           -->
        `,
    });
</code>```

Nice and simple no magic involved. A keen reader probably noticed GetJudgement service call in the ListController. This is what I am trying to remove from TheList component using require property.

The reason? Is actually simple. I want to stop database being hammered by Judgement requests as much as possible. It's a static list and there is really no need to request it more than once per instance of the app.

So far I have only been successful with receiving the following error message:

```<code>Error: $compile:ctreq
Missing Required Controller
Controller 'cJudgements', required by directive 'cTheList', can't be found!
</code>```

Can anyone see what I am doing wrong?

PS: I am using angular 1.5

PSS: I do not mind which way cJudgement is implemented (directive or component).

PSSS: If someone wonders I have tried using jCtrl: '^cJudgements'.

PSSSS: And multiple ^s for that matter just in case.

Edit

@Kindzoku posted a link to the article that I have read before posting the question. I hope this also helps someone in understanding $onInit and require in Angular 1.5+.

Plunker

Due to popular demand I made a plunker example.

答:
@iiminov has the right answer. No parent HTML c-judgements was defined.

Working plunker.

Body:
I am having no joy with implementing require: {} property as part of an angular component. Allow me to demonstrate with an example I have.

This is the component/directive that supposed to fetch a list of judgements. Nothing very fancy, just a simple factory call.

// judgements.component.js
function JudgementsController(GetJudgements) {
    var ctrl = this;

    ctrl.Get = function () {
        GetJudgements.get().$promise.then(
            function (data) {
                ctrl.Judgements = data.judgements;
            }, function (error) {
                // show error message
            });
    }

    ctrl.$onInit = function () {
        ctrl.Get();
    };
}

angular
    .module('App')
    //.component('cJudgements', {
    //    controller: JudgementsController,
    //});
    .directive('cJudgements', function () {
        return {
            scope: true,
            controller: 'JudgementsController',
            //bindToController: true,
        };
    });

I am trying to implement component require property to give me access to ctrl.Judgements from the above component/directive as follows:

// list.component.js
function ListController(GetList, GetJudgements) {
    var ctrl = this;
    ctrl.list = [];

    ctrl.Get = function () {
        GetList.get().$promise.then(
            function (data) {
                ctrl.list = data.list;
            }, function (error) {
                // show error message
            });
    };

    //ctrl.GetJudgements = function () {
    //    GetJudgements.get().$promise.then(
    //        function (data) {
    //            ctrl.Judgements = data.judgements;
    //        }, function (error) {
    //            // show error message
    //        });
    //}

    ctrl.$onInit = function () {
        ctrl.Get();
        //ctrl.GetJudgements();
    };
}

angular
    .module('App')
    .component('cTheList', {
        bindings: {
            listid: '<',
        },
        controller: ListController,
        controllerAs: 'ctrl',
        require: {
            jCtrl: 'cJudgements',
        },
        template: `
            <c-list-item ng-repeat="item in ctrl.list"
                         item="item"
                         judgements="ctrl.Judgements"></c-list-item>

        `,
    });

Nice and simple no magic involved. A keen reader probably noticed GetJudgement service call in the ListController. This is what I am trying to remove from TheList component using require property.

The reason? Is actually simple. I want to stop database being hammered by Judgement requests as much as possible. It's a static list and there is really no need to request it more than once per instance of the app.

So far I have only been successful with receiving the following error message:

Error: $compile:ctreq
Missing Required Controller
Controller 'cJudgements', required by directive 'cTheList', can't be found!

Can anyone see what I am doing wrong?

PS: I am using angular 1.5

PSS: I do not mind which way cJudgement is implemented (directive or component).

PSSS: If someone wonders I have tried using jCtrl: '^cJudgements'.

PSSSS: And multiple ^s for that matter just in case.

Edit

@Kindzoku posted a link to the article that I have read before posting the question. I hope this also helps someone in understanding $onInit and require in Angular 1.5+.

Plunker

Due to popular demand I made a plunker example.


问:
Change Nginx root directory to workspace folder path
Issue

I installed Nginx with brew on Mac OSX. Then I modified /usr/local/etc/nginx/nginx.conf as below and got a server 500 error:

```<code>server {
    listen       666;
    server_name  localhost;
    root /Users/username/Desktop/workspace/projectname/dist;
    location / {
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}
</code>```

What I tried

I knew that brew install default root is /usr/local/var/www so I was able to get it working by paste dist folder into /usr/local/var/www and update Nginx config like this:

```<code>server {
    listen       666;
    server_name  localhost;
    root /usr/local/var/www/dist;
    location / {
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}
</code>```

Other issue

Even after I paste dist folder into /usr/local/var/www I still got 500 error by updating root like the followings:

```<code>root /dist
root dist
root ./dist
</code>```

Why does default

```<code>root index.html
</code>```

gets displayed when I first run Nginx ? but I have to specify my dist folder with full path like /usr/local/var/www/dist ? Can someone please explain.

Goal

I want to be able to change root directory to my dist folder in workspace so I don't need to paste the dist folder into /usr/local/var/www every time after I rebuild.

答: I'm going to assume permissions is the problem. nginx runs as user "www-data" unless you change it. Your directories and files need to allow that user and have their directories set as 755 and the files set to 644. </p>

Body:
Issue

I installed Nginx with brew on Mac OSX. Then I modified /usr/local/etc/nginx/nginx.conf as below and got a server 500 error:

server {
    listen       666;
    server_name  localhost;
    root /Users/username/Desktop/workspace/projectname/dist;
    location / {
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

What I tried

I knew that brew install default root is /usr/local/var/www so I was able to get it working by paste dist folder into /usr/local/var/www and update Nginx config like this:

server {
    listen       666;
    server_name  localhost;
    root /usr/local/var/www/dist;
    location / {
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

Other issue

Even after I paste dist folder into /usr/local/var/www I still got 500 error by updating root like the followings:

root /dist
root dist
root ./dist

Why does default

root index.html

gets displayed when I first run Nginx ? but I have to specify my dist folder with full path like /usr/local/var/www/dist ? Can someone please explain.

Goal

I want to be able to change root directory to my dist folder in workspace so I don't need to paste the dist folder into /usr/local/var/www every time after I rebuild.


问:
Powershell Code for a birthday cake
My son is a computer science major, and his birthday is coming up. I want to create a code themed cake for him. I have studied PowerShell code and created what I think is something correct and fun. However, I'm unsure and was turned on to this site to get help with it. This is what I have ... JularJ is my son's display name for his video games.</p>

```<code>$day=11/21/2017
$today=Get-Date
if (Today=$day)
{
    echo"Happy 18th Birthday [Jular]"}
else
{
    echo"Eat Cake Anyway"
}
</code>```

答:
Try the following code. It works every year ;)</p>

```<code>cls

$day=Get-Date -Day 21 -Month 11 -Year 2000
$today=Get-Date

if ($today.Day -eq $day.Day -and $today.Month -eq $day.Month)
{
    $age = (New-Object DateTime -ArgumentList ($today - $day).Ticks).Year

    1..$age | %{'.' * $_}
    "Happy {0}th Birthday [Jular] ! " -f $age
    $age..1 | %{'.' * $_}
}
else
{
    "Eat Cake Anyway"
}
</code>```

Title: Powershell Code for a birthday cake

Body:
My son is a computer science major, and his birthday is coming up. I want to create a code themed cake for him. I have studied PowerShell code and created what I think is something correct and fun. However, I'm unsure and was turned on to this site to get help with it. This is what I have ... JularJ is my son's display name for his video games.

$day=11/21/2017
$today=Get-Date
if (Today=$day)
{
    echo"Happy 18th Birthday [Jular]"}
else
{
    echo"Eat Cake Anyway"
}

Body:
Try the following code. It works every year ;)

cls

$day=Get-Date -Day 21 -Month 11 -Year 2000
$today=Get-Date

if ($today.Day -eq $day.Day -and $today.Month -eq $day.Month)
{
    $age = (New-Object DateTime -ArgumentList ($today - $day).Ticks).Year

    1..$age | %{'.' * $_}
    "Happy {0}th Birthday [Jular] ! " -f $age
    $age..1 | %{'.' * $_}
}
else
{
    "Eat Cake Anyway"
}


问:
How can I tell why my node app is crashing on Heroku? (HTML, Stripe, Heroku, NodeJS)
So, I've developed a website (HTML) that has an embedded payment form from Stripe called Checkout. When you visit the website, it prompts you to enter your credit card information, so the checkout form is working correctly.
The issue I'm having is processing the token once it's created.

I'm extremely new to web development and I've never written server code before so please, bear with me.
I've been following guides (Process payments with Node, Vue, Stripe & How to set up Stripe payments with Node.js) and stripes documentation on tokenization to create charges using server-side code (Stripe Checkout)

I understand that I have to have Heroku set up to process the charges so I created an account and set up an app from my terminal. I made a new directory that has the modules required (stripe, express, and bodyParser) and I have this code in my server.js file:

It deploys to Heroku successfully but crashes. This is what is being returned in the console:

What am I doing wrong? Any assistance would be a great help.

答:
You are missing a vital piece:

```<code>// Start the server
app.listen(port, function(){
  console.log('Server listening on port ' + port)
});
</code>```

You don't seem to start the server in your application. This should be in the bottom of server.js. You also have to remember to set the port:

```<code>var port = process.env.PORT || 3000;
</code>```

It goes above app.listen of course.

I can't tell for sure if that will fix all your errors, but you have to start with starting the server first.

Also, remember to check for errors in callbacks. In the callback for create you are not doing that. E.g.

```<code>if (err){
    console.error(err);
    res.json({ error: err, charge: false });
} else {
    // send response with charge data
    res.json({ error: false, charge: charge });
}
</code>```

You are doing res.send() whether or not there are errors. I doubt that this has anything to do with the Heroku error though.

Body:
You are missing a vital piece:

// Start the server
app.listen(port, function(){
  console.log('Server listening on port ' + port)
});

You don't seem to start the server in your application. This should be in the bottom of server.js. You also have to remember to set the port:

var port = process.env.PORT || 3000;

It goes above app.listen of course.

I can't tell for sure if that will fix all your errors, but you have to start with starting the server first.

Also, remember to check for errors in callbacks. In the callback for create you are not doing that. E.g.

if (err){
    console.error(err);
    res.json({ error: err, charge: false });
} else {
    // send response with charge data
    res.json({ error: false, charge: charge });
}

You are doing res.send() whether or not there are errors. I doubt that this has anything to do with the Heroku error though.


问:
Using FOR's i = x in a var name
I'm trying to use a for loop to give values to three vars (but it could be 2 or even 100 vars, that's not the problem, I guess), and I want to use the value of i to indicate a var name with the name "num1" for example making the code look like num[i] = x or num + [i] = x (I tried both but none worked). I'm not sure what I am doing wrong. Here's my code so far:

```<code>function numbers() {
  var num1, num2, num3 = 0;

  for (var i = 1; i < 4; i++) {
    num[i] = Math.floor(Math.random() * 999);
    document.getElementById("n1").innerHTML = num[i];
  }
}
</code>```

I also want to make the document.getElementById("n1").innerHTML get the number in "n[number]" from the I value, something like "n" + [i], but it doesn't work neither.

答:
You could use window['name'] like :

```<code> function numbers() {
   var num1, num2, num3 = 0;

   for (var i = 1; i < 4; i++) {
     window['num'+i] = Math.floor(Math.random() * 999);
     document.getElementById("n1").innerHTML = window['num'+i];
   }
 }
</code>```

Hope this helps.

Title: Using FOR's i = x in a var name

Body:
I'm trying to use a for loop to give values to three vars (but it could be 2 or even 100 vars, that's not the problem, I guess), and I want to use the value of i to indicate a var name with the name "num1" for example making the code look like num[i] = x or num + [i] = x (I tried both but none worked). I'm not sure what I am doing wrong. Here's my code so far:

function numbers() {
  var num1, num2, num3 = 0;

  for (var i = 1; i < 4; i++) {
    num[i] = Math.floor(Math.random() * 999);
    document.getElementById("n1").innerHTML = num[i];
  }
}

I also want to make the document.getElementById("n1").innerHTML get the number in "n[number]" from the I value, something like "n" + [i], but it doesn't work neither.

Body:
You could use window['name'] like :

 function numbers() {
   var num1, num2, num3 = 0;

   for (var i = 1; i < 4; i++) {
     window['num'+i] = Math.floor(Math.random() * 999);
     document.getElementById("n1").innerHTML = window['num'+i];
   }
 }

Hope this helps.


答:
You can cast the inner object to an array and implode that.

```<code>$string = implode(',', (array) $object[0]);
</code>```

In general, casting objects to arrays and vice versa isn't always a good idea. But in this case if you don't care about the keys and just need the values, it should work consistently.

Title: Create a List of Values from a JSON Object in PHP

Body:
How can I convert the following JSON object array into an ordered list of values using PHP?

JSON Object

array:1 [▼
  0 => {#226 ▼
    +"sum(hour0)": "2098571"
    +"sum(hour1)": "1316168"
    +"sum(hour2)": "643316"
    +"sum(hour3)": "210643"
    +"sum(hour4)": "97135"
    +"sum(hour5)": "25334"
    +"sum(hour6)": "20451"
    +"sum(hour7)": "20639"
    +"sum(hour8)": "20382"
    +"sum(hour9)": "16966"
    +"sum(hour10)": "25301"
    +"sum(hour11)": "17352"
    +"sum(hour12)": "23883"
    +"sum(hour13)": "425294"
    +"sum(hour14)": "3776592"
    +"sum(hour15)": "5292751"
    +"sum(hour16)": "5945308"
    +"sum(hour17)": "952250"
    +"sum(hour18)": "0"
    +"sum(hour19)": "0"
    +"sum(hour20)": "0"
    +"sum(hour21)": "0"
    +"sum(hour22)": "0"
    +"sum(hour23)": "0"
  }
]

Desired Output

2098571,1315168,643316,210643,...

Body:
You can cast the inner object to an array and implode that.

$string = implode(',', (array) $object[0]);

In general, casting objects to arrays and vice versa isn't always a good idea. But in this case if you don't care about the keys and just need the values, it should work consistently.


问:
How to insert from two lists into a list of dictionaries with identical keynames in Python 3.6.1
I am a newbie to Python and dictionaries. Using Python 3.6.1. I have googled similar issues, but it seems like solutions that others use involve dictionaries with different keys, and that many answers are related to older versions of Python. Any help is appreciated!

I have the following list of dictionaries that returns this when printed:

```<code>[{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None}]
</code>```

I have the following lists from which I want to insert the values into the above list of dictionaries:

```<code>coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate']

coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]]

heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height']

heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333]
</code>```

From these lists I want to insert the values into the list of dictionaries. So that the result follows the following pattern:
the first entry of the first valuelist will correspond to the first value of the second valuelist (where both end up in the same dictionary).
Obviously I would wish to not use the coordkeys, and heightkeys lists if that is possible.

To illlustrate the pattern the end result will have, with all the values from both lists, the end result starts as follows:

[{'Coordinate': [44,33], 'Height': 333},
    {'Coordinate': [55,22], 'Height': 444},
    # And so on until the end of both lists
    ]

I tried to play with only one list as follows:

```<code>geographic_details = dict(list(zip(coordkeys, coordvalues)))
</code>```

But a print of the output returns only the last entry from the coordinate-values list, and not all of the values from the list:

```<code>{'Coordinate': [79, 91]}
</code>```

So obviously only the last key-value pair is kept, because there are several keys with the same name. zip or this way of using zip seems like not the way to go here.

EDIT:

I tried adding from both lists by doing this, but it seems like this is not allowed.:

This last line of code missed an ending parenthesis. Now I added it so it looks like this:

```<code>geographic_details = dict(list(zip(coordkeys, coordvalues), zip(heightkeys, heightvalues)))
</code>```

However a new error is returned:

```<code>TypeError: list() takes at most 1 argument (2 given)
</code>```

答:
Do you want something like this ?

```<code>import numpy as np
numpy_array=[{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None}]

coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate']

coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]]

heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height']

heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333]

for index,value in enumerate(zip(coordvalues,heightvalues)):
    for index_1,value_1 in enumerate(numpy_array):
        for key,value_2 in value_1.items():
            if index==index_1:
                if isinstance(value_2,np.ndarray):
                    value_2[0]=value[0][0]
                    value_2[1]=value[0][1]
                value_1['Height']=value[1]

print(numpy_array)
</code>```

output:

```<code>[{'Height': 333, 'Coordinate': array([44, 33], dtype=object)}, {'Height': 444, 'Coordinate': array([55, 22], dtype=object)}, {'Height': 555, 'Coordinate': array([77, 66], dtype=object)}, {'Height': 666, 'Coordinate': array([88, 99], dtype=object)}, {'Height': 777, 'Coordinate': array([77, 11], dtype=object)}, {'Height': 888, 'Coordinate': array([46, 78], dtype=object)}, {'Height': 999, 'Coordinate': array([44, 33], dtype=object)}, {'Height': 222, 'Coordinate': array([13, 92], dtype=object)}, {'Height': 2222, 'Coordinate': array([21, 69], dtype=object)}, {'Height': 3333, 'Coordinate': array([79, 91], dtype=object)}]
</code>```

Body:
I am a newbie to Python and dictionaries. Using Python 3.6.1. I have googled similar issues, but it seems like solutions that others use involve dictionaries with different keys, and that many answers are related to older versions of Python. Any help is appreciated!

I have the following list of dictionaries that returns this when printed:

[{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None}]

I have the following lists from which I want to insert the values into the above list of dictionaries:

coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate']

coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]]

heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height']

heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333]

From these lists I want to insert the values into the list of dictionaries. So that the result follows the following pattern:
the first entry of the first valuelist will correspond to the first value of the second valuelist (where both end up in the same dictionary).
Obviously I would wish to not use the coordkeys, and heightkeys lists if that is possible.

To illlustrate the pattern the end result will have, with all the values from both lists, the end result starts as follows:

[{'Coordinate': [44,33], 'Height': 333},
    {'Coordinate': [55,22], 'Height': 444},
    # And so on until the end of both lists
    ]

I tried to play with only one list as follows:

geographic_details = dict(list(zip(coordkeys, coordvalues)))

But a print of the output returns only the last entry from the coordinate-values list, and not all of the values from the list:

{'Coordinate': [79, 91]}

So obviously only the last key-value pair is kept, because there are several keys with the same name. zip or this way of using zip seems like not the way to go here.

EDIT:

I tried adding from both lists by doing this, but it seems like this is not allowed.:

This last line of code missed an ending parenthesis. Now I added it so it looks like this:

geographic_details = dict(list(zip(coordkeys, coordvalues), zip(heightkeys, heightvalues)))

However a new error is returned:

TypeError: list() takes at most 1 argument (2 given)

Body:
Do you want something like this ?

import numpy as np
numpy_array=[{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None},
{'Coordinate': np.array([None, None], dtype=object), 'Height': None}]

coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate']

coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]]

heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height']

heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333]

for index,value in enumerate(zip(coordvalues,heightvalues)):
    for index_1,value_1 in enumerate(numpy_array):
        for key,value_2 in value_1.items():
            if index==index_1:
                if isinstance(value_2,np.ndarray):
                    value_2[0]=value[0][0]
                    value_2[1]=value[0][1]
                value_1['Height']=value[1]

print(numpy_array)

output:

[{'Height': 333, 'Coordinate': array([44, 33], dtype=object)}, {'Height': 444, 'Coordinate': array([55, 22], dtype=object)}, {'Height': 555, 'Coordinate': array([77, 66], dtype=object)}, {'Height': 666, 'Coordinate': array([88, 99], dtype=object)}, {'Height': 777, 'Coordinate': array([77, 11], dtype=object)}, {'Height': 888, 'Coordinate': array([46, 78], dtype=object)}, {'Height': 999, 'Coordinate': array([44, 33], dtype=object)}, {'Height': 222, 'Coordinate': array([13, 92], dtype=object)}, {'Height': 2222, 'Coordinate': array([21, 69], dtype=object)}, {'Height': 3333, 'Coordinate': array([79, 91], dtype=object)}]


问:
How do I ignore a directory in the root of my git repository, but include it further down in the tree?
I need to use .gitignore to exclude a directory in the root of my repository.  However, other directories with the same name exist deeper in the directory tree, and I need those to be included.  It seems that when I put the name of the directory into .gitignore, it catches all of these directories, not just the one I need to ignore.  I understand that .gitignore is actually not a list of files, but patterns.  So how can I construct a pattern to ignore just a file in my root directory, but not files with the same name further down?

答:
Use a leading /

```<code>  /file.x
</code>```

That will only match a top level file.x but not one lower down, in "want/file.x", say.

OwnerDisplayName: skiphoppy

Body:
Use a leading /

  /file.x

That will only match a top level file.x but not one lower down, in "want/file.x", say.

OwnerDisplayName: rq


问:
Signal (SIGTERM) not received by subprocess on Windows
I have a server that starts a subprocess, and I can manage to do a send_signal(SIGTERM) which will kill the process. But not gracefully.
If I call my subprocess from shell (i.e. as a single process), the defined signal handler will kick in and exit gracefully.

server.py:
(so.. from another script I first call start_app(), and later exit_app()

```<code>def start_app():
    app = subprocess.Popen("python app.py")

def exit_app():
    p = app.poll()
    if p==None:
        print("Subprocess is alive") # debug
    app.send_signal(signal.SIGTERM)
</code>```

app.py

```<code>def exit_signal_handler(signal, frame):
    print("Terminate signal received")
    app.exit()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    signal.signal(signal.SIGTERM, exit_signal_handler)
    signal.signal(signal.SIGINT, exit_signal_handler)
    sys.exit(app.exec())
</code>```

Again, if I call app.py from shell and send a SIGTERMsignal I get a trace Terminate signal received and app closes.
But when app.py is started by server and I call exit_app in server, I get a trace Subprocess is alive (from server.py) and app is killed but the signal is not caught in app's signalhandler exit_signal_handler

EDIT:
It seems send_signal() doesn't send a signal to the subprocess in the sense that subprocess catches the signal. It send`s a signal for an action to take place on the subprocess:

```<code>    def send_signal(self, sig):
        """Send a signal to the process
        """
        if sig == signal.SIGTERM:
            self.terminate()
        elif sig == signal.CTRL_C_EVENT:
            os.kill(self.pid, signal.CTRL_C_EVENT)
        elif sig == signal.CTRL_BREAK_EVENT:
            os.kill(self.pid, signal.CTRL_BREAK_EVENT)
        else:
            raise ValueError("Unsupported signal: {}".format(sig))
</code>```

This probably answers my question but I'll leave it open...

答:
As you are using Windows, SIGTERM handler is useless, more reference:

On Windows, the C runtime implements the six signals that are required by standard C: SIGINT, SIGABRT, SIGTERM, SIGSEGV, SIGILL, and SIGFPE.

SIGABRT and SIGTERM are implemented just for the current process.

But you could use signal.CTRL_BREAK_EVENT as an alternative.

I.e. create a signal handler in app.py that handles SIGBREAK, but send the CTRL_BREAK_EVENT from the parent. Also, make sure to start your subprocess using creationflags=subprocess.CREATE_NEW_PROCESS_GROUP (otherwise it will kill the parent as well)

```<code>app = subprocess.Popen("python app.py", shell=True, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
time.sleep(1)

while 1:
    p = app.poll()
    if p is not None:
        break
    app.send_signal(signal.CTRL_BREAK_EVENT)
    time.sleep(2)
</code>```

app.py:

```<code>exit = False

def exit_signal_handler(signal, frame):
    global exit
    print("Terminate signal received")
    exit = True

signal.signal(signal.SIGBREAK, exit_signal_handler)
while not exit:
    pass
</code>```

Body:
I have a server that starts a subprocess, and I can manage to do a send_signal(SIGTERM) which will kill the process. But not gracefully.
If I call my subprocess from shell (i.e. as a single process), the defined signal handler will kick in and exit gracefully.

server.py:
(so.. from another script I first call start_app(), and later exit_app()

def start_app():
    app = subprocess.Popen("python app.py")

def exit_app():
    p = app.poll()
    if p==None:
        print("Subprocess is alive") # debug
    app.send_signal(signal.SIGTERM)

app.py

def exit_signal_handler(signal, frame):
    print("Terminate signal received")
    app.exit()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    signal.signal(signal.SIGTERM, exit_signal_handler)
    signal.signal(signal.SIGINT, exit_signal_handler)
    sys.exit(app.exec())

Again, if I call app.py from shell and send a SIGTERMsignal I get a trace Terminate signal received and app closes.
But when app.py is started by server and I call exit_app in server, I get a trace Subprocess is alive (from server.py) and app is killed but the signal is not caught in app's signalhandler exit_signal_handler

EDIT:
It seems send_signal() doesn't send a signal to the subprocess in the sense that subprocess catches the signal. It send`s a signal for an action to take place on the subprocess:

    def send_signal(self, sig):
        """Send a signal to the process
        """
        if sig == signal.SIGTERM:
            self.terminate()
        elif sig == signal.CTRL_C_EVENT:
            os.kill(self.pid, signal.CTRL_C_EVENT)
        elif sig == signal.CTRL_BREAK_EVENT:
            os.kill(self.pid, signal.CTRL_BREAK_EVENT)
        else:
            raise ValueError("Unsupported signal: {}".format(sig))

This probably answers my question but I'll leave it open...

Body:
As you are using Windows, SIGTERM handler is useless, more reference:

On Windows, the C runtime implements the six signals that are required by standard C: SIGINT, SIGABRT, SIGTERM, SIGSEGV, SIGILL, and SIGFPE.

SIGABRT and SIGTERM are implemented just for the current process.

But you could use signal.CTRL_BREAK_EVENT as an alternative.

I.e. create a signal handler in app.py that handles SIGBREAK, but send the CTRL_BREAK_EVENT from the parent. Also, make sure to start your subprocess using creationflags=subprocess.CREATE_NEW_PROCESS_GROUP (otherwise it will kill the parent as well)

app = subprocess.Popen("python app.py", shell=True, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
time.sleep(1)

while 1:
    p = app.poll()
    if p is not None:
        break
    app.send_signal(signal.CTRL_BREAK_EVENT)
    time.sleep(2)

app.py:

exit = False

def exit_signal_handler(signal, frame):
    global exit
    print("Terminate signal received")
    exit = True

signal.signal(signal.SIGBREAK, exit_signal_handler)
while not exit:
    pass


问:
Create a program to inject XML code into a file
I am looking to create a program that essentially creates an XML file and injects specific code based on check boxes.

Example: User clicks box for "Action A" and it writes to a file the specific line of code needed for that action.

My goal is to make it easy for end users to generate XML files for an application without understanding XML in general.

What coding language should I use?
What language would allow for a graphical interface?

Thanks!

答: Maybe go with Java. You can use Netbeans IDE for that. You can use Swing in java to create the UI and Java I/O to output the XML to be generated by user responses. </p>


问:
Getting lines one by one to the dynamically allocated char array
Is this possible to get lines from file one by one and save them to the char array which size is determined by the number of characters in each line?</p>

答:
from
https://linux.die.net/man/3/getline

```<code>ssize_t getline(char **lineptr, size_t *n, FILE *stream);
</code>```

getline automatically allocates lineptr if it is NULL or not large enough to contain the string

Body:
from
https://linux.die.net/man/3/getline

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

getline automatically allocates lineptr if it is NULL or not large enough to contain the string


问:
How does Anaconda work with installing packages?
I just downloaded anaconda and downloaded their basic R package.

I also got some packages from anaconda, using the anaconda terminal commands that they provide on their website.

My question is -- when I am starting a new R session in r studio, do I still need to install.packages()? Can I just load the package?

When I press libary(rJava) for example -- the R command line doesn't say anything back on whether it was successful, that's why I'm not sure. Thanks.

答: if you have installed the R packages via the R command line then you can just directly load them. I would recommend that you use the command line rather than R studio.</p>


问:
How to refresh a page on browser using selenium-webdriver?
Follow the below part of the code:

```<code>driver.get "https://example.com/"

element = driver.find_element :name => "username"
element.send_keys "*****"
element = driver.find_element :name => "password"
element.send_keys "*****"
element.submit
</code>```

Now point is when the driver opened the URL on the browser, Some times
the next page to which username and password has to be put by the
script, not coming- which causes the script to failed. Some intermediate
page is coming asking us to click on 'retry button' or 'refresh the
page'. Thus the script whenever such case occurred stopped execution, as
not getting the mentioned element.

So is there any way to refresh that intermediate page with "sleep"
before going to the "Log-in" page, so that script can run in one go?

答:
For Capybara, I think Tommyixi's comment is the best:</p>

```
visit current_path
```

Body:
Follow the below part of the code:

driver.get "https://example.com/"

element = driver.find_element :name => "username"
element.send_keys "*****"
element = driver.find_element :name => "password"
element.send_keys "*****"
element.submit

Now point is when the driver opened the URL on the browser, Some times
the next page to which username and password has to be put by the
script, not coming- which causes the script to failed. Some intermediate
page is coming asking us to click on 'retry button' or 'refresh the
page'. Thus the script whenever such case occurred stopped execution, as
not getting the mentioned element.

So is there any way to refresh that intermediate page with "sleep"
before going to the "Log-in" page, so that script can run in one go?

Body:
For Capybara, I think Tommyixi's comment is the best:

visit current_path