问:
How to accelerate merge sort in linked list?
I already have an iterative version merge sort algorithm to sort linked list.

Following version work well in general case.

Roughly describe my algorithm:

I use button up, first iterate I merge 2 nodes and 2 nodes into 4 nodes which is sorted, and so on...

```<code>typedef struct ELE {
    char *value;
    struct ELE *next;
} list_ele_t;

/* Queue structure */
typedef struct {
    list_ele_t *head; /* Linked list of elements */
    list_ele_t *tail; /* Linked list of elements */
    int size;
} queue_t;

void q_sort(queue_t *q)
{
    if (!q || !q->head || q->size == 1)
        return;

    int block_size = 1, n = q->size, i, alen, blen;
    list_ele_t virtual_head;
    list_ele_t *last = NULL, *it = NULL, *l1 = NULL, *l2 = NULL, *tmp = NULL;
    // list_ele_t *l1head = NULL, *l1tail = NULL, *l2tail = NULL;
    virtual_head.next = q->head;
    while (block_size < n) {
        int iter = 0;
        last = &virtual_head;
        it = virtual_head.next;
        while (iter < n) {
            // decide each iterate time's block size a and b
            alen = min(n - iter, block_size);
            // avoid odd block
            blen = min(n - iter - alen, block_size);

            l1 = it;
            l1head = l1;
            // if left block is odd, just skip
            if (blen != 0) {
                // seperate one list in to l1 and l2
                for (i = 0; i < alen - 1; ++i)
                    it = it->next;
                l1tail = it;
                l2 = it->next;
                it->next = NULL;
                it = l2;
                for (i = 0; i < blen - 1; ++i)
                    it = it->next;
                l2tail = it;
                tmp = it->next;
                it->next = NULL;
                it = tmp;
            }

            while (l1 || l2) {
                if (l2 == NULL ||
                    (l1 != NULL && strcmp(l1->value, l2->value) < 0)) {
                    // if l2 doesn't contain any node, just append l1 to
                    // merge list or if value of l1 is smaller
                    last->next = l1;
                    last = last->next;
                    l1 = l1->next;
                } else {
                    // if l1 doesn't contain any node, just append l2 to
                    // merge list or if value of l2 is smaller
                    last->next = l2;
                    last = last->next;
                    l2 = l2->next;
                }
            }
            last->next = NULL;
            iter += alen + blen;
        }
        block_size <<= 1;
    }

    q->head = virtual_head.next;
    list_ele_t *nd = q->head;
    while (nd->next) {
        nd = nd->next;
    }
    q->tail = nd;
}
</code>```

When this algorithm encounter very long linked list will be very slow, but this kind of testbench have some specific format like have several repetitive section. e.g. AAAAABBBBBBB

As a result, I add some code into origin version. I check whether the member of list 1 (l1) and list 2 (l2) are same. If so, I skip merge step, just append l2 to l1

Following is new version:

```<code>void q_sort(queue_t *q)
{
    long long cnt = 0;
    if (!q || !q->head || q->size == 1)
        return;
    int block_size = 1, n = q->size, i, alen, blen;
    list_ele_t virtual_head;
    list_ele_t *last = NULL, *it = NULL, *l1 = NULL, *l2 = NULL, *tmp = NULL;
    list_ele_t *l1head = NULL, *l1tail = NULL, *l2tail = NULL;
    virtual_head.next = q->head;
    while (block_size < n) {
        int iter = 0;
        last = &virtual_head;
        it = virtual_head.next;
        while (iter < n) {
            // decide each iterate time's block size a and b
            alen = min(n - iter, block_size);
            // avoid odd block
            blen = min(n - iter - alen, block_size);
            // printf("%d %d block size: %d\n",alen,blen,block_size);

            l1 = it;
            l1head = l1;
            // if left block is odd, just skip
            if (blen != 0) {
                // seperate one list in to l1 and l2
                for (i = 0; i < alen - 1; ++i)
                    it = it->next;
                l1tail = it;
                l2 = it->next;
                it->next = NULL;
                it = l2;
                for (i = 0; i < blen - 1; ++i)
                    it = it->next;
                l2tail = it;
                tmp = it->next;
                it->next = NULL;
                it = tmp;
            }

            if (l1head && l2tail && strcmp(l1head->value, l2tail->value) == 0
                && (l1tail && l2 && strcmp(l1tail->value,l2->value) == 0)) {
                iter += alen + blen;
                last->next = l1;
                l1tail->next = l2;
                last = l2tail;
                l2tail->next = NULL;
            } else {
                while (l1 || l2) {
                    if (l2 == NULL ||
                        (l1 != NULL && strcmp(l1->value, l2->value) < 0)) {
                        // if l2 doesn't contain any node, just append l1 to
                        // merge list or if value of l1 is smaller
                        last->next = l1;
                        last = last->next;
                        l1 = l1->next;
                    } else {
                        // if l1 doesn't contain any node, just append l2 to
                        // merge list or if value of l2 is smaller
                        last->next = l2;
                        last = last->next;
                        l2 = l2->next;
                    }
                }
                last->next = NULL;
                iter += alen + blen;
            }
        }
        block_size <<= 1;
    }

    q->head = virtual_head.next;
    list_ele_t *nd = q->head;
    while (nd->next) {
        nd = nd->next;
    }
    q->tail = nd;
}
</code>```

Concept is simple but my addition seems wrong. Error message told me maybe there exist infinite loop.

First, I wonder are there any mistake I make when I add this section? how to fix it?

```<code>if (l1head && l2tail && strcmp(l1head->value, l2tail->value) == 0
            && (l1tail && l2 && strcmp(l1tail->value,l2->value) == 0)) {
            iter += alen + blen;
            last->next = l1;
            l1tail->next = l2;
            last = l2tail;
            l2tail->next = NULL;
        }
</code>```

Second, are there better way to accelerate this specific format linked list? ( e.g. C->C->C->C->B->B.....B)

Thanks all of yours advice!

答:
Example code that uses a small (32) array of "lists", where array[i] is a list with 2^i nodes (except last entry is unlimited size). This is probably the fastest way to sort a list using a list. It's usually faster to copy the list to an array, sort the array, and create a new sorted list from the array. The input parameter is a pointer to the first node of a list, and the returned value is a pointer to the first node of the sorted list. After sorting a list, the calling code will need to scan the sorted list to set the tail pointer in the list structure. The comparison in merge uses "src2 < src1" to follow the conventions used in C++ template sorts.</p>

```<code>typedef struct NODE_{
struct NODE_ * next;
uint64_t data;
}NODE;

NODE * MergeLists(NODE *, NODE *);      /* prototype */

#define NUMLISTS 32                     /* number of lists */

NODE * SortList(NODE *pList)
{
NODE * aList[NUMLISTS];                 /* array of lists */
NODE * pNode;
NODE * pNext;
size_t i;
    if(pList == NULL)                   /* check for empty list */
        return NULL;
    for(i = 0; i < NUMLISTS; i++)       /* zero array */
        aList[i] = NULL;
    pNode = pList;                      /* merge nodes into array */
    while(pNode != NULL){
        pNext = pNode->next;
        pNode->next = NULL;
        for(i = 0; (i < NUMLISTS) && (aList[i] != NULL); i++){
            pNode = MergeLists(aList[i], pNode);
            aList[i] = NULL;
        }
        if(i == NUMLISTS)
            i--;
        aList[i] = pNode;
        pNode = pNext;
    }
    pNode = NULL;                       /* merge array into one list */
    for(i = 0; i < NUMLISTS; i++)
        pNode = MergeLists(aList[i], pNode);
    return pNode;
}

NODE * MergeLists(NODE *pSrc1, NODE *pSrc2)
{
NODE *pDst = NULL;                      /* destination head ptr */
NODE **ppDst = &pDst;                   /* ptr to head or prev->next */
    if(pSrc1 == NULL)
        return pSrc2;
    if(pSrc2 == NULL)
        return pSrc1;
    while(1){
        if(pSrc2->data < pSrc1->data){  /* if src2 < src1 */
            *ppDst = pSrc2;
            pSrc2 = *(ppDst = &pSrc2->next);
            if(pSrc2 == NULL){
                *ppDst = pSrc1;
                break;
            }
        } else {                        /* src1 <= src2 */
            *ppDst = pSrc1;
            pSrc1 = *(ppDst = &pSrc1->next);
            if(pSrc1 == NULL){
                *ppDst = pSrc2;
                break;
            }
        }
    }
    return pDst;
}
</code>```

Body:
I already have an iterative version merge sort algorithm to sort linked list.

Following version work well in general case.

Roughly describe my algorithm:

I use button up, first iterate I merge 2 nodes and 2 nodes into 4 nodes which is sorted, and so on...

typedef struct ELE {
    char *value;
    struct ELE *next;
} list_ele_t;

/* Queue structure */
typedef struct {
    list_ele_t *head; /* Linked list of elements */
    list_ele_t *tail; /* Linked list of elements */
    int size;
} queue_t;

void q_sort(queue_t *q)
{
    if (!q || !q->head || q->size == 1)
        return;

    int block_size = 1, n = q->size, i, alen, blen;
    list_ele_t virtual_head;
    list_ele_t *last = NULL, *it = NULL, *l1 = NULL, *l2 = NULL, *tmp = NULL;
    // list_ele_t *l1head = NULL, *l1tail = NULL, *l2tail = NULL;
    virtual_head.next = q->head;
    while (block_size < n) {
        int iter = 0;
        last = &virtual_head;
        it = virtual_head.next;
        while (iter < n) {
            // decide each iterate time's block size a and b
            alen = min(n - iter, block_size);
            // avoid odd block
            blen = min(n - iter - alen, block_size);

            l1 = it;
            l1head = l1;
            // if left block is odd, just skip
            if (blen != 0) {
                // seperate one list in to l1 and l2
                for (i = 0; i < alen - 1; ++i)
                    it = it->next;
                l1tail = it;
                l2 = it->next;
                it->next = NULL;
                it = l2;
                for (i = 0; i < blen - 1; ++i)
                    it = it->next;
                l2tail = it;
                tmp = it->next;
                it->next = NULL;
                it = tmp;
            }

            while (l1 || l2) {
                if (l2 == NULL ||
                    (l1 != NULL && strcmp(l1->value, l2->value) < 0)) {
                    // if l2 doesn't contain any node, just append l1 to
                    // merge list or if value of l1 is smaller
                    last->next = l1;
                    last = last->next;
                    l1 = l1->next;
                } else {
                    // if l1 doesn't contain any node, just append l2 to
                    // merge list or if value of l2 is smaller
                    last->next = l2;
                    last = last->next;
                    l2 = l2->next;
                }
            }
            last->next = NULL;
            iter += alen + blen;
        }
        block_size <<= 1;
    }

    q->head = virtual_head.next;
    list_ele_t *nd = q->head;
    while (nd->next) {
        nd = nd->next;
    }
    q->tail = nd;
}

When this algorithm encounter very long linked list will be very slow, but this kind of testbench have some specific format like have several repetitive section. e.g. AAAAABBBBBBB

As a result, I add some code into origin version. I check whether the member of list 1 (l1) and list 2 (l2) are same. If so, I skip merge step, just append l2 to l1

Following is new version:

void q_sort(queue_t *q)
{
    long long cnt = 0;
    if (!q || !q->head || q->size == 1)
        return;
    int block_size = 1, n = q->size, i, alen, blen;
    list_ele_t virtual_head;
    list_ele_t *last = NULL, *it = NULL, *l1 = NULL, *l2 = NULL, *tmp = NULL;
    list_ele_t *l1head = NULL, *l1tail = NULL, *l2tail = NULL;
    virtual_head.next = q->head;
    while (block_size < n) {
        int iter = 0;
        last = &virtual_head;
        it = virtual_head.next;
        while (iter < n) {
            // decide each iterate time's block size a and b
            alen = min(n - iter, block_size);
            // avoid odd block
            blen = min(n - iter - alen, block_size);
            // printf("%d %d block size: %d\n",alen,blen,block_size);

            l1 = it;
            l1head = l1;
            // if left block is odd, just skip
            if (blen != 0) {
                // seperate one list in to l1 and l2
                for (i = 0; i < alen - 1; ++i)
                    it = it->next;
                l1tail = it;
                l2 = it->next;
                it->next = NULL;
                it = l2;
                for (i = 0; i < blen - 1; ++i)
                    it = it->next;
                l2tail = it;
                tmp = it->next;
                it->next = NULL;
                it = tmp;
            }

            if (l1head && l2tail && strcmp(l1head->value, l2tail->value) == 0
                && (l1tail && l2 && strcmp(l1tail->value,l2->value) == 0)) {
                iter += alen + blen;
                last->next = l1;
                l1tail->next = l2;
                last = l2tail;
                l2tail->next = NULL;
            } else {
                while (l1 || l2) {
                    if (l2 == NULL ||
                        (l1 != NULL && strcmp(l1->value, l2->value) < 0)) {
                        // if l2 doesn't contain any node, just append l1 to
                        // merge list or if value of l1 is smaller
                        last->next = l1;
                        last = last->next;
                        l1 = l1->next;
                    } else {
                        // if l1 doesn't contain any node, just append l2 to
                        // merge list or if value of l2 is smaller
                        last->next = l2;
                        last = last->next;
                        l2 = l2->next;
                    }
                }
                last->next = NULL;
                iter += alen + blen;
            }
        }
        block_size <<= 1;
    }

    q->head = virtual_head.next;
    list_ele_t *nd = q->head;
    while (nd->next) {
        nd = nd->next;
    }
    q->tail = nd;
}

Concept is simple but my addition seems wrong. Error message told me maybe there exist infinite loop.

First, I wonder are there any mistake I make when I add this section? how to fix it?

if (l1head && l2tail && strcmp(l1head->value, l2tail->value) == 0
            && (l1tail && l2 && strcmp(l1tail->value,l2->value) == 0)) {
            iter += alen + blen;
            last->next = l1;
            l1tail->next = l2;
            last = l2tail;
            l2tail->next = NULL;
        }

Second, are there better way to accelerate this specific format linked list? ( e.g. C->C->C->C->B->B.....B)

Thanks all of yours advice!

Body:
Example code that uses a small (32) array of "lists", where array[i] is a list with 2^i nodes (except last entry is unlimited size). This is probably the fastest way to sort a list using a list. It's usually faster to copy the list to an array, sort the array, and create a new sorted list from the array. The input parameter is a pointer to the first node of a list, and the returned value is a pointer to the first node of the sorted list. After sorting a list, the calling code will need to scan the sorted list to set the tail pointer in the list structure. The comparison in merge uses "src2 < src1" to follow the conventions used in C++ template sorts.

typedef struct NODE_{
struct NODE_ * next;
uint64_t data;
}NODE;

NODE * MergeLists(NODE *, NODE *);      /* prototype */

#define NUMLISTS 32                     /* number of lists */

NODE * SortList(NODE *pList)
{
NODE * aList[NUMLISTS];                 /* array of lists */
NODE * pNode;
NODE * pNext;
size_t i;
    if(pList == NULL)                   /* check for empty list */
        return NULL;
    for(i = 0; i < NUMLISTS; i++)       /* zero array */
        aList[i] = NULL;
    pNode = pList;                      /* merge nodes into array */
    while(pNode != NULL){
        pNext = pNode->next;
        pNode->next = NULL;
        for(i = 0; (i < NUMLISTS) && (aList[i] != NULL); i++){
            pNode = MergeLists(aList[i], pNode);
            aList[i] = NULL;
        }
        if(i == NUMLISTS)
            i--;
        aList[i] = pNode;
        pNode = pNext;
    }
    pNode = NULL;                       /* merge array into one list */
    for(i = 0; i < NUMLISTS; i++)
        pNode = MergeLists(aList[i], pNode);
    return pNode;
}

NODE * MergeLists(NODE *pSrc1, NODE *pSrc2)
{
NODE *pDst = NULL;                      /* destination head ptr */
NODE **ppDst = &pDst;                   /* ptr to head or prev->next */
    if(pSrc1 == NULL)
        return pSrc2;
    if(pSrc2 == NULL)
        return pSrc1;
    while(1){
        if(pSrc2->data < pSrc1->data){  /* if src2 < src1 */
            *ppDst = pSrc2;
            pSrc2 = *(ppDst = &pSrc2->next);
            if(pSrc2 == NULL){
                *ppDst = pSrc1;
                break;
            }
        } else {                        /* src1 <= src2 */
            *ppDst = pSrc1;
            pSrc1 = *(ppDst = &pSrc1->next);
            if(pSrc1 == NULL){
                *ppDst = pSrc2;
                break;
            }
        }
    }
    return pDst;
}


来源: stackexchange

问:
Making a bash script switch to interactive mode and give a prompt
I am writing a training tool, it is written in bash to teach bash/unix.

I want a script to run to set things up, then to hand control to the user.
I want it to be easily runnable by typing ./script-name

How do I do this?

I.E.

User types: tutorial/run

The run-tutorial script sets things up.

The user is presented with a task. (this bit works)

The command prompt is returned, with the shell still configured.

Currently it will work if I type . tutorial/bashrc

答:
Try making it an alias in your ~/.bashrc file. Add this to the bottom of ~/.bashrc:

```<code>alias tutorial='. tutorial/bashrc'
</code>```

Then close and re-open your terminal, or type . ~/.bashrc to re-source it.

To use this alias, simply call tutorial, and that will automatically get replaced with its alias, as though you had called . tutorial/bashrc.

ContentLicense: CC BY-SA 3.0

Body:
Try making it an alias in your ~/.bashrc file. Add this to the bottom of ~/.bashrc:

alias tutorial='. tutorial/bashrc'

Then close and re-open your terminal, or type . ~/.bashrc to re-source it.

To use this alias, simply call tutorial, and that will automatically get replaced with its alias, as though you had called . tutorial/bashrc.

ContentLicense: CC BY-SA 4.0


问:
Java While loop condition isn't being exicuted
I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code: </p>

```<code>import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int counter = 0;
    String[] arr = new String[15];
    System.out.println("Enter item or type 'zzz' to quit");
    arr[0] = input.nextLine();
    counter++;

     do{
         arr[counter] = input.nextLine();
         if (input.equals("zzz")){
             System.out.println("bleh");
         }
         counter++;

     } while (!input.equals("zzz") && counter <= 14);

     Arrays.sort(arr);
     System.out.println("Array is " + Arrays.toString(arr));
}
</code>```

答:
input is a Scanner. It will never equal a String.

Try this

```<code>Scanner sc = new Scanner(System.in);
String input;  // this is now a proper string to compare

String[] arr = new String[15];

System.out.println("Enter item or type 'zzz' to quit");
input = sc.nextLine();

int counter = 0;
while (counter < arr.length) {
   if (input.equals("zzz")) return;  // check most recently entered input
   arr[counter++] = input; // if not returned, store in the list and increase counter
   input = sc.nextLine();  // prompt next line
}
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
</code>```

Body:
I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code:

import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int counter = 0;
    String[] arr = new String[15];
    System.out.println("Enter item or type 'zzz' to quit");
    arr[0] = input.nextLine();
    counter++;

     do{
         arr[counter] = input.nextLine();
         if (input.equals("zzz")){
             System.out.println("bleh");
         }
         counter++;

     } while (!input.equals("zzz") && counter <= 14);

     Arrays.sort(arr);
     System.out.println("Array is " + Arrays.toString(arr));
}

Body:
input is a Scanner. It will never equal a String.

Try this

Scanner sc = new Scanner(System.in);
String input;  // this is now a proper string to compare

String[] arr = new String[15];

System.out.println("Enter item or type 'zzz' to quit");
input = sc.nextLine();

int counter = 0;
while (counter < arr.length) {
   if (input.equals("zzz")) return;  // check most recently entered input
   arr[counter++] = input; // if not returned, store in the list and increase counter
   input = sc.nextLine();  // prompt next line
}
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));


问:
When exactly does tvOS purge data?
I am planning to use Core Data to store downloaded data (about 2mb in all). Apple's docs state:

"Your app can download the data it needs into its cache directory. Downloaded data is not deleted while the app is running. However, when space is low and your app is not running, this data may be deleted. Do not use the entire cache space as this can cause unpredictable results."

Does this mean the data can be purged when the app is in the background or only when it is really quit (by sliding the app up in the "running app Cover-Flow-Like view")?

答: Data stored in CoreData is different from the app's cache directory and is not subject to being deleted by tvOS.</p>

Title: When exactly does tvOS purge data?


问:
Why are my data elements being copied instead of moved?
I'm performing some tests about move semantics, and my class behavior seems weird for me.

Given the mock class VecOfInt:

```<code>class VecOfInt {
public:
    VecOfInt(size_t num) : m_size(num), m_data(new int[m_size]) {}
    ~VecOfInt() { delete[] m_data; }
    VecOfInt(VecOfInt const& other) : m_size(other.m_size),  m_data(new int[m_size]) {
        std::cout << "copy..." <<std::endl;
        std::copy(other.m_data, other.m_data + m_size, m_data);
    }
    VecOfInt(VecOfInt&& other) : m_size(other.m_size) {
        std::cout << "move..." << std::endl;
        m_data = other.m_data;
        other.m_data = nullptr;
    }
    VecOfInt& operator=(VecOfInt const& other) {
        std::cout << "copy assignment..." << std::endl;
        m_size = other.m_size;
        delete m_data;
        m_data = nullptr;
        m_data = new int[m_size];
        m_data = other.m_data;
        return *this;
    }
    VecOfInt& operator=(VecOfInt&& other) {
        std::cout << "move assignment..." << std::endl;
        m_size = other.m_size;
        m_data = other.m_data;
        other.m_data = nullptr;
        return *this;
    }
private:
    size_t m_size;
    int* m_data;
};
</code>```

OK CASE

When I insert a single value in-place:

```<code>int main() {
    std::vector<VecOfInt> v;
    v.push_back(10);
    return 0;
}
</code>```

Then it gives me the following output (what I think is fine):

move...

WEIRD CASE

When I insert three different values in-place:

```<code>int main() {
    std::vector<VecOfInt> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    return 0;
}
</code>```

Then the output calls the copy constructor 3 times:

move...
move...
copy...
move...
copy...
copy...

What I'm missing here?

答:
Add noexcept decorators to your move constructor and move assignment operator:

```<code>VecOfInt(VecOfInt&& other) noexcept : m_size(other.m_size) {
    std::cout << "move..." << std::endl;
    m_data = other.m_data;
    other.m_data = nullptr;
}

VecOfInt& operator=(VecOfInt&& other) noexcept {
    std::cout << "move assignment..." << std::endl;
    m_size = other.m_size;
    m_data = other.m_data;
    other.m_data = nullptr;
    return *this;
}
</code>```

Some functions (for instance, std::move_if_noexcept, used by std::vector) will decide to copy your object if its move operations are not decorated with noexcept., i.e. there is no guarantee they will not throw. That's why you should aim to make your move operations (move constructor, move assignment operator) noexcept. This can significantly improve the performance of your program.

According to Scott Meyer's in Effective Modern C++:

std::vector takes advantage of this "move if you can, but copy if
  you must" strategy , and it's not the only function in the Standard
  Library that does. Other functions sporting strong exception safety
  guarantee in C++98 (e.g. std::vector::reserve, std::deque::insert,
  etc) behave the same way. All these functions replace calls to copy
  operations in c++98 with calls to move operations in C++11 only if the
  move operations are known not to emit exceptions. But how can a
  function know if a move operation won't produce an exception? The
  answer is obvious: it checks to see if the operation is declared
  noexcept.

Body:
I'm performing some tests about move semantics, and my class behavior seems weird for me.

Given the mock class VecOfInt:

class VecOfInt {
public:
    VecOfInt(size_t num) : m_size(num), m_data(new int[m_size]) {}
    ~VecOfInt() { delete[] m_data; }
    VecOfInt(VecOfInt const& other) : m_size(other.m_size),  m_data(new int[m_size]) {
        std::cout << "copy..." <<std::endl;
        std::copy(other.m_data, other.m_data + m_size, m_data);
    }
    VecOfInt(VecOfInt&& other) : m_size(other.m_size) {
        std::cout << "move..." << std::endl;
        m_data = other.m_data;
        other.m_data = nullptr;
    }
    VecOfInt& operator=(VecOfInt const& other) {
        std::cout << "copy assignment..." << std::endl;
        m_size = other.m_size;
        delete m_data;
        m_data = nullptr;
        m_data = new int[m_size];
        m_data = other.m_data;
        return *this;
    }
    VecOfInt& operator=(VecOfInt&& other) {
        std::cout << "move assignment..." << std::endl;
        m_size = other.m_size;
        m_data = other.m_data;
        other.m_data = nullptr;
        return *this;
    }
private:
    size_t m_size;
    int* m_data;
};

OK CASE

When I insert a single value in-place:

int main() {
    std::vector<VecOfInt> v;
    v.push_back(10);
    return 0;
}

Then it gives me the following output (what I think is fine):

move...

WEIRD CASE

When I insert three different values in-place:

int main() {
    std::vector<VecOfInt> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    return 0;
}

Then the output calls the copy constructor 3 times:

move...
move...
copy...
move...
copy...
copy...

What I'm missing here?

Body:
Add noexcept decorators to your move constructor and move assignment operator:

VecOfInt(VecOfInt&& other) noexcept : m_size(other.m_size) {
    std::cout << "move..." << std::endl;
    m_data = other.m_data;
    other.m_data = nullptr;
}

VecOfInt& operator=(VecOfInt&& other) noexcept {
    std::cout << "move assignment..." << std::endl;
    m_size = other.m_size;
    m_data = other.m_data;
    other.m_data = nullptr;
    return *this;
}

Some functions (for instance, std::move_if_noexcept, used by std::vector) will decide to copy your object if its move operations are not decorated with noexcept., i.e. there is no guarantee they will not throw. That's why you should aim to make your move operations (move constructor, move assignment operator) noexcept. This can significantly improve the performance of your program.

According to Scott Meyer's in Effective Modern C++:

std::vector takes advantage of this "move if you can, but copy if
  you must" strategy , and it's not the only function in the Standard
  Library that does. Other functions sporting strong exception safety
  guarantee in C++98 (e.g. std::vector::reserve, std::deque::insert,
  etc) behave the same way. All these functions replace calls to copy
  operations in c++98 with calls to move operations in C++11 only if the
  move operations are known not to emit exceptions. But how can a
  function know if a move operation won't produce an exception? The
  answer is obvious: it checks to see if the operation is declared
  noexcept.


问:
SCORM authoring tool advice
I've only recently heard of SCORM and i've been asked to put together a simple e-learning module which can be deployed as a SCORM module. The module is a questionnaire with an additional bank of information (possibly laid out wiki-style). I've just looked at some of the open source tools eXe and xerte and both look quite good.

What I'm not sure about is the limitations of using these tools. I want to be able to fully style all aspects of the template and add javascript tooltips etc, and possibly use ajax to load in each section of the quiz. However, I guess if i'm using ajax, then i'm using server side code, which then limits the module to a specific platform.

Are these things possible using one of these authoring systems? I'm trying to get my head round the possible restrictions. How do these tools handle data storage such as quiz scores per user?

Grateful for any advice!

答:
You have a lot of control over the style and design of a SCORM course. Internally, we run the range of courses that are entirely HTML/JavaScript, Flash/JavaScript and even courses in Java. The authoring tools differ greatly too in the output they produce. Most free ones will produce HTML output. Several of the pay ones like Articulate and Smartbuilder produce Flash content. Regardless of the design or authoring tools that are used, a SCORM course has to communicate to the LMS using a JavaScript API. So at some point the course will have to have some JavaScript so stick to technologies that work well with JavaScript.

I can not recommend enough using a precanned authoring tool. Writing a SCORM course from scratch will involve a lot of work. Your customer may not define their needs well and you may target SCORM 2004 only to find they actually need SCORM 1.2. With an authoring tool that is as simple as changing the publishing settings in a drop down. For a self authored course, that could be a lot of rescripting and debugging.

Most authoring tools have some type of quiz/assessment authoring that allow you to control scoring, tracking and setup question pools.

I would stay away from AJAX as that can break the "Shareable" part of Shareable Content Object if the course is deployed in a firewalled intranent. But I would not stay away from AJAX if your client needs a secure assessment. To make a course shareable, all the content is included in the package including all the answers. Although usually obscured using some method they are still transfered down to the client browser where someone with enough know how can view the source files or use Flash decompilers.

As far as the SCORM 2004 properties around quizes, most authoring tools will use the cmi.interaction data elements to store each interaction a learner performs. That usually includes a unique ID for the interaction, timestamp, description, correct response and what the learner responded. There are more properties that can be set but those are the most common ones I see used. There is also a set of scoring properties in cmi.scaled_passing_score which is the required score to demonstrate mastery of a SCO and cmi.score where you can set the learners raw, min and max scores. Again, the nice thing about an authoring tool is all that is wired up for you when you publish.

There are several testing tools you can use. ADL has their conformance testers that will allow you to see the data passed between the course and the LMS and scorm.com has their Test Track software that you can test the course and see the results. Both are useful for final testing and debugging of a course.

Title: SCORM authoring tool advice


问:
Beautiful Soup, scraping an auction site that clears the sold item div on completion of auction
ran into a problem with a scraper I'm building.  I wanted to scrape information from an auction site.  The issue is when I request the html I have to refresh the page, when you refresh this auction site page any items auction items that have ended are removed so I lose the data I was looking to get.

```<code>def soldDetection(soup):
    #Select the timer and check if it == "Lot Closed" once lot is closed send the entire container information to getData() to extract price and details
    while True:
        getPage(url)
        container = soup.find_all('li', class_='current-price')
        #print(container)
        for child in container:
            label = child.span.contents[0]
            #print (label)
            if label == 'Closing bid':
                # grab entire div for the card with data for the getData()
                print('Found')
                parentDiv = label.find_parent('div', class_='lot-single')
                getData(parentDiv)
                return parentDiv
            else:
                continue
        time.sleep(1)
        print('Nothing Sold')
        continue
</code>```

In my browser if I don't refresh the 'current-price' span content changes from "Current bid" to "Closing bid"  but if I refresh that item is cleared from the html.  Is there a way to get beautiful soup to watch this without refreshing and clearing?  I am concerned that bs4 might not be the right tool for this job, if so what tool should I use?

Thanks,

答:
Well I found a solution,  I used selenium to open a browser and watch for the changes that javascript was sending to the page. Then collected all the html and sent it to my beautiful soup function to navigate the tree.</p>

```<code>from selenium import webdriver
browser = webdriver.Firefox()
browser.get(websiteAddress)
...
      elems = browser.find_elements_by_xpath("//*[contains(text(),'Closing bid')]")
        if not elems:
            print('Not Found')
            continue
        label = elems[0].text
        if label == 'Closing bid':
            # grab entire div for the card with data for the getData()
            soup = bs4.BeautifulSoup(browser.page_source,'html.parser')
</code>```

Body:
ran into a problem with a scraper I'm building.  I wanted to scrape information from an auction site.  The issue is when I request the html I have to refresh the page, when you refresh this auction site page any items auction items that have ended are removed so I lose the data I was looking to get.

def soldDetection(soup):
    #Select the timer and check if it == "Lot Closed" once lot is closed send the entire container information to getData() to extract price and details
    while True:
        getPage(url)
        container = soup.find_all('li', class_='current-price')
        #print(container)
        for child in container:
            label = child.span.contents[0]
            #print (label)
            if label == 'Closing bid':
                # grab entire div for the card with data for the getData()
                print('Found')
                parentDiv = label.find_parent('div', class_='lot-single')
                getData(parentDiv)
                return parentDiv
            else:
                continue
        time.sleep(1)
        print('Nothing Sold')
        continue

In my browser if I don't refresh the 'current-price' span content changes from "Current bid" to "Closing bid"  but if I refresh that item is cleared from the html.  Is there a way to get beautiful soup to watch this without refreshing and clearing?  I am concerned that bs4 might not be the right tool for this job, if so what tool should I use?

Thanks,

Body:
Well I found a solution,  I used selenium to open a browser and watch for the changes that javascript was sending to the page. Then collected all the html and sent it to my beautiful soup function to navigate the tree.

from selenium import webdriver
browser = webdriver.Firefox()
browser.get(websiteAddress)
...
      elems = browser.find_elements_by_xpath("//*[contains(text(),'Closing bid')]")
        if not elems:
            print('Not Found')
            continue
        label = elems[0].text
        if label == 'Closing bid':
            # grab entire div for the card with data for the getData()
            soup = bs4.BeautifulSoup(browser.page_source,'html.parser')


问:
is there a way (or conditional statement in Clojure) to go through all different conditions even if one of the conditions is false?
I would like to evaluate all the conditions in this block but i can't find any conditional statement that does this without pulling out when one condition is false. If there's a way outside using conditional statements please let me know also.

Kindly help. Tnx.

```<code>(when
     ;;when "number" is found in 'a' execute the nextline
      (clojure.string/includes? (.toString a) "number")
        (println (hash-map :num {:test 'number?, :data (flatten num)}))
     ;;when "vector" is found in 'b' execute the nextline
      (clojure.string/includes? (.toString b) "vector")
        (println (hash-map :vec {:test 'vector?, :data vec}))
     ;;when "string" is found in 'c' execute the nextline
      (clojure.string/includes? (.toString c) "symbol")
        (println (hash-map :sym {:test 'symbol?, :data (flatten sym)}) )
     )
</code>```

答:
Just write it as a sequence of 3 when statements.

```<code>(do   ; it doesn't hurt to wrap in a `do`, but this is usually not needed

  ;when "number" is found in 'a' execute the nextline
  (when (clojure.string/includes? (.toString a) "number")
    (println (hash-map :num {:test 'number?, :data (flatten num)})))

  ;when "vector" is found in 'b' execute the nextline
  (when (clojure.string/includes? (.toString b) "vector")
    (println (hash-map :vec {:test 'vector?, :data vec})))

  ;when "string" is found in 'c' execute the nextline
  (when (clojure.string/includes? (.toString c) "symbol")
    (println (hash-map :sym {:test 'symbol?, :data (flatten sym)}))))
</code>```

As the comment says, wrapping everything in a do is possible but probably not needed.

Body:
I would like to evaluate all the conditions in this block but i can't find any conditional statement that does this without pulling out when one condition is false. If there's a way outside using conditional statements please let me know also.

Kindly help. Tnx.

(when
     ;;when "number" is found in 'a' execute the nextline
      (clojure.string/includes? (.toString a) "number")
        (println (hash-map :num {:test 'number?, :data (flatten num)}))
     ;;when "vector" is found in 'b' execute the nextline
      (clojure.string/includes? (.toString b) "vector")
        (println (hash-map :vec {:test 'vector?, :data vec}))
     ;;when "string" is found in 'c' execute the nextline
      (clojure.string/includes? (.toString c) "symbol")
        (println (hash-map :sym {:test 'symbol?, :data (flatten sym)}) )
     )

Body:
Just write it as a sequence of 3 when statements.

(do   ; it doesn't hurt to wrap in a `do`, but this is usually not needed

  ;when "number" is found in 'a' execute the nextline
  (when (clojure.string/includes? (.toString a) "number")
    (println (hash-map :num {:test 'number?, :data (flatten num)})))

  ;when "vector" is found in 'b' execute the nextline
  (when (clojure.string/includes? (.toString b) "vector")
    (println (hash-map :vec {:test 'vector?, :data vec})))

  ;when "string" is found in 'c' execute the nextline
  (when (clojure.string/includes? (.toString c) "symbol")
    (println (hash-map :sym {:test 'symbol?, :data (flatten sym)}))))

As the comment says, wrapping everything in a do is possible but probably not needed.


问:
Display user data in alert dialog from Firebase Database
Im trying to get a user's information to be displayed in an alert dialog box when their profile is clicked on. I am able to get the dialog box to be displayed when clicked but the dialog box is empty. The users data is being stored in Firebase Real-Time Database.Iv posted the code Im using and added comments to the code. Im guessing the issue is with the Database Reference or the DataSnapshot?

```<code>    //Variables
    usersDb = FirebaseDatabase.getInstance().getReference().child("Users");
    mAuth = FirebaseAuth.getInstance();
    currentUId = mAuth.getCurrentUser().getUid();

    // OnItemClickListener
    flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
        @Override
        public void onItemClicked(int itemPosition, Object dataObject) {

               // users profile card
            cards obj = (cards) dataObject;
            final String userId = obj.getUserId();

            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            DatabaseReference userbio = usersDb.child(userId).child("Bio");
            userbio.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()){
                        if (dataSnapshot.child(userId).child("Bio").getValue() != null){
                        userBio = dataSnapshot.child("Bio").getValue().toString();
                    }
                }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

            builder.setTitle("Bio");
            builder.setMessage(userBio);
            // Set click listener for alert dialog buttons
            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch(which){
                        case DialogInterface.BUTTON_POSITIVE:
                            // User clicked the Yes button
                            break;

                        case DialogInterface.BUTTON_NEGATIVE:
                            // User clicked the No button
                            break;
                    }
                }
            };
            // Set the alert dialog yes button click listener
            builder.setPositiveButton("Yes", dialogClickListener);
            // Set the alert dialog no button click listener
            builder.setNegativeButton("No",dialogClickListener);
            AlertDialog dialog = builder.create();
            // Display the alert dialog on interface
            dialog.show();
        }
    }); }
</code>```

I figured out the issue. I have added the corrected code below.

```<code>             DatabaseReference databaseReference = usersDb.child(userId);
             databaseReference.addValueEventListener(new ValueEventListener()
                  {
                 @Override
                 public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                   {
                     if (dataSnapshot.exists()) {
                         if (dataSnapshot.child("Bio").getValue() != null) {
                             userBio = dataSnapshot.child("Bio").getValue().toString();
                         }
                     }}
                 @Override
                 public void onCancelled(@NonNull DatabaseError databaseError) {

                 }
             });
            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            builder.setTitle("Bio");
            builder.setMessage(userBio);
</code>```

答: Maybe its because you are calling twice child("Bio"), first in the DatabaseReference and then in the DataSnapshot. Try to delete it from one of them.

Body:
Im trying to get a user's information to be displayed in an alert dialog box when their profile is clicked on. I am able to get the dialog box to be displayed when clicked but the dialog box is empty. The users data is being stored in Firebase Real-Time Database.Iv posted the code Im using and added comments to the code. Im guessing the issue is with the Database Reference or the DataSnapshot?

    //Variables
    usersDb = FirebaseDatabase.getInstance().getReference().child("Users");
    mAuth = FirebaseAuth.getInstance();
    currentUId = mAuth.getCurrentUser().getUid();

    // OnItemClickListener
    flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
        @Override
        public void onItemClicked(int itemPosition, Object dataObject) {

               // users profile card
            cards obj = (cards) dataObject;
            final String userId = obj.getUserId();

            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            DatabaseReference userbio = usersDb.child(userId).child("Bio");
            userbio.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()){
                        if (dataSnapshot.child(userId).child("Bio").getValue() != null){
                        userBio = dataSnapshot.child("Bio").getValue().toString();
                    }
                }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

            builder.setTitle("Bio");
            builder.setMessage(userBio);
            // Set click listener for alert dialog buttons
            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch(which){
                        case DialogInterface.BUTTON_POSITIVE:
                            // User clicked the Yes button
                            break;

                        case DialogInterface.BUTTON_NEGATIVE:
                            // User clicked the No button
                            break;
                    }
                }
            };
            // Set the alert dialog yes button click listener
            builder.setPositiveButton("Yes", dialogClickListener);
            // Set the alert dialog no button click listener
            builder.setNegativeButton("No",dialogClickListener);
            AlertDialog dialog = builder.create();
            // Display the alert dialog on interface
            dialog.show();
        }
    }); }

I figured out the issue. I have added the corrected code below.

             DatabaseReference databaseReference = usersDb.child(userId);
             databaseReference.addValueEventListener(new ValueEventListener()
                  {
                 @Override
                 public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                   {
                     if (dataSnapshot.exists()) {
                         if (dataSnapshot.child("Bio").getValue() != null) {
                             userBio = dataSnapshot.child("Bio").getValue().toString();
                         }
                     }}
                 @Override
                 public void onCancelled(@NonNull DatabaseError databaseError) {

                 }
             });
            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            builder.setTitle("Bio");
            builder.setMessage(userBio);


问:
C++ to Java Code Conversion
I have in C++

```<code>r.bits[k] &= 0xFF ^ msk;
</code>```

So in Java

```<code>r.bits[k] = r.bits[k] & 0xFF,
</code>```

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.

答:
The caret means bitwise XOR

The caret does NOT mean a kind of pointer in C++ (though MSVC++ has extension for C++/CLI that use that symbol)

Title: C++ to Java Code Conversion

Body:
I have in C++

r.bits[k] &= 0xFF ^ msk;

So in Java

r.bits[k] = r.bits[k] & 0xFF,

but what is the meaning of the caret symbol? msk also will contain hexadecimal values.
I know the caret symbol is a type of pointer in C++ but not sure what it is doing here.
Please explain.


问:
React-Native project (Could not connect to Development server)
First!

```<code>☁  wonder  react-native --version
react-native-cli: 2.0.1
react-native: 0.58.6
☁  wonder  node --version
v13.6.0
☁  wonder  npm --version
6.13.4
</code>```

When attempting to build and exe on simulator locally I'm getting;

despite there not being anything running on this port and this is the out-of-the-box port for RN projects but I will paste my AppDelagate file and tool versions..Can anyone explain how this works so that I can troubleshoot.

```<code>> react-native run-ios

Found Xcode project wonder.xcodeproj
Building using "xcodebuild -project wonder.xcodeproj -configuration Debug -scheme wonder -destination id=C9362944-1FDD-4D6E-A6BB-8E758F427 -derivedDataPath build"
User defaults from command line:

    IDEDerivedDataPathOverride = /Users/{NAME}/Documents/Projects/wonderService/wonder/ios/build

note: Using new build system

note: Planning build

note: Using build description from disk

PhaseScriptExecution Start\ Packager /Users/{NAME}/Documents/Projects/wonderService/wonder/ios/build/Build/Intermediates.noindex/React.build/Debug-iphonesimulator/React.build/Script-006B79A01A781F3800
6873D1.sh (in target 'React' from project 'React')
    cd /Users/{NAME}/Documents/Projects/wonderService/wonder/node_modules/react-native/React
    /bin/sh -c /Users/{NAME}/Documents/Projects/wonderService/wonder/ios/build/Build/Intermediates.noindex/React.build/Debug-iphonesimulator/React.build/Script-006B79A01A781F38006873D1.sh

Connection to localhost port 8081 [tcp/sunproxyadmin] succeeded!

</code>```

AppDelegate.h file

```<code>#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"];

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"wonder"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [UIColor blackColor];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

@end
</code>```

Above I do remember having to add

```<code>jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"];
</code>```

this can be reversed.However,I don't believe this to be the error

I also understand when customizing PORTS for projects it could be made here

```<code>node_modules/react-native/React/React.xcodeproj/project.pbxproj
</code>```

but there are no signs of any other PORT being used in the instance.

lastly, I've toggled between using 127.0.0.1 && localhost... SAME RESULT

答:
@Maggie

Port Issue

Nothing running;

Node Server

This had some traction to it;

Server Terminal reads this

Error: Unable to resolve module "./index.ios" from "/Users/chris/Documents/Projects/wonderService/wonderFront/.": The module "./index.ios" could not be found from "/Users/chris/Documents/Projects/wonderService/wonderFront/.". Indeed, none of these files exist:
  * "/Users/chris/Documents/Projects/wonderService/wonderFront/index.ios(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)"
  * "/Users/chris/Documents/Projects/wonderService/wonderFront/index.ios/index(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)"
    at ModuleResolver.resolveDependency (/Users/chris/Documents/Projects/wonderService/wonderFront/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:163:15)

Body:
First!

☁  wonder  react-native --version
react-native-cli: 2.0.1
react-native: 0.58.6
☁  wonder  node --version
v13.6.0
☁  wonder  npm --version
6.13.4

When attempting to build and exe on simulator locally I'm getting;

despite there not being anything running on this port and this is the out-of-the-box port for RN projects but I will paste my AppDelagate file and tool versions..Can anyone explain how this works so that I can troubleshoot.

> react-native run-ios

Found Xcode project wonder.xcodeproj
Building using "xcodebuild -project wonder.xcodeproj -configuration Debug -scheme wonder -destination id=C9362944-1FDD-4D6E-A6BB-8E758F427 -derivedDataPath build"
User defaults from command line:

    IDEDerivedDataPathOverride = /Users/{NAME}/Documents/Projects/wonderService/wonder/ios/build

note: Using new build system

note: Planning build

note: Using build description from disk

PhaseScriptExecution Start\ Packager /Users/{NAME}/Documents/Projects/wonderService/wonder/ios/build/Build/Intermediates.noindex/React.build/Debug-iphonesimulator/React.build/Script-006B79A01A781F3800
6873D1.sh (in target 'React' from project 'React')
    cd /Users/{NAME}/Documents/Projects/wonderService/wonder/node_modules/react-native/React
    /bin/sh -c /Users/{NAME}/Documents/Projects/wonderService/wonder/ios/build/Build/Intermediates.noindex/React.build/Debug-iphonesimulator/React.build/Script-006B79A01A781F38006873D1.sh

Connection to localhost port 8081 [tcp/sunproxyadmin] succeeded!

AppDelegate.h file

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"];

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"wonder"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [UIColor blackColor];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

@end

Above I do remember having to add

jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"];

this can be reversed.However,I don't believe this to be the error

I also understand when customizing PORTS for projects it could be made here

node_modules/react-native/React/React.xcodeproj/project.pbxproj

but there are no signs of any other PORT being used in the instance.

lastly, I've toggled between using 127.0.0.1 && localhost... SAME RESULT


问:
Shared element transition image jumps down on exit transition
I've been searching everywhere for a cause of this problem and applied most of the solutions that I've found online but I've had no luck.

Here's the situation, I have two activities, one with a viewpager with a recyclerview inside each tab. When I click one of the items from the recyclerview it will open a modal activity that has the target transition image inside a fragment.

So the image will expand from the recyclerview item to the activity modal image

So something like this: Activity1/ViewPager/RecyclerView/Item/Image -> Activity2/Fragment/Image

It works beautifully from Activity1 to Activity2 but when the exit animation occurs the image jumps down, like half the image and lands in Activity one half an image down so it looks really clunky.

Here there are some code snippets:

recyclerview_item.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:id="@+id/product_container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:clickable="true"
    android:focusable="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="vertical">

    <RelativeLayout
        android:background="@drawable/bordered_image"
        android:padding="2dp"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/product_image"
            android:layout_width="match_parent"
            android:layout_height="140dp"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
            android:src="@drawable/default_item" />
    </RelativeLayout>

    <TextView
        android:id="@+id/product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/product_price"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="16sp" />

</LinearLayout>
</code>```

I open the activity like this:

```<code>val options = ActivityOptions
    .makeSceneTransitionAnimation(this, sharedImage, sharedImage.transitionName)
startActivity(intent, options.toBundle())
</code>```

This is how I handle the modal activity

```<code>    requestWindowFeature(Window.FEATURE_NO_TITLE)
    window.setBackgroundDrawableResource(R.drawable.rounded_dialog)
    window.setLayout(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
</code>```

And inside the onCreateView of the fragment I add this

```<code>image.transitionName = "image_${mItem.id}"
image.loadUrl(mItem.image)
startPostponedEnterTransition()
</code>```

And I use glide for showing the image like this

```<code>private fun ImageView.loadUrl(url: String) {
    val options = RequestOptions()
    Glide.with(context)
        .load(url)
        .apply(
            options.transforms(
                CenterCrop(),
                RoundedCorners(150)
            )
        )
        .into(this)
}
</code>```

This is how the image returns to the activity 1:

EDIT: So I've found the problem. I use a custom style for the activity dialog. In the android manifest I add this to the activity:

```<code><activity android:name=".activities.Activity2"
    android:theme="@style/AppTheme.ActivityDialog"/>
</code>```

And the style is this:

```<code><style name="AppTheme.ActivityDialog" parent="Theme.AppCompat.DayNight.Dialog">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowContentTransitions">true</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowBackground">@color/white</item>
</style>
</code>```

This is somehow breaking the animation

答:
So I found what the problem was:

An activity transition works like this. When you start your second activity, it is >displayed on top of your first one with a transparent background. The shared elements are >positioned the same way they are on the first activity and then animated to the correct >position specified on the second activity.

In your case you are using android:theme="@style/Theme.AppCompat.Dialog" which mean the >size of the second activity's drawing area is smaller than the one from the first >activity. This explains the clipping and the no transition when clicking outside.

I changed the theme of the Activity2 to this:

```<code><style name="AppTheme.ActivityDialog" parent="AppTheme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:backgroundDimEnabled">true</item>
</style>
</code>```

And added a cardview to the activity 2 layout and it works now

Body:
I've been searching everywhere for a cause of this problem and applied most of the solutions that I've found online but I've had no luck.

Here's the situation, I have two activities, one with a viewpager with a recyclerview inside each tab. When I click one of the items from the recyclerview it will open a modal activity that has the target transition image inside a fragment.

So the image will expand from the recyclerview item to the activity modal image

So something like this: Activity1/ViewPager/RecyclerView/Item/Image -> Activity2/Fragment/Image

It works beautifully from Activity1 to Activity2 but when the exit animation occurs the image jumps down, like half the image and lands in Activity one half an image down so it looks really clunky.

Here there are some code snippets:

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:id="@+id/product_container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:clickable="true"
    android:focusable="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="vertical">

    <RelativeLayout
        android:background="@drawable/bordered_image"
        android:padding="2dp"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/product_image"
            android:layout_width="match_parent"
            android:layout_height="140dp"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
            android:src="@drawable/default_item" />
    </RelativeLayout>

    <TextView
        android:id="@+id/product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/product_price"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="16sp" />

</LinearLayout>

I open the activity like this:

val options = ActivityOptions
    .makeSceneTransitionAnimation(this, sharedImage, sharedImage.transitionName)
startActivity(intent, options.toBundle())

This is how I handle the modal activity

    requestWindowFeature(Window.FEATURE_NO_TITLE)
    window.setBackgroundDrawableResource(R.drawable.rounded_dialog)
    window.setLayout(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )

And inside the onCreateView of the fragment I add this

image.transitionName = "image_${mItem.id}"
image.loadUrl(mItem.image)
startPostponedEnterTransition()

And I use glide for showing the image like this

private fun ImageView.loadUrl(url: String) {
    val options = RequestOptions()
    Glide.with(context)
        .load(url)
        .apply(
            options.transforms(
                CenterCrop(),
                RoundedCorners(150)
            )
        )
        .into(this)
}

This is how the image returns to the activity 1:

EDIT: So I've found the problem. I use a custom style for the activity dialog. In the android manifest I add this to the activity:

<activity android:name=".activities.Activity2"
    android:theme="@style/AppTheme.ActivityDialog"/>

And the style is this:

This is somehow breaking the animation

Body:
So I found what the problem was:

An activity transition works like this. When you start your second activity, it is >displayed on top of your first one with a transparent background. The shared elements are >positioned the same way they are on the first activity and then animated to the correct >position specified on the second activity.

In your case you are using android:theme="@style/Theme.AppCompat.Dialog" which mean the >size of the second activity's drawing area is smaller than the one from the first >activity. This explains the clipping and the no transition when clicking outside.

I changed the theme of the Activity2 to this:

<style name="AppTheme.ActivityDialog" parent="AppTheme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:backgroundDimEnabled">true</item>
</style>

And added a cardview to the activity 2 layout and it works now


问:
Broadcaster/Listener pattern using variadic templates
I am trying to implement a sort of a Broadcaster/Listener pattern using variadic template:

```<code>template <typename... Args>
class WithListeners {
public:
    class Listener {
    public:
        virtual void operator()(Args&&... args) = 0;
    };
private:
    std::list<std::shared_ptr<Listener>> listeners;
public:
    void addListener(std::shared_ptr<Listener> l) {
        if (std::find(listeners.begin(), listeners.end(), l) == listeners.end())
            listeners.push_back(l);
    }
    void removeListener(std::shared_ptr<Listener> l) {
        listeners.remove(l);
    }
    void callListeners(Args&&... args) const {
        for (auto l : listeners) {
            if (l) (*l)(std::forward<Args>(args)...);
        }
    }
};
</code>```

The thing is that I can compile it with <> but not with <int>. So for example this doesn't compile:

```<code>class MyClassWithListener : public WithListeners<int>::Listener{
public:
    virtual void operator()(int value) override {
        //my handling code
    }
};
</code>```

It says that the function with override specifier does not override any base class method.

答:
You may think that your operator() makes use of perfect forwarding, but it does not. The Args... template argument is fully resolved by the time the operator() method is being considered, so it just takes all arguments as regular RValue references.

Because of that, your override needs to do the same thing:

```<code>class MyClassWithListener : public WithListeners<int>::Listener{
public:
    virtual void operator()(int&& value) override {
        //my handling code
    }
};
</code>```

You would be better served to just go with straight arguments in this case:

```<code>template <typename... Args>
class WithListeners {
public:
    class Listener {
    public:
      virtual void operator()(Args... args) = 0;
    };

    void callListeners(Args... args) const {
        for (auto l : listeners) {
            if (l) (*l)(std::move(args)...);
        }
    }
};
</code>```

Since you can still fully define the arguments of the listener:

```<code>class MyClassWithListener : public WithListeners<const int&>::Listener{
public:
    virtual void operator()(const int& value) override {
        //my handling code
    }
};
</code>```

Body:
I am trying to implement a sort of a Broadcaster/Listener pattern using variadic template:

template <typename... Args>
class WithListeners {
public:
    class Listener {
    public:
        virtual void operator()(Args&&... args) = 0;
    };
private:
    std::list<std::shared_ptr<Listener>> listeners;
public:
    void addListener(std::shared_ptr<Listener> l) {
        if (std::find(listeners.begin(), listeners.end(), l) == listeners.end())
            listeners.push_back(l);
    }
    void removeListener(std::shared_ptr<Listener> l) {
        listeners.remove(l);
    }
    void callListeners(Args&&... args) const {
        for (auto l : listeners) {
            if (l) (*l)(std::forward<Args>(args)...);
        }
    }
};

The thing is that I can compile it with <> but not with <int>. So for example this doesn't compile:

class MyClassWithListener : public WithListeners<int>::Listener{
public:
    virtual void operator()(int value) override {
        //my handling code
    }
};

It says that the function with override specifier does not override any base class method.

Body:
You may think that your operator() makes use of perfect forwarding, but it does not. The Args... template argument is fully resolved by the time the operator() method is being considered, so it just takes all arguments as regular RValue references.

Because of that, your override needs to do the same thing:

class MyClassWithListener : public WithListeners<int>::Listener{
public:
    virtual void operator()(int&& value) override {
        //my handling code
    }
};

You would be better served to just go with straight arguments in this case:

template <typename... Args>
class WithListeners {
public:
    class Listener {
    public:
      virtual void operator()(Args... args) = 0;
    };

    void callListeners(Args... args) const {
        for (auto l : listeners) {
            if (l) (*l)(std::move(args)...);
        }
    }
};

Since you can still fully define the arguments of the listener:

class MyClassWithListener : public WithListeners<const int&>::Listener{
public:
    virtual void operator()(const int& value) override {
        //my handling code
    }
};


问:
JavaScript Define Property in Terms of Method
Please note this question is not answered by
Self-references in object literals / initializers
as that question addresses defining properties in terms of other properites, not methods.

Also, How does the "this" keyword in Javascript act within an object literal? is too high-level a decription of the subject for me to be able to solve my use case.

In Python, I can do this:

```<code>class Test:
    def __init__(self):
        self.id = self.get_id()

    def get_id(self):
        return 10

t = Test()
print(t.id)
</code>```

Meaning an object property can be defined in terms of a method of the same object.

In JavaScript, it doesn't work:

```<code>var Test = {
  id : this.getId(),
  getId : function() {
    return 10;
  }
};
</code>```

Gives script.js:47 Uncaught TypeError: this.getId is not a function

I've tried defining the id after the method definition but that didn't work.

How do I do this in JavaScript please?

答:
var Test = {
  get id() {
    return 10
  }
}

console.log(Test.id)```
</div>
</div>
</p>

<p>https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/get</p>

<p>or</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var Test = {
  get id () {
    return this.getId()
  },
  getId: function () {
    return 10
  }
}

console.log(Test.id)</code>```

Body:
Please note this question is not answered by
Self-references in object literals / initializers
as that question addresses defining properties in terms of other properites, not methods.

Also, How does the "this" keyword in Javascript act within an object literal? is too high-level a decription of the subject for me to be able to solve my use case.

In Python, I can do this:

class Test:
    def __init__(self):
        self.id = self.get_id()

    def get_id(self):
        return 10

t = Test()
print(t.id)

Meaning an object property can be defined in terms of a method of the same object.

In JavaScript, it doesn't work:

var Test = {
  id : this.getId(),
  getId : function() {
    return 10;
  }
};

Gives script.js:47 Uncaught TypeError: this.getId is not a function

I've tried defining the id after the method definition but that didn't work.

How do I do this in JavaScript please?

Body:
var Test = {
  get id() {
    return 10
  }
}

console.log(Test.id)

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/get

or

var Test = {
  get id () {
    return this.getId()
  },
  getId: function () {
    return 10
  }
}

console.log(Test.id)


问:
Convert XML data to ER diagram
Is it possible to convert data in XML/TXT format into an ER Diagram? If yes, how?

I am looking at any open-source tool or code that would help in doing so using C# or VB

答: No, it is almost impossible because I don't know any good ER Diagram open source tool which would accept xml in entry and generate diagrams from it.</p>

Title: Convert XML data to ER diagram


问:
Getting the event body attributes in Ruby with AWS Lambda
So I'm new to ruby and I have a simple REST API.

The post request looks like this:

```<code>POST /endpoint, { 'message': 1 }
</code>```

My lambda handler looks like this:

```<code>def run(event:, context:)
    puts "#{event['body']}"
    # prints the request body
end
</code>```

I'm trying to figure out how to store message, which is an int in a variable.

I was trying to do something like this but doesn't work

```<code>my_int = event['body']['message']
</code>```

答:
event['body'] is going to return a string, a json string.

You need to parse it with something like this.

```<code>body = JSON.parse(event['body'])
my_int = body['message']
</code>```

Also if you were to do.

```<code>puts event.inspect
</code>```

instead of

```<code>puts "#{event['body']}"
</code>```

you would have been able to see that body returned a string and not an object. I hope that helps and good luck.

Body:
So I'm new to ruby and I have a simple REST API.

The post request looks like this:

POST /endpoint, { 'message': 1 }

My lambda handler looks like this:

def run(event:, context:)
    puts "#{event['body']}"
    # prints the request body
end

I'm trying to figure out how to store message, which is an int in a variable.

I was trying to do something like this but doesn't work

my_int = event['body']['message']

Body:
event['body'] is going to return a string, a json string.

You need to parse it with something like this.

body = JSON.parse(event['body'])
my_int = body['message']

Also if you were to do.

puts event.inspect

instead of

puts "#{event['body']}"

you would have been able to see that body returned a string and not an object. I hope that helps and good luck.


问:
Swift 3 Send image to CloudKit with CKAsset
N.B: This is not a repeat question, I have looked at the other solutions but none are working in Swift 3, but they do in Swift 2.

I need to get an image from a photo library with UIImagePickerController, that is working fine, then what I need to do, is to somehow save that to a public record in CloudKit, I am very open as to how this is done. Please, if possible, be clear as to what I need to change/add and where.

I have provided my entire view controller file just to be sure.

```<code>import UIKit
import CloudKit

var email: String = ""

class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    //MARK: Properties

    @IBOutlet weak var firstNameField: UITextField!
    @IBOutlet weak var lastNameField: UITextField!
    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var passwordField: UITextField!
    @IBOutlet weak var confirmPasswordField: UITextField!
    @IBOutlet weak var notMatching: UILabel!
    @IBOutlet weak var emailLabel: UILabel!
    @IBOutlet weak var errorLabel: UILabel!

    @IBOutlet weak var photoImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.firstNameField.autocorrectionType = .no
        self.lastNameField.autocorrectionType = .no
        self.emailField.autocorrectionType = .no
        self.passwordField.autocorrectionType = .no
        self.confirmPasswordField.autocorrectionType = .no
        self.notMatching.isHidden = true

        firstNameField.delegate = self
        lastNameField.delegate = self
        emailField.delegate = self
        passwordField.delegate = self
        confirmPasswordField.delegate = self

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //MARK: UIImagePickerControllerDelegate

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

        // Dismiss the picker if the user canceled.
        dismiss(animated: true, completion: nil)

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        // The info dictionary may contain multiple representations of the image. You want to use the original.
        guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }

        // Set photoImageView to display the selected image.
        photoImageView.image = selectedImage

        // Dismiss the picker.
        dismiss(animated: true, completion: nil)

    }

    //MARK: Actions

    @IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {

        //Hide keyboards
        firstNameField.resignFirstResponder()
        lastNameField.resignFirstResponder()
        emailField.resignFirstResponder()
        passwordField.resignFirstResponder()
        confirmPasswordField.resignFirstResponder()

        let imagePickerController = UIImagePickerController()

        imagePickerController.sourceType = .photoLibrary

        imagePickerController.delegate = self
        present(imagePickerController, animated: true, completion: nil)

    }

    @IBAction func signUpPressed(_ sender: UIButton) {

        let container = CKContainer.default()
        let pubDB = container.publicCloudDatabase
        //let privDB = container.privateCloudDatabase

        //Check if users exist
        let query = CKQuery(recordType: "MyUsers", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
        pubDB.perform(query, inZoneWith: nil, completionHandler: { (records, error) in

            //error code 11 is no objects found
            if error == nil || error?._code == 11 {

                var emailExists = false

                for record in records! {

                    if record.object(forKey: "email") as? String == self.emailField.text {
                        //other user with the same username exists - don't allow user to create account
                        emailExists = true

                    }

                }

                if emailExists == true {

                    self.emailLabel.text = "\(self.emailField.text!) is taken. Please choose another one."

                } else {

                    if self.firstNameField.text != nil && self.lastNameField.text != nil && self.passwordField.text == self.confirmPasswordField.text {

                        //user can sign up

                        let record = CKRecord(recordType: "MyUsers")
                        record.setObject(self.emailField.text! as CKRecordValue?, forKey: "email")
                        record.setObject(self.passwordField.text! as CKRecordValue?, forKey: "password")
                        record.setObject(self.firstNameField.text! as CKRecordValue?, forKey: "firstName")
                        record.setObject(self.lastNameField.text! as CKRecordValue?, forKey: "lastName")

                        print("all good")

                        pubDB.save(record, completionHandler: { (record, error) in

                            if error == nil {

                                OperationQueue.main.addOperation {

                                    UserDefaults.standard.set(self.emailField.text!, forKey: "Email")
                                    email = self.emailField.text!
                                    //self.performSegue(withIdentifier: "Games", sender: self)

                                }

                            } else {

                                print(error)

                            }

                        })

                    } else {

                    }

                }

            } else {

                print(error)

            }

        })

    }

    // MARK: UITextFieldDelegate

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // Hide the keyboard.
        textField.resignFirstResponder()
        return true
    }

}
</code>```

Thank you!

答:
Swift 5 version, but abstracted to a function where I can pass in a UI Image object and return the URL to be used.  Useful where I had the image saved in CoreData and wanted to later upload to CloudKit as well.

```<code>func getImageURL(for image: UIImage?) -> URL {
    let documentsDirectoryPath:NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let tempImageName = "tempImage.jpg"
    var imageURL: URL?

    if let image = image {

        let imageData:Data = image.jpegData(compressionQuality: 1.0)!
        let path:String = documentsDirectoryPath.appendingPathComponent(tempImageName)
        try? image.jpegData(compressionQuality: 1.0)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
        imageURL = URL(fileURLWithPath: path)
        try? imageData.write(to: imageURL!, options: [.atomic])
    }
    return imageURL!
}
</code>```

And then how I use it:

```<code>  let imageURL = getImageURL(for: UIImage(data: itemToPublish!.Photo!)!)
  let imageAsset = CKAsset(fileURL: imageURL)
            itemBeingUpdated["photo"] = imageAsset

  CKContainer.default().publicCloudDatabase.save(challengeRecord) { ...
</code>```

Body:
N.B: This is not a repeat question, I have looked at the other solutions but none are working in Swift 3, but they do in Swift 2.

I need to get an image from a photo library with UIImagePickerController, that is working fine, then what I need to do, is to somehow save that to a public record in CloudKit, I am very open as to how this is done. Please, if possible, be clear as to what I need to change/add and where.

I have provided my entire view controller file just to be sure.

import UIKit
import CloudKit

var email: String = ""

class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    //MARK: Properties

    @IBOutlet weak var firstNameField: UITextField!
    @IBOutlet weak var lastNameField: UITextField!
    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var passwordField: UITextField!
    @IBOutlet weak var confirmPasswordField: UITextField!
    @IBOutlet weak var notMatching: UILabel!
    @IBOutlet weak var emailLabel: UILabel!
    @IBOutlet weak var errorLabel: UILabel!

    @IBOutlet weak var photoImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.firstNameField.autocorrectionType = .no
        self.lastNameField.autocorrectionType = .no
        self.emailField.autocorrectionType = .no
        self.passwordField.autocorrectionType = .no
        self.confirmPasswordField.autocorrectionType = .no
        self.notMatching.isHidden = true

        firstNameField.delegate = self
        lastNameField.delegate = self
        emailField.delegate = self
        passwordField.delegate = self
        confirmPasswordField.delegate = self

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //MARK: UIImagePickerControllerDelegate

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

        // Dismiss the picker if the user canceled.
        dismiss(animated: true, completion: nil)

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        // The info dictionary may contain multiple representations of the image. You want to use the original.
        guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }

        // Set photoImageView to display the selected image.
        photoImageView.image = selectedImage

        // Dismiss the picker.
        dismiss(animated: true, completion: nil)

    }

    //MARK: Actions

    @IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {

        //Hide keyboards
        firstNameField.resignFirstResponder()
        lastNameField.resignFirstResponder()
        emailField.resignFirstResponder()
        passwordField.resignFirstResponder()
        confirmPasswordField.resignFirstResponder()

        let imagePickerController = UIImagePickerController()

        imagePickerController.sourceType = .photoLibrary

        imagePickerController.delegate = self
        present(imagePickerController, animated: true, completion: nil)

    }

    @IBAction func signUpPressed(_ sender: UIButton) {

        let container = CKContainer.default()
        let pubDB = container.publicCloudDatabase
        //let privDB = container.privateCloudDatabase

        //Check if users exist
        let query = CKQuery(recordType: "MyUsers", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
        pubDB.perform(query, inZoneWith: nil, completionHandler: { (records, error) in

            //error code 11 is no objects found
            if error == nil || error?._code == 11 {

                var emailExists = false

                for record in records! {

                    if record.object(forKey: "email") as? String == self.emailField.text {
                        //other user with the same username exists - don't allow user to create account
                        emailExists = true

                    }

                }

                if emailExists == true {

                    self.emailLabel.text = "\(self.emailField.text!) is taken. Please choose another one."

                } else {

                    if self.firstNameField.text != nil && self.lastNameField.text != nil && self.passwordField.text == self.confirmPasswordField.text {

                        //user can sign up

                        let record = CKRecord(recordType: "MyUsers")
                        record.setObject(self.emailField.text! as CKRecordValue?, forKey: "email")
                        record.setObject(self.passwordField.text! as CKRecordValue?, forKey: "password")
                        record.setObject(self.firstNameField.text! as CKRecordValue?, forKey: "firstName")
                        record.setObject(self.lastNameField.text! as CKRecordValue?, forKey: "lastName")

                        print("all good")

                        pubDB.save(record, completionHandler: { (record, error) in

                            if error == nil {

                                OperationQueue.main.addOperation {

                                    UserDefaults.standard.set(self.emailField.text!, forKey: "Email")
                                    email = self.emailField.text!
                                    //self.performSegue(withIdentifier: "Games", sender: self)

                                }

                            } else {

                                print(error)

                            }

                        })

                    } else {

                    }

                }

            } else {

                print(error)

            }

        })

    }

    // MARK: UITextFieldDelegate

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // Hide the keyboard.
        textField.resignFirstResponder()
        return true
    }

}

Thank you!

Body:
Swift 5 version, but abstracted to a function where I can pass in a UI Image object and return the URL to be used.  Useful where I had the image saved in CoreData and wanted to later upload to CloudKit as well.

func getImageURL(for image: UIImage?) -> URL {
    let documentsDirectoryPath:NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let tempImageName = "tempImage.jpg"
    var imageURL: URL?

    if let image = image {

        let imageData:Data = image.jpegData(compressionQuality: 1.0)!
        let path:String = documentsDirectoryPath.appendingPathComponent(tempImageName)
        try? image.jpegData(compressionQuality: 1.0)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
        imageURL = URL(fileURLWithPath: path)
        try? imageData.write(to: imageURL!, options: [.atomic])
    }
    return imageURL!
}

And then how I use it:

  let imageURL = getImageURL(for: UIImage(data: itemToPublish!.Photo!)!)
  let imageAsset = CKAsset(fileURL: imageURL)
            itemBeingUpdated["photo"] = imageAsset

  CKContainer.default().publicCloudDatabase.save(challengeRecord) { ...


问:
Number of rows with specified number of null columns
How to get information how many rows in a table have particular number of nulls in it?

I want to get something like this:

```<code>Number of nulls | Number of rows
        0       |      10
        1       |       4
        2       |      11
</code>```

Motivation:

I need this for data mining purposes. If for example I have an observation that has in almost all columns null value then I need to get rid of this observation, but there can be also a situation where many observations have small value of nulls which is acceptable.

答:
For SQL Server 2008 you can do </p>

```<code>DECLARE @T TABLE
(
pk INT PRIMARY KEY,
c1 INT,
c2 INT,
c3 VARCHAR(10)
)

INSERT INTO @T
SELECT 1,1,1,'foo'
UNION ALL
SELECT 2,1,NULL,'bar'
UNION ALL
SELECT 3,NULL,NULL,NULL
UNION ALL
SELECT 4,NULL,NULL,NULL

SELECT Num AS [Number of Nulls],
       COUNT(*) AS [Number of rows]
FROM @T
CROSS APPLY (SELECT COUNT(*) - COUNT(c) FROM (VALUES(cast(c1 as SQL_VARIANT)),
                                                    (c2),
                                                    (c3)) T (c)) CA(Num)
GROUP BY Num
</code>```

Body:
How to get information how many rows in a table have particular number of nulls in it?

I want to get something like this:

Number of nulls | Number of rows
        0       |      10
        1       |       4
        2       |      11

Motivation:

I need this for data mining purposes. If for example I have an observation that has in almost all columns null value then I need to get rid of this observation, but there can be also a situation where many observations have small value of nulls which is acceptable.

Body:
For SQL Server 2008 you can do

DECLARE @T TABLE
(
pk INT PRIMARY KEY,
c1 INT,
c2 INT,
c3 VARCHAR(10)
)

INSERT INTO @T
SELECT 1,1,1,'foo'
UNION ALL
SELECT 2,1,NULL,'bar'
UNION ALL
SELECT 3,NULL,NULL,NULL
UNION ALL
SELECT 4,NULL,NULL,NULL

SELECT Num AS [Number of Nulls],
       COUNT(*) AS [Number of rows]
FROM @T
CROSS APPLY (SELECT COUNT(*) - COUNT(c) FROM (VALUES(cast(c1 as SQL_VARIANT)),
                                                    (c2),
                                                    (c3)) T (c)) CA(Num)
GROUP BY Num


问:
Data formatting in postgresql
Each "user_id" has multiple observations with distinct “Status” values.

```<code>user_id        status         score      region
  1001         applied         700    california
  1001         pre_approved    700    california
  1001         Approved        700    california
</code>```

What i am trying to do is having one observation per user_id with flags indicating which "Status" values were observed for the "user_id".

```<code>user_id    applied_ind  pre_approved_ind   Approved_ind         score      region
  1001           1                 1               1             700    california
</code>```

答:
You can use conditional aggregation:</p>

```<code>select user_id,
       max(1) filter (where status = 'applied') as applied_ind,
       max(1) filter (where status = 'pre_approved') as pre_approved_ind,
       max(1) filter (where status = 'approved') as approved_ind,
       score, region
from t
group by user_id, score, region;
</code>```

Title: Data formatting in postgresql

Body:
Each "user_id" has multiple observations with distinct “Status” values.

user_id        status         score      region
  1001         applied         700    california
  1001         pre_approved    700    california
  1001         Approved        700    california

What i am trying to do is having one observation per user_id with flags indicating which "Status" values were observed for the "user_id".

user_id    applied_ind  pre_approved_ind   Approved_ind         score      region
  1001           1                 1               1             700    california

Body:
You can use conditional aggregation:

select user_id,
       max(1) filter (where status = 'applied') as applied_ind,
       max(1) filter (where status = 'pre_approved') as pre_approved_ind,
       max(1) filter (where status = 'approved') as approved_ind,
       score, region
from t
group by user_id, score, region;