问:
How to create an intersection with complexity in O (n)?
I need to create a function that intersects two vectors: vectorA ∩ vectorB and allocates the values found in this intersection in a vectorC!

Rules:

(a) The complexity of the function/method must be:

O(n), if n> m

O(m), if m> n

(b) The complexity of the program (function / main method) must be:

O(n log n), if n > m

O(m log m), if m > n

c) The signing of the function of intersection shall be obligatorily:

void intersections (char a [], int n, char b [], int m, char c [], int * k)

d) Predefined language functions can not be used to treat vectors (search, pertinence, insertion, deletion, ordering, etc.).

I was thinking of using an algorithm of complexity O(n) which is called "Linear Time". However this algorithm makes it "linear" comparison obviously as the name says.

Example:

```<code>A = { 'E', 'C', 'B', 'J', 'S', 'F', 'C', 'V', 'G' }
B = { 'G', 'C', 'M', 'W', 'L', 'O' }
C = { 'G', 'C' }
</code>```

How far have I come?

Currently I can fetch and compare the corresponding values for the intersection.

What is my difficulty?

1) The values after the comparison can not be added to the vector char c[] with repetitions. How to prevent the same?

2) How to use the pointer int *k (which is the size of the vector char c[]) and allocate the corresponding values without repetitions to it?

```<code>bool checkHasStringEqual(char vectorA, char vectorB) {
    string stringA, stringB;
    stringA = toupper(vectorA),
    stringB = toupper(vectorB);

    size_t found = stringA.find(stringB);

    return (found != std::string::npos);
}

void intersection(char a[], char b[], char c[], int n, int m, int *k){
    int indexA = 0, indexB = 0, counterIntersection = 0;

    if(n > m) {
        while(indexA < n) {
            if(indexB != m) {
                if(checkHasStringEqual(a[indexA], b[indexB])) {
                    cout << "STRING A: " << a[indexA] << " == " << "STRING B: " << b[indexB] << endl;
                    counterIntersection++;
                }

                cout << "( " << a[indexA] << "-->" << b[indexB] << ")" << " -- " << "( " << indexA << ", " << indexB << ")" << endl;
                (indexA == n -1) ? (indexA = 0, indexB++) : indexA++;

            } else {
                cout << "CAME TO THE END OF THE ANALYSIS" << endl;
                break;
            }
        }
    }

    if(m > n) {
        //TODO
    }
}
</code>```

答:
The stated task is doable in linear time using a single lookup table, even without sorting, due to the significantly restricted domain size being managed. char has at-most 1 << CHAR_BIT distinct representations. On almost all systems that is simply 8-bits, or 256 possible values. A char16_t  would use 16 bits, or 65536 possible representations, and of course, a char32_t, would have over 2-billion representations.

I'm assuming we're in the domain of the first one, or even two, of these, and not the last. Given that, this is doable with a single markup table indexed by all possible values within the domain. The algorithm is simple:

Start with an table of markers, size = 1 << CHAR_BIT, all initialized to false.

Enumerate either input sequence.

For each character take the unsigned char equivalent as an index into the markup table, setting the table value to true

Enumerate the other input sequence.

For each character take the unsigned char equivalent value as an index into he markup table. If the value is true, clear it to false and add that character to the output sequence.

When finished, the result will be a unique-set-intersection of the two input character sequences. An example is given below. As it (and many other things) was not specified, I took liberty to make k an in/out argument. On input it refers to the maximum number of chars that can fit in C[], On output it contains the number of chars actually stored.

```<code>#include <iostream>
#include <climits>

void mk_intersection(char a[], int n, char b[], int m, char c[], int * k)
{
    bool tbl[1 << CHAR_BIT] = { 0 };

    int o = *k;
    *k = 0;

    // markup a[]
    for (int i = 0; i < n; ++i)
        tbl[static_cast<unsigned char>(a[i])] = true;

    // filter b[] from markup
    for (int i = 0; i < m && *k < o; ++i)
    {
        if (tbl[static_cast<unsigned char>(b[i])])
        {
            tbl[static_cast<unsigned char>(b[i])] = false;
            c[(*k)++] = b[i];
        }
    }
}

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

    char A[] = { 'E', 'C', 'B', 'J', 'S', 'F', 'C', 'V', 'G' };
    char B[] = { 'G', 'C', 'M', 'W', 'L', 'O' };
    char C[std::max(sizeof A, sizeof B)] = { 0 };
    int c_len = sizeof C;

    mk_intersection(A, sizeof A, B, sizeof B, C, &c_len);

    for (int i = 0; i < c_len; ++i)
        std::cout.put(C[i]);
    std::cout.put('\n');

    return 0;
}
</code>```

Output

```<code>GC
</code>```

That's it. Regarding your question of "how to make main O(n log n), frankly, that's nonsense. It implies that you can, at your discretion, presort the input before invoking your intersection operation. In doing so you can implement your function using a simple one-pass merge, which would work, and not have the domain-size limit I've described earlier. But for this example it is neither needed, nor warranted. It isn't required. And frankly, both arguments a[] and b[] could (and should) be const.

Body:
I need to create a function that intersects two vectors: vectorA ∩ vectorB and allocates the values found in this intersection in a vectorC!

Rules:

(a) The complexity of the function/method must be:

O(n), if n> m

O(m), if m> n

(b) The complexity of the program (function / main method) must be:

O(n log n), if n > m

O(m log m), if m > n

c) The signing of the function of intersection shall be obligatorily:

void intersections (char a [], int n, char b [], int m, char c [], int * k)

d) Predefined language functions can not be used to treat vectors (search, pertinence, insertion, deletion, ordering, etc.).

I was thinking of using an algorithm of complexity O(n) which is called "Linear Time". However this algorithm makes it "linear" comparison obviously as the name says.

Example:

A = { 'E', 'C', 'B', 'J', 'S', 'F', 'C', 'V', 'G' }
B = { 'G', 'C', 'M', 'W', 'L', 'O' }
C = { 'G', 'C' }

How far have I come?

Currently I can fetch and compare the corresponding values for the intersection.

What is my difficulty?

1) The values after the comparison can not be added to the vector char c[] with repetitions. How to prevent the same?

2) How to use the pointer int *k (which is the size of the vector char c[]) and allocate the corresponding values without repetitions to it?

bool checkHasStringEqual(char vectorA, char vectorB) {
    string stringA, stringB;
    stringA = toupper(vectorA),
    stringB = toupper(vectorB);

    size_t found = stringA.find(stringB);

    return (found != std::string::npos);
}

void intersection(char a[], char b[], char c[], int n, int m, int *k){
    int indexA = 0, indexB = 0, counterIntersection = 0;

    if(n > m) {
        while(indexA < n) {
            if(indexB != m) {
                if(checkHasStringEqual(a[indexA], b[indexB])) {
                    cout << "STRING A: " << a[indexA] << " == " << "STRING B: " << b[indexB] << endl;
                    counterIntersection++;
                }

                cout << "( " << a[indexA] << "-->" << b[indexB] << ")" << " -- " << "( " << indexA << ", " << indexB << ")" << endl;
                (indexA == n -1) ? (indexA = 0, indexB++) : indexA++;

            } else {
                cout << "CAME TO THE END OF THE ANALYSIS" << endl;
                break;
            }
        }
    }

    if(m > n) {
        //TODO
    }
}

Body:
The stated task is doable in linear time using a single lookup table, even without sorting, due to the significantly restricted domain size being managed. char has at-most 1 << CHAR_BIT distinct representations. On almost all systems that is simply 8-bits, or 256 possible values. A char16_t  would use 16 bits, or 65536 possible representations, and of course, a char32_t, would have over 2-billion representations.

I'm assuming we're in the domain of the first one, or even two, of these, and not the last. Given that, this is doable with a single markup table indexed by all possible values within the domain. The algorithm is simple:

Start with an table of markers, size = 1 << CHAR_BIT, all initialized to false.

Enumerate either input sequence.

For each character take the unsigned char equivalent as an index into the markup table, setting the table value to true

Enumerate the other input sequence.

For each character take the unsigned char equivalent value as an index into he markup table. If the value is true, clear it to false and add that character to the output sequence.

When finished, the result will be a unique-set-intersection of the two input character sequences. An example is given below. As it (and many other things) was not specified, I took liberty to make k an in/out argument. On input it refers to the maximum number of chars that can fit in C[], On output it contains the number of chars actually stored.

#include <iostream>
#include <climits>

void mk_intersection(char a[], int n, char b[], int m, char c[], int * k)
{
    bool tbl[1 << CHAR_BIT] = { 0 };

    int o = *k;
    *k = 0;

    // markup a[]
    for (int i = 0; i < n; ++i)
        tbl[static_cast<unsigned char>(a[i])] = true;

    // filter b[] from markup
    for (int i = 0; i < m && *k < o; ++i)
    {
        if (tbl[static_cast<unsigned char>(b[i])])
        {
            tbl[static_cast<unsigned char>(b[i])] = false;
            c[(*k)++] = b[i];
        }
    }
}

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

    char A[] = { 'E', 'C', 'B', 'J', 'S', 'F', 'C', 'V', 'G' };
    char B[] = { 'G', 'C', 'M', 'W', 'L', 'O' };
    char C[std::max(sizeof A, sizeof B)] = { 0 };
    int c_len = sizeof C;

    mk_intersection(A, sizeof A, B, sizeof B, C, &c_len);

    for (int i = 0; i < c_len; ++i)
        std::cout.put(C[i]);
    std::cout.put('\n');

    return 0;
}

Output

GC

That's it. Regarding your question of "how to make main O(n log n), frankly, that's nonsense. It implies that you can, at your discretion, presort the input before invoking your intersection operation. In doing so you can implement your function using a simple one-pass merge, which would work, and not have the domain-size limit I've described earlier. But for this example it is neither needed, nor warranted. It isn't required. And frankly, both arguments a[] and b[] could (and should) be const.


来源: stackexchange

问:
Is that possible to replace text from html code
I have variable label1= "please pay $ 50:#000000"
and is that possible to replace :#000000 and set color :#000000 from html code

Now my html code is like this

```<code><labe>{{label1}}</label>
</code>```

but I need to make it like:

if(label1 contains :#000000 or :DC143C then replace it with empty string("") and set font color as color which is available in variable label1

答:
Yes. You can split variable label1 by :

Try this:

TS:

```<code>GetValue(str: string, type:string) {
    var splitArray: string[] = str.split(":");

    if(type == "text") {
      return splitArray[0];
    } else {
      return splitArray[1];
    }
}
</code>```

HTML:

```<code><label [style.color]="GetValue(label1,'color')">
    <span [innerHtml]="GetValue(label1,'text')">
    </span>
</label>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have variable label1= "please pay $ 50:#000000"
and is that possible to replace :#000000 and set color :#000000 from html code

Now my html code is like this

<labe>{{label1}}

but I need to make it like:

if(label1 contains :#000000 or :DC143C then replace it with empty string("") and set font color as color which is available in variable label1

Body:
Yes. You can split variable label1 by :

Try this:

TS:

GetValue(str: string, type:string) {
    var splitArray: string[] = str.split(":");

    if(type == "text") {
      return splitArray[0];
    } else {
      return splitArray[1];
    }
}

HTML:

<label [style.color]="GetValue(label1,'color')">
    <span [innerHtml]="GetValue(label1,'text')">
    </span>
</label>


问:
Cannot Get Constraint to Work on SQL Task in ForEach Loop
I am trying to perform a pretty basic process:

(Reset) Truncate Table

Loop Through Folder of Files

Check to See if FileName Exists in FILES Table

If Not, Import Data from File Into DATA Table

Insert FileName into FILES Table

I can get it to go through the folder of files, load them, and insert the filename into the table.  However, I cannot get the constraint to work so that it ONLY loads the files that are not already in the FILES table.

Here is my overall setup:

Variables:

Here's the ForEach Loop Setup:

'File Exists in Table' SQL Task:

I tried:

```<code>SELECT COUNT(id) as id FROM PORG_Files WHERE filename = ?
</code>```

I also tried a SqlStatementSource Expression of:

```<code>"SELECT COUNT(id) as id FROM PORG_Files WHERE filename = '" + @[User::CurrentFileName] + "'"
</code>```

But I wasn't sure what to do with the SQLStatement under General while using the Expression.

Here is the Contstraint that always seems to be True:

I thought the issue was with the path formatting where the variable has double \s, but with the REPLACE to correct it, it isn't working.

For good measure, here is the 'Insert File into Table' SQL Task:

Files insert into the table just fine, here is how the table looks:

What the hell am I doing wrong?!?!

Thanks!!

答:
It ended up being a few things.

The constraint did need to use @[User::id] == 0

I needed to use @[User::CurrentFileName] in the Query in the SQL Task

I did NOT need the REPLACE in the Query

Thank you, without the multitude of ideas I may not have figured it out!

Body:
I am trying to perform a pretty basic process:

(Reset) Truncate Table

Loop Through Folder of Files

Check to See if FileName Exists in FILES Table

If Not, Import Data from File Into DATA Table

Insert FileName into FILES Table

I can get it to go through the folder of files, load them, and insert the filename into the table.  However, I cannot get the constraint to work so that it ONLY loads the files that are not already in the FILES table.

Here is my overall setup:

Variables:

Here's the ForEach Loop Setup:

'File Exists in Table' SQL Task:

I tried:

SELECT COUNT(id) as id FROM PORG_Files WHERE filename = ?

I also tried a SqlStatementSource Expression of:

"SELECT COUNT(id) as id FROM PORG_Files WHERE filename = '" + @[User::CurrentFileName] + "'"

But I wasn't sure what to do with the SQLStatement under General while using the Expression.

Here is the Contstraint that always seems to be True:

I thought the issue was with the path formatting where the variable has double \s, but with the REPLACE to correct it, it isn't working.

For good measure, here is the 'Insert File into Table' SQL Task:

Files insert into the table just fine, here is how the table looks:

What the hell am I doing wrong?!?!

Thanks!!


问:
while read line not working on mac with makefile
I am having to do this and it's still not working (i.e. put everything on a single line):

```<code>commit:
  cat data/commit-folders.csv | while read line; do git add $line/; git commit $line/ -m 'Autocommit'; git push origin master; done
.PHONY: commit
</code>```

For some reason $line is showing up as ine and I've tried $(line) and still no go. I would like to put this on multiple lines too but haven't figured that out.

```<code>commit:
  cat data/commit-folders.csv | while read line \
    do
      -git add $line
      -git commit $line/ -m 'Autocommit'
      -git push origin master
    done
</code>```

The - on -git is for Makefile to ignore the errors from the command. I would like to maintain that behavior in this situation if possible.

Basically I am trying to read a CSV file which just has a path per line (a folder like foo/bar/baz) and I want to commit foo/bar/baz/ with the trailing slash.

答:
For some reason $line is showing up as ine and I've tried $(line)

$ gets expanded by make first. So $line is read as ${l}ine, and as ${l} is undefined in makefile, it results in ine.

Also ${line} expands to nothing, as in your case it should be a shell's variable, not make's one.

So the right solution is $$line, which first (by make) is expanded to $line, and then (by shell) to the right value.

I would like to put this on multiple lines too but haven't figured that out.

With GNU make you can use .ONESHELL:

```<code>.ONESHELL:
commit:
    cat data/commit-folders.csv | while read line \
    do
        git add $$line
        git commit $$line/ -m 'Autocommit'
        git push origin master
    done
    exit 0
</code>```

The - on -git is for Makefile to ignore the errors from the command

This is needed when you don't use .ONESHELL. With .ONESHELL it basically works as if you execute a shell script file.

Body:
I am having to do this and it's still not working (i.e. put everything on a single line):

commit:
  cat data/commit-folders.csv | while read line; do git add $line/; git commit $line/ -m 'Autocommit'; git push origin master; done
.PHONY: commit

For some reason $line is showing up as ine and I've tried $(line) and still no go. I would like to put this on multiple lines too but haven't figured that out.

commit:
  cat data/commit-folders.csv | while read line \
    do
      -git add $line
      -git commit $line/ -m 'Autocommit'
      -git push origin master
    done

The - on -git is for Makefile to ignore the errors from the command. I would like to maintain that behavior in this situation if possible.

Basically I am trying to read a CSV file which just has a path per line (a folder like foo/bar/baz) and I want to commit foo/bar/baz/ with the trailing slash.

Body:
For some reason $line is showing up as ine and I've tried $(line)

$ gets expanded by make first. So $line is read as ${l}ine, and as ${l} is undefined in makefile, it results in ine.

Also ${line} expands to nothing, as in your case it should be a shell's variable, not make's one.

So the right solution is $$line, which first (by make) is expanded to $line, and then (by shell) to the right value.

I would like to put this on multiple lines too but haven't figured that out.

With GNU make you can use .ONESHELL:

.ONESHELL:
commit:
    cat data/commit-folders.csv | while read line \
    do
        git add $$line
        git commit $$line/ -m 'Autocommit'
        git push origin master
    done
    exit 0

The - on -git is for Makefile to ignore the errors from the command

This is needed when you don't use .ONESHELL. With .ONESHELL it basically works as if you execute a shell script file.


问:
How to configure the project and virtualenv paths in crontab to schedule jobs in Django?
I am using a library called django_cron to schedule tasks with Django. I've already done all the required setup, including, but not limited to adding this chunk of code to the crons.py file:

```<code>class MyCronJob(CronJobBase):
    RUN_EVERY_MINS = 1 # every 2 minutes.

    schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
    code = 'core.my_cron_job'    # a unique code

    def do(self):
       pass;
</code>```

However, I am having a lot of trouble to configure the contrab command in the contrab editor. I am currently using this command (because I am using a virtual environment):

```<code>* * * * * source /Users/myame/Desktop/dev/Websites/django_env/bin/activate
&& python /Users/myname/Desktop/dev/Websites/project/manage.py runcrons
</code>```

I am getting this error:

```<code>crontab: installing new crontab
"/tmp/crontab.kdldvixya8":4: bad minute
crontab: errors in crontab file, can't install
</code>```

How can I solve this? What's wrong with it? Thank you in advance.

答:
You don't need to activate the virtualenv, you can just call python within there directly.  Try like this

```<code>0 * * * * /Users/myame/Desktop/dev/Websites/django_env/bin/python /Users/myname/Desktop/dev/Websites/project/manage.py runcrons
</code>```

Should run on the hour

Body:
I am using a library called django_cron to schedule tasks with Django. I've already done all the required setup, including, but not limited to adding this chunk of code to the crons.py file:

class MyCronJob(CronJobBase):
    RUN_EVERY_MINS = 1 # every 2 minutes.

    schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
    code = 'core.my_cron_job'    # a unique code

    def do(self):
       pass;

However, I am having a lot of trouble to configure the contrab command in the contrab editor. I am currently using this command (because I am using a virtual environment):

* * * * * source /Users/myame/Desktop/dev/Websites/django_env/bin/activate
&& python /Users/myname/Desktop/dev/Websites/project/manage.py runcrons

I am getting this error:

crontab: installing new crontab
"/tmp/crontab.kdldvixya8":4: bad minute
crontab: errors in crontab file, can't install

How can I solve this? What's wrong with it? Thank you in advance.

Body:
You don't need to activate the virtualenv, you can just call python within there directly.  Try like this

0 * * * * /Users/myame/Desktop/dev/Websites/django_env/bin/python /Users/myname/Desktop/dev/Websites/project/manage.py runcrons

Should run on the hour


问:
Find an object in array
I am making a filter that allows user clicks a checkbox to do filter. When I click a checkbox, It will add that object of item into an array of filters. When clicking again that item, I will remove that item from the array.

I am using a hard code for the object of item to make sure they are the same object every time I click. The object look like this:

var item1 = {name: "A", id: 1};

The below toggleFilter method is triggered when I click a checkbox, then dispatch an action from Vuex.

```<code>methods: {
            toggleFilter(categoryId) {
                var item1 = {name: "A", id: 1};

                this.$store.dispatch('filter/toggleFilter', item1);
            }
        }
</code>```

Vuex action:

```<code>let actions = {
    toggleFilter({state, commit, rootState, rootGetters}, attribute) {
        let index = state.filters.indexOf(attribute);

        if (index === -1) {
            commit('addFilter', attribute);
        } else {
            commit('removeFilter', index);
        }

        console.log(state.filters);
    }
};
</code>```

The problem is when I click again the checkbox, it doesn't remove the object from the array, it adds 1 more object into it.

One more weirdness thing is I use the exact above Vuex action for another object, something like this:

```<code>methods: {
            toggleFilter(option) {
                option.attributeId = this.attribute.id;
                option.type = 'attribute';

                this.$store.dispatch('filter/toggleFilter', option);
            }
        }
</code>```

And it works. I don't know why the 1st case doesn't work, but the 2nd case works.

答:
Every time you create new object var item1 = {name: "A", id: 1};, so indexOf can't not find it. If you item's id is unique, you can try comparing attribute.id

```<code>let actions = {
    toggleFilter({state, commit, rootState, rootGetters}, attribute) {
    let index = state.filters.map(item => item.id).indexOf(attribute.id);
        if (index === -1) {
            commit('addFilter', attribute);
        } else {
            commit('removeFilter', index);
        }

        console.log(state.filters);
    }
};
</code>```

Title: Find an object in array

Body:
I am making a filter that allows user clicks a checkbox to do filter. When I click a checkbox, It will add that object of item into an array of filters. When clicking again that item, I will remove that item from the array.

I am using a hard code for the object of item to make sure they are the same object every time I click. The object look like this:

var item1 = {name: "A", id: 1};

The below toggleFilter method is triggered when I click a checkbox, then dispatch an action from Vuex.

methods: {
            toggleFilter(categoryId) {
                var item1 = {name: "A", id: 1};

                this.$store.dispatch('filter/toggleFilter', item1);
            }
        }

Vuex action:

let actions = {
    toggleFilter({state, commit, rootState, rootGetters}, attribute) {
        let index = state.filters.indexOf(attribute);

        if (index === -1) {
            commit('addFilter', attribute);
        } else {
            commit('removeFilter', index);
        }

        console.log(state.filters);
    }
};

The problem is when I click again the checkbox, it doesn't remove the object from the array, it adds 1 more object into it.

One more weirdness thing is I use the exact above Vuex action for another object, something like this:

methods: {
            toggleFilter(option) {
                option.attributeId = this.attribute.id;
                option.type = 'attribute';

                this.$store.dispatch('filter/toggleFilter', option);
            }
        }

And it works. I don't know why the 1st case doesn't work, but the 2nd case works.

Body:
Every time you create new object var item1 = {name: "A", id: 1};, so indexOf can't not find it. If you item's id is unique, you can try comparing attribute.id

let actions = {
    toggleFilter({state, commit, rootState, rootGetters}, attribute) {
    let index = state.filters.map(item => item.id).indexOf(attribute.id);
        if (index === -1) {
            commit('addFilter', attribute);
        } else {
            commit('removeFilter', index);
        }

        console.log(state.filters);
    }
};


问:
What the Chinese, Japanese, and Korean characters are in Unicode
From what I've gathered:

Hiragana is U+3040 to U+309F

Katakana is U+30A0 to U+30FF.

U+4E00..U+9FFF is part of the complete [Chinese] set, but not all.

The exact ranges for Chinese characters (except the extensions) are [\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD].

CJK (for Chinese, Japanese, Korean) encompasses all characters for the Chinese Hànzì, the Japanese Kanji and the Korean Hanja. (So they are all mixed).

The linked answers don't fully explain where everything is. Wondering if there is a clear answer to this so I don't have to go through each character one-by-one.

答:
This is a sorted list containing anything that's used in Chinese, Japanese, Korean (and also some Vietnamese)

U+1100..U+11FF: Hangul Jamo

U+2E80..U+2EFFCJK Radicals Supplement

U+2F00..U+2FDF: Kangxi Radicals

U+3000..U+303F: CJK Symbols and Punctuation (may not be counted as characters, depending on what you want to do)

U+3040..U+309F: Hiragana

U+30A0..U+30FF: Katakana

U+3100..U+312F: Bopomofo

U+3130..U+318F: Hangul Compatibility Jamo

U+3190..U+319F: Kanbun

U+31A0..U+31BF: Bopomofo Extended

U+31C0..U+31EF: CJK Strokes

U+31F0..U+31FF: Katakana Phonetic Extensions

U+31F0..U+31FF: Katakana Phonetic Extensions

U+3200..U+32FF: Enclosed CJK Letters and Months

U+3300..U+33FF: CJK Compatibility

U+3400..U+4DBF: CJK Unified Ideographs Extension A

U+4E00..U+9FEF: CJK Unified Ideographs

U+A960..U+A97F: Hangul Jamo Extended-A

U+AC00..U+D7A3: Hangul Syllables

U+D7B0..U+D7FF: Hangul Jamo Extended-B

U+F900..U+FAFF: CJK Compatibility Ideographs

U+FE30..U+FE4F: CJK Compatibility Forms

U+FF00..U+FFEF: Halfwidth and Fullwidth Forms. But this also contains punctuation symbols and Latin alphabet. Real Katakana and Jamo characters are from U+FF66 to U+FFDD

U+1B000..U+1B0FF: Kana Supplement

U+1B100..U+1B12F: Kana Extended-A

U+1B130..U+1B16F: Small Kana Extension

U+1F200..U+1F2FF: Enclosed Ideographic Supplement

U+20000..U+2A6DF: CJK Unified Ideographs Extension B

U+2A700..U+2B73F: CJK Unified Ideographs Extension C

U+2B740..U+2B81F: CJK Unified Ideographs Extension D

U+2B820..U+2CEAF: CJK Unified Ideographs Extension E

U+2CEB0..U+2EBEF: CJK Unified Ideographs Extension F

U+2F800..U+2FA1F: CJK Compatibility Ideographs Supplement

U+30000..U+3134F: CJK Unified Ideographs Extension G


问:
How to unwrap a div and then add a div to the next item in a list on a click
I asked a question earlier (Remove a class and then add a class to the next item in a rundown when clicking a button) and while that one works, I asked the wrong type of question. Inside of removing and adding a class, I'm trying to wrap and unwrap a div inside another div and wrap a div inside the next item on a click.

What I'm trying to do is remove the div wrapping of .current around item 1 and wrap a div called .current on the next item in the rundown (item 2).

My code:

(function() {
  $("#next-item").on("click", function() {
    var curr = $('.nav-right').children('.current'); //find .current
    if (curr.next().length > 0) { // If you want to stop at last element
      curr.next().wrapInner('current'); //wrap a div around next item
      curr.contents().unwrap(); //unwrap div from previous item
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.current {
  border: 1px solid
}</code>```

<button id="next-item">next item</button>

item 1

item 2

item 3

item 4

item 5

```

JS Fiddle: https://jsfiddle.net/openbayou/wzt6bp0d/

答:
The code below gives the onclick an ability to loop, even from the beginning when it reaches the end:

```<code>$(function(){

    // store all items
    var allItems =  $(".nav-right").children();

    // initialize for loop counter
    var i = 0;

    // onclick
    $("#next-item").on("click", function(){

       // select the current item
       var wrapper = document.querySelector('.current');

       // removing the current wrapper
       wrapper.outerHTML = wrapper.innerHTML;

       // looping and wrap the next item with current div
       i = (i + 1) % allItems.length;
       allItems.eq(i).wrapInner('<div class="current"></div>');
    });

});
</code>```

Updated as per suggestion of @daniel-beck:

```<code>$(function(){

    // store all items
    var allItems =  $(".nav-right").children();

    // initialize for loop counter
    var i = 0;

    // onclick
    $("#next-item").on("click", function(){

       // select the current item and remove the current wrapper
       $('.current').contents().unwrap();

       // looping and wrap the next item with current div
       i = (i + 1) % allItems.length;
       allItems.eq(i).wrapInner('<div class="current"></div>');
    });

});
</code>```

Body:
I asked a question earlier (Remove a class and then add a class to the next item in a rundown when clicking a button) and while that one works, I asked the wrong type of question. Inside of removing and adding a class, I'm trying to wrap and unwrap a div inside another div and wrap a div inside the next item on a click.

What I'm trying to do is remove the div wrapping of .current around item 1 and wrap a div called .current on the next item in the rundown (item 2).

My code:

(function() {
  $("#next-item").on("click", function() {
    var curr = $('.nav-right').children('.current'); //find .current
    if (curr.next().length > 0) { // If you want to stop at last element
      curr.next().wrapInner('current'); //wrap a div around next item
      curr.contents().unwrap(); //unwrap div from previous item
    }
  });
});

.current {
  border: 1px solid
}

<button id="next-item">next item</button>

item 1

item 2

item 3

item 4

item 5

JS Fiddle: https://jsfiddle.net/openbayou/wzt6bp0d/

Body:
The code below gives the onclick an ability to loop, even from the beginning when it reaches the end:

$(function(){

    // store all items
    var allItems =  $(".nav-right").children();

    // initialize for loop counter
    var i = 0;

    // onclick
    $("#next-item").on("click", function(){

       // select the current item
       var wrapper = document.querySelector('.current');

       // removing the current wrapper
       wrapper.outerHTML = wrapper.innerHTML;

       // looping and wrap the next item with current div
       i = (i + 1) % allItems.length;
       allItems.eq(i).wrapInner('<div class="current"></div>');
    });

});

Updated as per suggestion of @daniel-beck:

$(function(){

    // store all items
    var allItems =  $(".nav-right").children();

    // initialize for loop counter
    var i = 0;

    // onclick
    $("#next-item").on("click", function(){

       // select the current item and remove the current wrapper
       $('.current').contents().unwrap();

       // looping and wrap the next item with current div
       i = (i + 1) % allItems.length;
       allItems.eq(i).wrapInner('<div class="current"></div>');
    });

});


问:
undefined reference to `curl_easy_init' on CLion/Mingw
I am trying to use curl inside c++ code. How should i do it properly ?

I have pasted libcurl.a & libcurl.dll.a in this directory:
C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\lib

This is my CMakeLists.txt from CLion/Mingw

```<code>cmake_minimum_required(VERSION 3.3)
project(tan)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -lcurl.dll")
add_executable(tan Tan/mail.cpp)
project(untitled6)
</code>```

When I add "#define CURL_STATICLIB" i get these errors:

```<code>reference to `curl_easy_init'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:84: undefined
reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:86: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:91: undefined reference to `curl_slist_append'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:92: undefined reference to `curl_slist_append'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:93: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:98: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:99: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:100: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:103: undefined reference to `curl_easy_perform'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:107: undefined reference to `curl_easy_strerror'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:111: undefined reference to `curl_slist_free_all'
C:/Users/John/CLionProjects/tan/Tam/mail.cpp:121: undefined reference to ````curl_easy_cleanup

Without "#define CURL_STATICLIB" i get these errors:

CMakeFiles\tan.dir/objects.a(mail.cpp.obj): In function `main':
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:81: undefined reference to `__imp_curl_easy_init'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:84: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:86: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:91: undefined reference to `__imp_curl_slist_append'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:92: undefined reference to `__imp_curl_slist_append'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:93: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:98: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:99: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:100: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:103: undefined reference to `__imp_curl_easy_perform'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:107: undefined reference to `__imp_curl_easy_strerror'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:111: undefined reference to `__imp_curl_slist_free_all'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:121: undefined reference to `__imp_curl_easy_cleanup'
```

答:
If anybody comes looking use this in CMakeLists.txt. The last line solved the issue.

Step1:
Copy libcurl.dll.a in C:/curl.
No need to copy "libcurl.a" OR "libcurl.dll.a" at any other place.
No need for #define CURL_STATICLIB in main.cpp file

Step2: Edit the CMakeLists.txt as below.

```<code>set(CMAKE_CXX_STANDARD 14)
add_executable(tan Tan/mail.cpp)
project(untitled6)
target_link_libraries(tan "C:/curl/libcurl.dll.a")
</code>```

Step3: If your program flashes quickly and closes. You might be missing some dll files. To check which ones you are missing , run the program (in my case tan.exe) with cmd. Take that dll from curl package (in my case curl-7.65.0-win64-mingw) and put it along side of your executable file. Make sure curl and your executable is compiled with same compiler. In my case it's Mingw.

Body:
I am trying to use curl inside c++ code. How should i do it properly ?

I have pasted libcurl.a & libcurl.dll.a in this directory:
C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\lib

This is my CMakeLists.txt from CLion/Mingw

cmake_minimum_required(VERSION 3.3)
project(tan)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -lcurl.dll")
add_executable(tan Tan/mail.cpp)
project(untitled6)

When I add "#define CURL_STATICLIB" i get these errors:

reference to `curl_easy_init'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:84: undefined
reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:86: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:91: undefined reference to `curl_slist_append'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:92: undefined reference to `curl_slist_append'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:93: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:98: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:99: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:100: undefined reference to `curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:103: undefined reference to `curl_easy_perform'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:107: undefined reference to `curl_easy_strerror'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:111: undefined reference to `curl_slist_free_all'
C:/Users/John/CLionProjects/tan/Tam/mail.cpp:121: undefined reference to ````curl_easy_cleanup

Without "#define CURL_STATICLIB" i get these errors:

CMakeFiles\tan.dir/objects.a(mail.cpp.obj): In function `main':
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:81: undefined reference to `__imp_curl_easy_init'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:84: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:86: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:91: undefined reference to `__imp_curl_slist_append'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:92: undefined reference to `__imp_curl_slist_append'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:93: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:98: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:99: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:100: undefined reference to `__imp_curl_easy_setopt'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:103: undefined reference to `__imp_curl_easy_perform'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:107: undefined reference to `__imp_curl_easy_strerror'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:111: undefined reference to `__imp_curl_slist_free_all'
C:/Users/John/CLionProjects/tan/Tan/mail.cpp:121: undefined reference to `__imp_curl_easy_cleanup'

Body:
If anybody comes looking use this in CMakeLists.txt. The last line solved the issue.

Step1:
Copy libcurl.dll.a in C:/curl.
No need to copy "libcurl.a" OR "libcurl.dll.a" at any other place.
No need for #define CURL_STATICLIB in main.cpp file

Step2: Edit the CMakeLists.txt as below.

set(CMAKE_CXX_STANDARD 14)
add_executable(tan Tan/mail.cpp)
project(untitled6)
target_link_libraries(tan "C:/curl/libcurl.dll.a")

Step3: If your program flashes quickly and closes. You might be missing some dll files. To check which ones you are missing , run the program (in my case tan.exe) with cmd. Take that dll from curl package (in my case curl-7.65.0-win64-mingw) and put it along side of your executable file. Make sure curl and your executable is compiled with same compiler. In my case it's Mingw.


问:
What happens to local files on iOS when the app is updated?
My iOS app is writing to local files to:

```<code>/var/mobile/Containers/Data/Application/A.../Library/a.txt
</code>```

When my app updates, it gets a new application container ID and folder:

```<code>/var/mobile/Containers/Data/Application/B...
</code>```

What happens to all the files I wrote to container ID A?

Is there an "update hook" that will allow me to copy all the "A" container files to path "B"?

Can the new version of the app (B) read the old versions files (A)?

Is there any documentation around what happens to the filesystem during updates?

Is it possible to recover files from container A after B has been installed?

答:
When you update an app, by changing its version number in the .plist file, iOS creates a new directory for that app with a different hexadecimal name and it copies all the files to the new directories. Now if you are using the absolute paths to get the details of files from the directories then those paths would be incorrect and you won't get the file details.

I just tried this in simulator. I created a function as below which will return the document directory path url

```<code>func getDocumentsDirectory() -> URL {

    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}
</code>```

I called this function from didFinishLaunchingWithOptions in app delegate when version number was 1.0 and it returned the below path :

```<code>file:///Users/BhargavRathod/Library/Developer/CoreSimulator/Devices/3082611F-BCCA-4D17-B390-E0EF4CA454DA/data/Containers/Data/Application/72759097-38F3-4292-825E-1D2343219973/Documents/
</code>```

When I updated the version number to 1.1 it returned me the new path as :

```<code>file:///Users/BhargavRathod/Library/Developer/CoreSimulator/Devices/3082611F-BCCA-4D17-B390-E0EF4CA454DA/data/Containers/Data/Application/72DC31E9-C32F-42CC-8449-F1946ADB1018/Documents/
</code>```

So if you are using a absolute path to access any file from document directory then it is not good practice. You can just save the file name(or relative path after the document directory) and whenever the access to that file name is required then get the file name and append it after the document directory path and access the file.

I hope this will be of some help to you.

Body:
My iOS app is writing to local files to:

/var/mobile/Containers/Data/Application/A.../Library/a.txt

When my app updates, it gets a new application container ID and folder:

/var/mobile/Containers/Data/Application/B...

What happens to all the files I wrote to container ID A?

Is there an "update hook" that will allow me to copy all the "A" container files to path "B"?

Can the new version of the app (B) read the old versions files (A)?

Is there any documentation around what happens to the filesystem during updates?

Is it possible to recover files from container A after B has been installed?

Body:
When you update an app, by changing its version number in the .plist file, iOS creates a new directory for that app with a different hexadecimal name and it copies all the files to the new directories. Now if you are using the absolute paths to get the details of files from the directories then those paths would be incorrect and you won't get the file details.

I just tried this in simulator. I created a function as below which will return the document directory path url

func getDocumentsDirectory() -> URL {

    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

I called this function from didFinishLaunchingWithOptions in app delegate when version number was 1.0 and it returned the below path :

file:///Users/BhargavRathod/Library/Developer/CoreSimulator/Devices/3082611F-BCCA-4D17-B390-E0EF4CA454DA/data/Containers/Data/Application/72759097-38F3-4292-825E-1D2343219973/Documents/

When I updated the version number to 1.1 it returned me the new path as :

file:///Users/BhargavRathod/Library/Developer/CoreSimulator/Devices/3082611F-BCCA-4D17-B390-E0EF4CA454DA/data/Containers/Data/Application/72DC31E9-C32F-42CC-8449-F1946ADB1018/Documents/

So if you are using a absolute path to access any file from document directory then it is not good practice. You can just save the file name(or relative path after the document directory) and whenever the access to that file name is required then get the file name and append it after the document directory path and access the file.

I hope this will be of some help to you.


问:
Read Oracle SYS_REFCURSOR in C# Entity Framework?
I have a simple C# console application and its code is like this:

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            SHRSContext shrsContext = new SHRSContext();

            DbCommand cmd = shrsContext.Database.Connection.CreateCommand();

            cmd.CommandText = "PKG_SHRS.GETLOGINATTEMPT";
            cmd.CommandType = CommandType.StoredProcedure;

            var pinUsername = new OracleParameter("pinUsername", OracleDbType.Varchar2, ParameterDirection.Input);
            pinUsername.Value = "admin";

            var poutLoginAttemptCount = new OracleParameter("poutLoginAttemptCount", OracleDbType.Int16, ParameterDirection.Output);

            cmd.Parameters.Add(pinUsername);
            cmd.Parameters.Add(poutLoginAttemptCount);

            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();

            Console.WriteLine(poutLoginAttemptCount.Value.ToString());
            Console.ReadLine();
        }
    }
}
</code>```

It uses entity framework and Oracle 11g as back-end. It calls a Oracle Procedure in a package PKG_SHRS.GETLOGINATTEMPT and it works perfectly.

The above code just provide a single output parameter as a numeric data type. If I need to get a table SYS_REFCURSOR as output parameter, what do I need to change in the given code?

答:
I assume VALIDATELOGIN procedure's output parameter is poutUserCursor and its type SYS_REFCURSOR. Try this code.

```<code>SHRSContext shrsContext = new SHRSContext();

DbCommand cmd = shrsContext.Database.Connection.CreateCommand();

cmd.CommandText = "PKG_SHRS.GETLOGINATTEMPT";
cmd.CommandType = CommandType.StoredProcedure;

var pinUsername = new OracleParameter("pinUsername", OracleDbType.Varchar2, ParameterDirection.Input);
pinUsername.Value = "admin";

// Assuming output parameter in the procedure is poutUserCursor
var poutUserCursor = new OracleParameter("poutUserCursor", OracleDbType.RefCursor, ParameterDirection.Output);

cmd.Parameters.Add(pinUsername);
cmd.Parameters.Add(poutUserCursor);

cmd.Connection.Open();

DbDataReader dr = cmd.ExecuteReader();

string column1 = string.Empty;
string column2 = string.Empty;

// Assume this will return one row. If multiple rows return, use while loop
if (dr.Read())
{
    // GetString will return string type. You can change as you need
    column1 = dr.GetString(0);
    column2 = dr.GetString(1);
}

cmd.Connection.Close();
</code>```

Body:
I have a simple C# console application and its code is like this:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            SHRSContext shrsContext = new SHRSContext();

            DbCommand cmd = shrsContext.Database.Connection.CreateCommand();

            cmd.CommandText = "PKG_SHRS.GETLOGINATTEMPT";
            cmd.CommandType = CommandType.StoredProcedure;

            var pinUsername = new OracleParameter("pinUsername", OracleDbType.Varchar2, ParameterDirection.Input);
            pinUsername.Value = "admin";

            var poutLoginAttemptCount = new OracleParameter("poutLoginAttemptCount", OracleDbType.Int16, ParameterDirection.Output);

            cmd.Parameters.Add(pinUsername);
            cmd.Parameters.Add(poutLoginAttemptCount);

            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();

            Console.WriteLine(poutLoginAttemptCount.Value.ToString());
            Console.ReadLine();
        }
    }
}

It uses entity framework and Oracle 11g as back-end. It calls a Oracle Procedure in a package PKG_SHRS.GETLOGINATTEMPT and it works perfectly.

The above code just provide a single output parameter as a numeric data type. If I need to get a table SYS_REFCURSOR as output parameter, what do I need to change in the given code?

Body:
I assume VALIDATELOGIN procedure's output parameter is poutUserCursor and its type SYS_REFCURSOR. Try this code.

SHRSContext shrsContext = new SHRSContext();

DbCommand cmd = shrsContext.Database.Connection.CreateCommand();

cmd.CommandText = "PKG_SHRS.GETLOGINATTEMPT";
cmd.CommandType = CommandType.StoredProcedure;

var pinUsername = new OracleParameter("pinUsername", OracleDbType.Varchar2, ParameterDirection.Input);
pinUsername.Value = "admin";

// Assuming output parameter in the procedure is poutUserCursor
var poutUserCursor = new OracleParameter("poutUserCursor", OracleDbType.RefCursor, ParameterDirection.Output);

cmd.Parameters.Add(pinUsername);
cmd.Parameters.Add(poutUserCursor);

cmd.Connection.Open();

DbDataReader dr = cmd.ExecuteReader();

string column1 = string.Empty;
string column2 = string.Empty;

// Assume this will return one row. If multiple rows return, use while loop
if (dr.Read())
{
    // GetString will return string type. You can change as you need
    column1 = dr.GetString(0);
    column2 = dr.GetString(1);
}

cmd.Connection.Close();


问:
galleria jquery plugin slow with lots of images
Has anyone extended the galleria plugin to handle lots of images (over 200)?  The large number of thumbnails makes the initial load take a really long time.</p>

答: You need to use separate thumbnail files and option preload.</p>

ContentLicense: CC BY-SA 3.0


问:
How to disable selecting text in a Python/Tk program?
How would that be done?
I have been unable to find it on here or with Google.</p>

```<code>#Refrences
from tkinter import *

class Interface:

    def __init__(self,stage):

        topLeft = Frame(stage,bg='black')
        test = Entry(topLeft,bg='#2a2a2a',fg='white',insertontime=0)
        test.config(insertbackground='white', exportselection=0)
        test.grid()
        topLeft.grid(row=0,column=0)

def launch():
    window = Tk()
    lobby = Interface(window)
    window.mainloop()

launch()
</code>```

答:
You can set the text highlight color to match the background of entry widget. Note that the text in the widget can still be selected but the user will not see it visually which will give the illusion that selection is disabled.</p>

```<code>test = Entry(topLeft,bg='#2a2a2a',fg='white',insertontime=0)
test.configure(selectbackground=test.cget('bg'), inactiveselectbackground=test.cget('bg'))
</code>```

Body:
How would that be done?
I have been unable to find it on here or with Google.

#Refrences
from tkinter import *

class Interface:

    def __init__(self,stage):

        topLeft = Frame(stage,bg='black')
        test = Entry(topLeft,bg='#2a2a2a',fg='white',insertontime=0)
        test.config(insertbackground='white', exportselection=0)
        test.grid()
        topLeft.grid(row=0,column=0)

def launch():
    window = Tk()
    lobby = Interface(window)
    window.mainloop()

launch()

Body:
You can set the text highlight color to match the background of entry widget. Note that the text in the widget can still be selected but the user will not see it visually which will give the illusion that selection is disabled.

test = Entry(topLeft,bg='#2a2a2a',fg='white',insertontime=0)
test.configure(selectbackground=test.cget('bg'), inactiveselectbackground=test.cget('bg'))


问:
How to show or hide image in HTML
In the following HTML/JS code, if I enter a valid e-mail id a command button and a tick mark should appear. But command button works fine. Tick mark is not appearing. Any one please help.</p>

```<code><html>
<head>

</head>
<body>
<form id="signUpForm">
  <input type="email" id="emailField" required>
  <button id="okButton" style="display:none">OK</button>
  <img id "img1" src="valid.jpg" width=100px style="display:none"/>

</form>

<script>
const signUpForm = document.getElementById('signUpForm');
const emailField = document.getElementById('emailField');
const flag1 = document.getElementById('okButton');
const img1 = document.getElementById('img1');

emailField.addEventListener('keyup', function (event) {
  isValidEmail = emailField.checkValidity();

  if ( isValidEmail ) {
        flag1.style="display:inline";
        img1.style="display:block"";
  } else {
        flag1.style="display:none";
        img1.style="display:none";
 }
});

okButton.addEventListener('click', function (event) {
  signUpForm.submit();
});
</script>

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

答:
```<code><html>
<head>

</head>
<body>
<form id="signUpForm">
  <input type="email" id="emailField" required>
  <button id="okButton" style="display:none">OK</button>
  <!-- fixed: id "img1" -> id="img1", width=100px -> width="100px" -->
  <img id="img1" src="valid.jpg" width="100px" style="display:none"/>

</form>

<script>
const signUpForm = document.getElementById('signUpForm');
const emailField = document.getElementById('emailField');
const flag1 = document.getElementById('okButton');
const img1 = document.getElementById('img1');

emailField.addEventListener('keyup', function (event) {
  isValidEmail = emailField.checkValidity();

  if ( isValidEmail ) {
        flag1.style="display:inline";
        img1.style="display:block"; //removed 3rd double quote
  } else {
        flag1.style="display:none";
        img1.style="display:none";
 }
});

okButton.addEventListener('click', function (event) {
  signUpForm.submit();
});
</script>

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

Title: How to show or hide image in HTML

Body:
In the following HTML/JS code, if I enter a valid e-mail id a command button and a tick mark should appear. But command button works fine. Tick mark is not appearing. Any one please help.

<form id="signUpForm">
  <input type="email" id="emailField" required>
  <button id="okButton" style="display:none">OK</button>

</form>


问:
ActiveModel::Serializers embed: :ids, include: true not sideloading data
I'm running a Rails 4.2 - AMS 0.9 app, and I have (for illustrative purposes) 3 models: Foo has_one Bar, has_many Bazes. I am only getting the ids in the response, and not the sideloaded items. Is there a config option, or something I've missed?

My AMS class is:

```<code>class FooSerializer < ActiveModel::Serializer
   embed :ids, include: true
   has_one :bar, key: :bar    ## For ember-data; it doesn't like "_id"
   has_many :bazes, key: :bazes

   attributes :id, :etc

end
</code>```

There're quite a few topics on AMS throughout StackOverflow, and I read many before posting, but this has just left me totally stumped.

答:
@Ted's answer worked for me on arrays, but when I tried to serialize in a show method, I couldn't use AciveModel::ArraySerializer of course. While researching why Ted's answer worked, I came across this little line in the AMS documentatiopn

When controller does not inherit from ActionController::Base, include Serialization module manually

```<code>class ApplicationController < ActionController::API
  include ActionController::Serialization
end
</code>```

link: https://github.com/rails-api/active_model_serializers/tree/0-9-stable#use-serialization-outside-of-actioncontrollerbase

Since my rails app is api only, this was what I needed.

Body:
I'm running a Rails 4.2 - AMS 0.9 app, and I have (for illustrative purposes) 3 models: Foo has_one Bar, has_many Bazes. I am only getting the ids in the response, and not the sideloaded items. Is there a config option, or something I've missed?

My AMS class is:

class FooSerializer < ActiveModel::Serializer
   embed :ids, include: true
   has_one :bar, key: :bar    ## For ember-data; it doesn't like "_id"
   has_many :bazes, key: :bazes

   attributes :id, :etc

end

There're quite a few topics on AMS throughout StackOverflow, and I read many before posting, but this has just left me totally stumped.

Body:
@Ted's answer worked for me on arrays, but when I tried to serialize in a show method, I couldn't use AciveModel::ArraySerializer of course. While researching why Ted's answer worked, I came across this little line in the AMS documentatiopn

When controller does not inherit from ActionController::Base, include Serialization module manually

class ApplicationController < ActionController::API
  include ActionController::Serialization
end

link: https://github.com/rails-api/active_model_serializers/tree/0-9-stable#use-serialization-outside-of-actioncontrollerbase

Since my rails app is api only, this was what I needed.


问:
R: ggplot2 histogram fill dodge - prevent partial overlap
I'm trying to plot a histogram with ggplot2 comparing 2 periods of time. I want the bars to dodge (i.e. plot side-by-side) and not stack. I've tried this:

```<code>qplot(region, data = data, fill = month) +
  labs(y = "Sales", fill = "") +
  geom_bar(position = "dodge")
</code>```

The dodge partially works but I'm still getting overlap:

How can I get the bars to position side-by-side properly?

Update

Output of dput(head(data, 20)) as requested by @RuiBarradas in the comments:

```<code>structure(list(month = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("May 2018",
"May 2019 (so far)"), class = "factor"), region = structure(c(5L,
6L, 6L, 5L, 5L, 4L, 6L, 6L, 4L, 5L, 6L, 5L, 6L, 6L, 5L, 4L, 5L,
5L, 6L, 6L), .Label = c("Abbotsford", "Agassiz", "Bowen Island",
"Burnaby East", "Burnaby North", "Burnaby South", "Chilliwack",
"Cloverdale", "Coquitlam", "Cultus Lake", "Harrison Hot Springs",
"Hope", "Islands-Van. & Gulf", "Ladner", "Langley", "Maple Ridge",
"Mission", "N. Delta", "New Westminster", "North Surrey", "North Vancouver",
"Pemberton", "Pitt Meadows", "Port Coquitlam", "Port Moody",
"Richmond", "Rosedale", "Sardis", "South Surrey White Rock",
"Squamish", "Sunshine Coast", "Surrey", "Tsawwassen", "Vancouver East",
"Vancouver West", "West Vancouver", "Whistler", "Yarrow", "Harrison Mills / Mt Woodside"
), class = "factor")), row.names = c(NA, 20L), class = "data.frame")
</code>```

答:
Apparently it is a qplot error, that can be reproduced with the data in the OP's link and the question's code.

```<code>library(ggplot2)

qplot(region, data = data, fill = month) +
  labs(y = "Sales") +
  geom_bar(position = position_dodge())
</code>```

But with ggplot everything works as expected.

```<code>ggplot(data, aes(x = region, fill = month)) +
  geom_bar(position = position_dodge()) +
  theme(axis.text.x = element_text(angle=90, hjust=1)) +
  labs(y = "Sales")
</code>```

Body:
I'm trying to plot a histogram with ggplot2 comparing 2 periods of time. I want the bars to dodge (i.e. plot side-by-side) and not stack. I've tried this:

qplot(region, data = data, fill = month) +
  labs(y = "Sales", fill = "") +
  geom_bar(position = "dodge")

The dodge partially works but I'm still getting overlap:

How can I get the bars to position side-by-side properly?

Update

Output of dput(head(data, 20)) as requested by @RuiBarradas in the comments:

structure(list(month = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("May 2018",
"May 2019 (so far)"), class = "factor"), region = structure(c(5L,
6L, 6L, 5L, 5L, 4L, 6L, 6L, 4L, 5L, 6L, 5L, 6L, 6L, 5L, 4L, 5L,
5L, 6L, 6L), .Label = c("Abbotsford", "Agassiz", "Bowen Island",
"Burnaby East", "Burnaby North", "Burnaby South", "Chilliwack",
"Cloverdale", "Coquitlam", "Cultus Lake", "Harrison Hot Springs",
"Hope", "Islands-Van. & Gulf", "Ladner", "Langley", "Maple Ridge",
"Mission", "N. Delta", "New Westminster", "North Surrey", "North Vancouver",
"Pemberton", "Pitt Meadows", "Port Coquitlam", "Port Moody",
"Richmond", "Rosedale", "Sardis", "South Surrey White Rock",
"Squamish", "Sunshine Coast", "Surrey", "Tsawwassen", "Vancouver East",
"Vancouver West", "West Vancouver", "Whistler", "Yarrow", "Harrison Mills / Mt Woodside"
), class = "factor")), row.names = c(NA, 20L), class = "data.frame")

Body:
Apparently it is a qplot error, that can be reproduced with the data in the OP's link and the question's code.

library(ggplot2)

qplot(region, data = data, fill = month) +
  labs(y = "Sales") +
  geom_bar(position = position_dodge())

But with ggplot everything works as expected.

ggplot(data, aes(x = region, fill = month)) +
  geom_bar(position = position_dodge()) +
  theme(axis.text.x = element_text(angle=90, hjust=1)) +
  labs(y = "Sales")


问:
Exporting custom ES6 module and importing into another local project is always undefined or {}, in TypeScript
I'm working with TypeScript 3.4.5 and Webpack 4.32.2 on Windows 10 through WSL.

I'm trying to create a local package of tools, which aggregates basic classes into an index file, where I export them. No matter how I export or import in the other projects, the imported classes are always either 'undefined' or an empty object '{}'.

I tried to both npm link this 'api-tools' package to another local project, and I also tried to just install it through package.json's file dependency method, ie: { "api-tools": "file:../api-tools" }, and in both scenarios the result is the same.

Here is the api-tools package's index file:

index.ts:

```<code>import RestAPI from './lib/RestAPI';
export { RestAPI };
</code>```

Here is the RestAPI library:

lib/RestAPI.ts:

```<code>export default class RestAPI {
    handle(req, res) {}
}
</code>```

In the consuming project, I am importing it like this:

```<code>import { RestAPI } from 'api-tools';
console.log(RestAPI);
</code>```

but logging this object to the console shows it is undefined.

I've tried different syntaxes of exporting and importing, ie.:

```<code>// RestAPI.ts:
export class RestAPI {
    handle() {}
}

// index.ts:
import { RestAPI } from './lib/RestAPI';
console.log(RestAPI);

exports = {
    RestAPI: RestAPI
}
// also tried module.exports = {...}
</code>```

Putting this console.log here shows that the exported RestAPI is defined correctly, with all of its properties. From here I try using it on the consuming projects in different ways:

```<code>// both give empty object {}
import * as RestAPI from 'api-tools';
import RestAPI from 'api-tools';

// gives undefined
import { RestAPI } from 'api-tools';

console.log(RestAPI);
</code>```

These always give an empty object, otherwise it is undefined.

Could this just be a TypeScript/typings thing? Everything builds fine and the paths of the projects seem fine, both to the compiled index.js, and the index.d.ts types file that api-tools package.json defines.

package.json:

```<code>{
  "main": "build/index.js",
  "types": "build/src/index.d.ts",
}
</code>```

tsconfig.json:

```<code>{
    "compilerOptions": {
        "declaration": true,
        "incremental": true,
        "baseUrl": "./",
        "outDir": "build",
        "module": "es6",            // specifiy module code generation
        "moduleResolution": "node",
        "target": "es6",         // specify ECMAScript target version
        "strict": true,
        "resolveJsonModule": true
    },
    "types": [ "webpack-env", "node" ]
}
</code>```

Could it possibly be some issue with doing this through WSL? Or Webpack even?

I also tried to publish the package to npm, and import it through the normal process of npm install, but same thing happens, which makes me think it might be something with my configuration or understanding of modules.

Thanks for any help, been trying to figure this out for too long :-].

答:
Figured it out. Webpack doesn't handle exports by default, have to set it in the output config:</p>

```<code>output: {
    library: 'api-tools',
    libraryTarget: 'umd'
},
</code>```

Body:
I'm working with TypeScript 3.4.5 and Webpack 4.32.2 on Windows 10 through WSL.

I'm trying to create a local package of tools, which aggregates basic classes into an index file, where I export them. No matter how I export or import in the other projects, the imported classes are always either 'undefined' or an empty object '{}'.

I tried to both npm link this 'api-tools' package to another local project, and I also tried to just install it through package.json's file dependency method, ie: { "api-tools": "file:../api-tools" }, and in both scenarios the result is the same.

Here is the api-tools package's index file:

index.ts:

import RestAPI from './lib/RestAPI';
export { RestAPI };

Here is the RestAPI library:

lib/RestAPI.ts:

export default class RestAPI {
    handle(req, res) {}
}

In the consuming project, I am importing it like this:

import { RestAPI } from 'api-tools';
console.log(RestAPI);

but logging this object to the console shows it is undefined.

I've tried different syntaxes of exporting and importing, ie.:

// RestAPI.ts:
export class RestAPI {
    handle() {}
}

// index.ts:
import { RestAPI } from './lib/RestAPI';
console.log(RestAPI);

exports = {
    RestAPI: RestAPI
}
// also tried module.exports = {...}

Putting this console.log here shows that the exported RestAPI is defined correctly, with all of its properties. From here I try using it on the consuming projects in different ways:

// both give empty object {}
import * as RestAPI from 'api-tools';
import RestAPI from 'api-tools';

// gives undefined
import { RestAPI } from 'api-tools';

console.log(RestAPI);

These always give an empty object, otherwise it is undefined.

Could this just be a TypeScript/typings thing? Everything builds fine and the paths of the projects seem fine, both to the compiled index.js, and the index.d.ts types file that api-tools package.json defines.

package.json:

{
  "main": "build/index.js",
  "types": "build/src/index.d.ts",
}

tsconfig.json:

{
    "compilerOptions": {
        "declaration": true,
        "incremental": true,
        "baseUrl": "./",
        "outDir": "build",
        "module": "es6",            // specifiy module code generation
        "moduleResolution": "node",
        "target": "es6",         // specify ECMAScript target version
        "strict": true,
        "resolveJsonModule": true
    },
    "types": [ "webpack-env", "node" ]
}

Could it possibly be some issue with doing this through WSL? Or Webpack even?

I also tried to publish the package to npm, and import it through the normal process of npm install, but same thing happens, which makes me think it might be something with my configuration or understanding of modules.

Thanks for any help, been trying to figure this out for too long :-].

Body:
Figured it out. Webpack doesn't handle exports by default, have to set it in the output config:

output: {
    library: 'api-tools',
    libraryTarget: 'umd'
},


问:
Autofield column is not showing in admin database
i have created a model Post

```<code>class Post(models.Model):
  id = models.AutoField(primary_key=True)
  title = models.CharField(max_length=100)
  image = models.ImageField(upload_to='blog_image', default='default.jpg')
  smallContent = models.TextField()
  content = models.TextField()
  data_posted = models.DateTimeField(default=timezone.now)
  author = models.ForeignKey(User, on_delete=models.CASCADE)

  def __str__(self):
     return self.title
</code>```

but id field is not showing in admin panel. i did makemigrations and migrate and both are done successfully.

答:
Since it is a readonly field I think you probably need to explicitly tell admin to show it.

I don't know if this will work but try in admin.py

```<code>from django.contrib import admin
from .models import Post

class PostAdmin(admin.ModelAdmin):
    readonly_fields = ['display_id']

    def display_id(self, obj):
        return obj.id

admin.site.register(Post, PostAdmin)
</code>```

Body:
i have created a model Post

class Post(models.Model):
  id = models.AutoField(primary_key=True)
  title = models.CharField(max_length=100)
  image = models.ImageField(upload_to='blog_image', default='default.jpg')
  smallContent = models.TextField()
  content = models.TextField()
  data_posted = models.DateTimeField(default=timezone.now)
  author = models.ForeignKey(User, on_delete=models.CASCADE)

  def __str__(self):
     return self.title

but id field is not showing in admin panel. i did makemigrations and migrate and both are done successfully.

Body:
Since it is a readonly field I think you probably need to explicitly tell admin to show it.

I don't know if this will work but try in admin.py

from django.contrib import admin
from .models import Post

class PostAdmin(admin.ModelAdmin):
    readonly_fields = ['display_id']

    def display_id(self, obj):
        return obj.id

admin.site.register(Post, PostAdmin)


问:
Protractor typescript issue while checking value from select menu
I am automating by using protractor typescript I am facing issue while selecting specific value from select menu, please see the screenshot

```<code><div class="pq-select-menu">
<label class="pq-select-option-label ui-state-enable" id="pq-option-565-0">
<input type="checkbox"><span class="pq-left-input">Application Administrators(1001)</span></label>
<label class="pq-select-option-label ui-state-enable pq-state-hover" id="pq-option-565-1">
<input type="checkbox"><span class="pq-left-input">Power Users(1002)</span></label>
<label class="pq-select-option-label ui-state-enable" id="pq-option-565-2">
<input type="checkbox"><span class="pq-left-input">Users(1003)</span></label>
<label class="pq-select-option-label ui-state-enable" id="pq-option-565-3">
<input type="checkbox"><span class="pq-left-input">automationGroup(1005)</span></label>
<label class="pq-select-option-label ui-state-enable" id="pq-option-565-4">
<input type="checkbox"><span class="pq-left-input">TestGroup2(1024)</span></label>
</div>
</code>```

After clicking on select menu by
element(by.xpath('.//td[@data-container-for="groups"]//div[@class="pq-select-text"]')).click(); enter code here
How I can select and to check if that value is checked or not.

答:
You can take advantage of xpath axes. They let you easily find elements relative to one another.

In this case you would identify the span tag using the text and find the preceding input within the same label

```<code>let inputEle = element(by.xpath('//div[@class="pq-select-menu"]//span[text()="Users(1003)"]/preceding-sibling::input'))

console.log(await inputEle.isSelected()) //should return true or false
</code>```

Body:
I am automating by using protractor typescript I am facing issue while selecting specific value from select menu, please see the screenshot

<input type="checkbox">Application Administrators(1001)

<input type="checkbox">Power Users(1002)

<input type="checkbox">Users(1003)

<input type="checkbox">automationGroup(1005)

<input type="checkbox">TestGroup2(1024)

After clicking on select menu by
element(by.xpath('.//td[@data-container-for="groups"]//div[@class="pq-select-text"]')).click(); enter code here
How I can select and to check if that value is checked or not.

Body:
You can take advantage of xpath axes. They let you easily find elements relative to one another.

In this case you would identify the span tag using the text and find the preceding input within the same label

let inputEle = element(by.xpath('//div[@class="pq-select-menu"]//span[text()="Users(1003)"]/preceding-sibling::input'))

console.log(await inputEle.isSelected()) //should return true or false


问:
How to make the three images apear inline?
 Chevy Camaro MSRP: From $25,000 Horsepower: 275 to 650 hp MPG: Up to 22 city / 31 highway Curb weight: 3,354 to 4,113 lbs Engine: 2.0 L 4-cylinder, 3.6 L V6, 6.2 L V8 And if you want the convertible version you pay $35000+

```<code>         <div class="links"><a> <img src="mustang.jpg" width="200" height="150"white-space= "nowrap"><span> Ford Mustang MSRP: From $26,395
                    Horsepower: 310 to 480 hp
                    MPG: Up to 21 city / 32 highway
                    Curb weight: 3,532 to 3,825 lbs
                    Engine: 2.3 L 4-cylinder, 5.0 L V8
                    For the convisrtable version the price starts at $31000</span></a>

             </div>
        <div class="links"> <a> <img src="challenger.jpg" width="200" height="150"white-space= "nowrap"><span>Dodge Challenger MSRP: From $27,845
                    Horsepower: 305 to 797 hp
                    MPG: Up to 19 city / 30 highway
                    Curb weight: 3,894 to 4,448 lbs
                    Engine: 3.6 L V6, 5.7 L V8, 6.2 L V8, 6.4 L V8
                    There are other models of this specific car, and the price can go as high as $37000</span></a>
             </div>
</code>```

答:
.column {
  float: left;
  width: 33.33%;
  padding: 5px;
}

/* Clearfix (clear floats) */
.row::after {
  content: "";
  clear: both;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="row">
 <div class="column"  ><a> <img src="mustang.jpg" width=100% white-space= "nowrap"><span> Ford Mustang MSRP: From $26,395
                    Horsepower: 310 to 480 hp
                    MPG: Up to 21 city / 32 highway
                    Curb weight: 3,532 to 3,825 lbs
                    Engine: 2.3 L 4-cylinder, 5.0 L V8
                    For the convisrtable version the price starts at $31000</span></a>

             </div>
        <div class="column"> <a> <img src="challenger.jpg" width=100% white-space= "nowrap"><span>Dodge Challenger MSRP: From $27,845
                    Horsepower: 305 to 797 hp
                    MPG: Up to 19 city / 30 highway
                    Curb weight: 3,894 to 4,448 lbs
                    Engine: 3.6 L V6, 5.7 L V8, 6.2 L V8, 6.4 L V8
                    There are other models of this specific car, and the price can go as high as $37000</span></a>
             </div>
             <div class="column"> <a> <img src="challenger.jpg" width=100% white-space= "nowrap"><span>Dodge Challenger MSRP: From $27,845
                    Horsepower: 305 to 797 hp
                    MPG: Up to 19 city / 30 highway
                    Curb weight: 3,894 to 4,448 lbs
                    Engine: 3.6 L V6, 5.7 L V8, 6.2 L V8, 6.4 L V8
                    There are other models of this specific car, and the price can go as high as $37000</span></a>
             </div>
             </div></code>```

Body:
Chevy Camaro MSRP: From $25,000 Horsepower: 275 to 650 hp MPG: Up to 22 city / 31 highway Curb weight: 3,354 to 4,113 lbs Engine: 2.0 L 4-cylinder, 3.6 L V6, 6.2 L V8 And if you want the convertible version you pay $35000+

  Ford Mustang MSRP: From $26,395
                    Horsepower: 310 to 480 hp
                    MPG: Up to 21 city / 32 highway
                    Curb weight: 3,532 to 3,825 lbs
                    Engine: 2.3 L 4-cylinder, 5.0 L V8
                    For the convisrtable version the price starts at $31000

  Dodge Challenger MSRP: From $27,845
                    Horsepower: 305 to 797 hp
                    MPG: Up to 19 city / 30 highway
                    Curb weight: 3,894 to 4,448 lbs
                    Engine: 3.6 L V6, 5.7 L V8, 6.2 L V8, 6.4 L V8
                    There are other models of this specific car, and the price can go as high as $37000

Body:
.column {
  float: left;
  width: 33.33%;
  padding: 5px;
}

/* Clearfix (clear floats) */
.row::after {
  content: "";
  clear: both;
  display: table;
}

 <div class="row">
 <div class="column"  ><a> <img src="mustang.jpg" width=100% white-space= "nowrap"><span> Ford Mustang MSRP: From $26,395
                    Horsepower: 310 to 480 hp
                    MPG: Up to 21 city / 32 highway
                    Curb weight: 3,532 to 3,825 lbs
                    Engine: 2.3 L 4-cylinder, 5.0 L V8
                    For the convisrtable version the price starts at $31000</span></a>

             </div>
        <div class="column"> <a> <img src="challenger.jpg" width=100% white-space= "nowrap"><span>Dodge Challenger MSRP: From $27,845
                    Horsepower: 305 to 797 hp
                    MPG: Up to 19 city / 30 highway
                    Curb weight: 3,894 to 4,448 lbs
                    Engine: 3.6 L V6, 5.7 L V8, 6.2 L V8, 6.4 L V8
                    There are other models of this specific car, and the price can go as high as $37000</span></a>
             </div>
             <div class="column"> <a> <img src="challenger.jpg" width=100% white-space= "nowrap"><span>Dodge Challenger MSRP: From $27,845
                    Horsepower: 305 to 797 hp
                    MPG: Up to 19 city / 30 highway
                    Curb weight: 3,894 to 4,448 lbs
                    Engine: 3.6 L V6, 5.7 L V8, 6.2 L V8, 6.4 L V8
                    There are other models of this specific car, and the price can go as high as $37000</span></a>
             </div>
             </div>


问:
Android Launcher app icon not updated to new icon after market update
I have provided an update for my application via Android market.
After new application installed from market, my app icon alone has not changed to the new app icon in the Android Launcher screen.

However, if the mobile restarted once, the new icon is reflected in Launcher screen too. It looks like my old app icon cached in Android Launcher.

What could be an issue? Is that a bug with Android or am I missing something?

答:
I also faced this problem, because of roundIcon configuration. So please make sure, you have updated both icon and roundIcon.

Android uses either of the icons based on the device configuration. Hence we should be defining both kinds of icons

https://developer.android.com/about/versions/nougat/android-7.1#circular-icons


问:
Docker image error: "/bin/sh: 1: [python,: not found"
I'm building a new Docker image based on the standard Ubuntu 14.04 image.

Here's my Dockerfile:

```<code>FROM ubuntu:14.04
RUN apt-get update -y
RUN apt-get install -y nginx git python-setuptools python-dev
RUN easy_install pip
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt # only 'django' for now
ENV projectname myproject
EXPOSE 80 8000
WORKDIR ${projectname}
CMD ['python', 'manage.py', 'runserver', '0.0.0.0:80']
</code>```

When I try to run this image, I get this error...

/bin/sh: 1: [python,: not found

But if I open a shell when running the image, running python opens the interactive prompt as expected.

Why can't I invoke python through CMD in the Dockerfile?

答:
I had the same error. But in my case it was syntax error in command.

I had a missing comma ","

CMD ["python" "app.py"]

instead of

CMD ["python", "app.py"]

Validating the yaml file format can help in this case. Can use any online yaml validator.

Body:
I'm building a new Docker image based on the standard Ubuntu 14.04 image.

Here's my Dockerfile:

FROM ubuntu:14.04
RUN apt-get update -y
RUN apt-get install -y nginx git python-setuptools python-dev
RUN easy_install pip
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt # only 'django' for now
ENV projectname myproject
EXPOSE 80 8000
WORKDIR ${projectname}
CMD ['python', 'manage.py', 'runserver', '0.0.0.0:80']

When I try to run this image, I get this error...

/bin/sh: 1: [python,: not found

But if I open a shell when running the image, running python opens the interactive prompt as expected.

Why can't I invoke python through CMD in the Dockerfile?


问:
PHP - Identifying Individual Users Under Same Router (main IP address)
Is it possible to find the IP address of (or otherwise identify) each user on the same "router" or "main IP address"?

Update, clarifying question:

Use-case:
I'd like to be able to track whether each of N individual computer users on a possibly common network has landed on a page.

Currently, using other PHP IP detect snippets on S/O, this seems to only identify all N individual computers on the network as coming from the same IP address. This does not help solve the problem of identifying whether these come from different users on the same network, or if it's the same user on the network hitting the page several times.

--

Note: cookies are likely disabled.

答:
This might not have been true 4 years ago when this question was first asked. But now most of the internet has an IPv6 address. I know most people currently also have an IPv4 address as well. I would check the connection by the IPv6 address. With IPv6 addresses each machine is supposed to get a different IP address even though it is on the same network.

Use this code to verify you are working with an IPv6 address. And if you are, different devices should have different IP addresses.

```<code><?php
//whether ip is from share internet
if (!empty($_SERVER['HTTP_CLIENT_IP']))
  {
    $ip_address = $_SERVER['HTTP_CLIENT_IP'];
  }
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
  {
    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
  }
//whether ip is from remote address
else
  {
    $ip_address = $_SERVER['REMOTE_ADDR'];
  }
$ip_address = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";

// Validate ip as IPv6
if (filter_var($ip_address , FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
    echo("$ip_address is a valid IPv6 address");
} else {
    echo("$ip_address is not a valid IPv6 address");
}
?>
</code>```

Body:
This might not have been true 4 years ago when this question was first asked. But now most of the internet has an IPv6 address. I know most people currently also have an IPv4 address as well. I would check the connection by the IPv6 address. With IPv6 addresses each machine is supposed to get a different IP address even though it is on the same network.

Use this code to verify you are working with an IPv6 address. And if you are, different devices should have different IP addresses.

<?php
//whether ip is from share internet
if (!empty($_SERVER['HTTP_CLIENT_IP']))
  {
    $ip_address = $_SERVER['HTTP_CLIENT_IP'];
  }
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
  {
    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
  }
//whether ip is from remote address
else
  {
    $ip_address = $_SERVER['REMOTE_ADDR'];
  }
$ip_address = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";

// Validate ip as IPv6
if (filter_var($ip_address , FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
    echo("$ip_address is a valid IPv6 address");
} else {
    echo("$ip_address is not a valid IPv6 address");
}
?>


问:
What is the use of binding adapter in Android?
I have been reading articles about binding adapter in Android,  but I don't seem to understand it.
When is a binding adapter used?
Can someone explain it with a simple example?

An article I read had a binding adapter in the Main Activity.  The binding Adapter had a parameter "toastMessage",  and apparently,  the method annotated with this binding adapter was said to be called whenever the "toastMessage" (which was an attribute in viewModel class)  changed.

I don't understand why we need to do this.

An explanation with a simple example would help a lot.

Thanks!

答:
Binding adapters are responsible for making the appropriate framework calls to set values.

When you're using data binding into your application, setting values into your views is a normal thing. Like below example:

```<code> <ProgressBar
         app:layout_constraintLeft_toLeftOf="parent"
         app:layout_constraintRight_toRightOf="parent"
         app:layout_constraintTop_toTopOf="parent"
         app:layout_constraintBottom_toBottomOf="parent"
         android:visibility="@{viewmodel.loadingData?View.VISIBLE:View.GONE}"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
</code>```

But some times you want to do something special in your setting methods. For example, you have a RecyclerView in your XML and you want to define its adapter, You can do it by defining it via a bindingAdapter in your code for it.

```<code><android.support.v7.widget.RecyclerView
            android:id="@+id/rv_main_articles"
            app:adapter="@{viewmodel.articles}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_width="0dp"
            android:layout_height="0dp"/>
</code>```

There are mostly two usages of binding adapters:

1- For RecyclerView:

```<code>@JvmStatic
        @BindingAdapter("app:adapter")
        fun <T> setItems(recyclerView: RecyclerView, items: List<T>?) {

            Log.d(TAG, "articles:[$items]")

            if (recyclerView.adapter is HomeAdapter) {

                if (items != null) {
                    (recyclerView.adapter as HomeAdapter).swapData(items)
                }

            }
        }
</code>```

2- For loading images into your ImageView(s)

```<code>@JvmStatic
        @BindingAdapter("app:loadImage")
        fun setImageResource(view: ImageView, imageUrl: String?) {

            val context = view.context

            val options = RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)

            imageUrl?.let {

                Glide.with(context)
                    .setDefaultRequestOptions(options)
                    .load(imageUrl)
                    .transition(DrawableTransitionOptions.withCrossFade(1000))
                    .into(view)
            }
        }
</code>```

More info : link

Body:
Binding adapters are responsible for making the appropriate framework calls to set values.

When you're using data binding into your application, setting values into your views is a normal thing. Like below example:

 <ProgressBar
         app:layout_constraintLeft_toLeftOf="parent"
         app:layout_constraintRight_toRightOf="parent"
         app:layout_constraintTop_toTopOf="parent"
         app:layout_constraintBottom_toBottomOf="parent"
         android:visibility="@{viewmodel.loadingData?View.VISIBLE:View.GONE}"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>

But some times you want to do something special in your setting methods. For example, you have a RecyclerView in your XML and you want to define its adapter, You can do it by defining it via a bindingAdapter in your code for it.

<android.support.v7.widget.RecyclerView
            android:id="@+id/rv_main_articles"
            app:adapter="@{viewmodel.articles}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_width="0dp"
            android:layout_height="0dp"/>

There are mostly two usages of binding adapters:

1- For RecyclerView:

@JvmStatic
        @BindingAdapter("app:adapter")
        fun <T> setItems(recyclerView: RecyclerView, items: List<T>?) {

            Log.d(TAG, "articles:[$items]")

            if (recyclerView.adapter is HomeAdapter) {

                if (items != null) {
                    (recyclerView.adapter as HomeAdapter).swapData(items)
                }

            }
        }

2- For loading images into your ImageView(s)

@JvmStatic
        @BindingAdapter("app:loadImage")
        fun setImageResource(view: ImageView, imageUrl: String?) {

            val context = view.context

            val options = RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)

            imageUrl?.let {

                Glide.with(context)
                    .setDefaultRequestOptions(options)
                    .load(imageUrl)
                    .transition(DrawableTransitionOptions.withCrossFade(1000))
                    .into(view)
            }
        }

More info : link


答:
AutoField is generated after the model is saved. It is not provided in Admin Panel as it should not be editable.

If want to make id editable (not recommended) override it as a CharField instead of AutoField with primary_key=True.

Else if just want to show it in the panel (while editing a saved model), add it to the read_only list of your model admin.

Read about AutoField here.

Title: Autofield column is not showing in admin database


问:
How to Center ListView?
I have Column but issue is if screen very small height there is error:

BOTTOM OVERFLOWED BY 5.0 PIXELS

```<code>Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        CenterBoxText(),
                        SizedBox(height: 1),
                        RaisedButton(
                          child: Text(‘Example’),
                        ),
                      ],
                    ),
</code>```

I have try replace Column with ListView and this stop error. But now on large screen Widget are display from top and not in center. Because ListView no have mainAxisAlignment: MainAxisAlignment.center.

How to solve?

Thanks!

答:
Try wrapping your Column widget with SingleChildScrollView widget, It will provide the ability to scroll.
Like this :

```<code> SingleChildScrollView(
              child: Column(
                       mainAxisAlignment: MainAxisAlignment.center,
                       children: <Widget>[
                         CenterBoxText(),
                         SizedBox(height: 1),
                         RaisedButton(
                           child: Text(‘Example’),
                         ),
                       ],
                     ),
                    ),
</code>```

Title: How to Center ListView?

Body:
I have Column but issue is if screen very small height there is error:

BOTTOM OVERFLOWED BY 5.0 PIXELS

Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        CenterBoxText(),
                        SizedBox(height: 1),
                        RaisedButton(
                          child: Text(‘Example’),
                        ),
                      ],
                    ),

I have try replace Column with ListView and this stop error. But now on large screen Widget are display from top and not in center. Because ListView no have mainAxisAlignment: MainAxisAlignment.center.

How to solve?

Thanks!

Body:
Try wrapping your Column widget with SingleChildScrollView widget, It will provide the ability to scroll.
Like this :

 SingleChildScrollView(
              child: Column(
                       mainAxisAlignment: MainAxisAlignment.center,
                       children: <Widget>[
                         CenterBoxText(),
                         SizedBox(height: 1),
                         RaisedButton(
                           child: Text(‘Example’),
                         ),
                       ],
                     ),
                    ),


问:
Comparison with the previous line and summation
There is a table in dataframe:

```<code>X1  X2
1   1
1   2
1   3
2   2
2   2
1   2
</code>```

It is necessary for each line calculate the value Y, where Y = X2(previous line)+1 if X1=X1(previous line), elso 0. Result:

```<code>X1  X2  Y
1   1   0
1   2   2
1   3   3
2   2   0
2   2   3
1   2   0
</code>```

答:
I use groupby on groups of unchanged X1. On each group, doing  shift on X2 to add 1 to it. Finally, fillna on changed values of X1

```<code>df['Y'] = df.groupby(df.X1.ne(df.X1.shift()).cumsum()).X2.shift().add(1).fillna(0)

Out[569]:
   X1  X2    Y
0   1   1  0.0
1   1   2  2.0
2   1   3  3.0
3   2   2  0.0
4   2   2  3.0
5   1   2  0.0
</code>```

Body:
There is a table in dataframe:

X1  X2
1   1
1   2
1   3
2   2
2   2
1   2

It is necessary for each line calculate the value Y, where Y = X2(previous line)+1 if X1=X1(previous line), elso 0. Result:

X1  X2  Y
1   1   0
1   2   2
1   3   3
2   2   0
2   2   3
1   2   0

Body:
I use groupby on groups of unchanged X1. On each group, doing  shift on X2 to add 1 to it. Finally, fillna on changed values of X1

df['Y'] = df.groupby(df.X1.ne(df.X1.shift()).cumsum()).X2.shift().add(1).fillna(0)

Out[569]:
   X1  X2    Y
0   1   1  0.0
1   1   2  2.0
2   1   3  3.0
3   2   2  0.0
4   2   2  3.0
5   1   2  0.0


问:
Trying to Remove any non-numbers from an Array
I am trying to get user input and then put this into an array, however, if the user puts in an element that is not a number how can I remove this? I can make an error message show up however the element still goes into the array.</p>

```<code>      var input_array = [];

      var number = prompt('Enter a Number');
      if (isNaN(number)) {
        alert("Please Enter a Number");
      }
      var array = input_array.push(parseInt(number));
</code>```

答:
This is a neat way of doing it using the ternary operator. Only add the input to array if it is a number.

```<code>var input_array = [];
var number = prompt('Enter a Number');
isNaN(number) ? alert('Please Enter a number'): input_array.push(number);

</code>```

Also prompt returns a string, so if you want your array to contain only numbers. Use parseInt when reading input

```<code>var number = parseInt(prompt('Enter a Number'));
</code>```

Body:
I am trying to get user input and then put this into an array, however, if the user puts in an element that is not a number how can I remove this? I can make an error message show up however the element still goes into the array.

      var input_array = [];

      var number = prompt('Enter a Number');
      if (isNaN(number)) {
        alert("Please Enter a Number");
      }
      var array = input_array.push(parseInt(number));

Body:
This is a neat way of doing it using the ternary operator. Only add the input to array if it is a number.

var input_array = [];
var number = prompt('Enter a Number');
isNaN(number) ? alert('Please Enter a number'): input_array.push(number);

Also prompt returns a string, so if you want your array to contain only numbers. Use parseInt when reading input

var number = parseInt(prompt('Enter a Number'));


问:
What happens to local files on iOS when the app is updated?
My iOS app is writing to local files to:

```<code>/var/mobile/Containers/Data/Application/A.../Library/a.txt
</code>```

When my app updates, it gets a new application container ID and folder:

```<code>/var/mobile/Containers/Data/Application/B...
</code>```

What happens to all the files I wrote to container ID A?

Is there an "update hook" that will allow me to copy all the "A" container files to path "B"?

Can the new version of the app (B) read the old versions files (A)?

Is there any documentation around what happens to the filesystem during updates?

Is it possible to recover files from container A after B has been installed?

答:
My iOS app is writing to local files to: /var/mobile/Containers/Data/Application/A.../Library/a.txt

Okay, stop right there. This is wrong.

Your app has its own sandbox. This sandbox persists forever, thru updates, as long as your app keeps its Bundle ID, and as long as the user does not delete the app.

You thus have no business knowing or thinking about the full absolute path to where your file is. All you know, and all you need to know, is that it is in your app’s sandbox in the Library directory. You can, at any time, obtain the URL of the Library directory by means of its search path:

https://developer.apple.com/documentation/foundation/filemanager/searchpathdirectory/librarydirectory

And that is where the file will always be. As long as you ask the FileManager for your Library directory and for the a.txt file within it, you will find the same file, regardless of any updates, as long as the user doesn’t actually delete your app (because that deletes the sandbox).

Can explain what happens to the files

Nothing. They stay where they are within the sandbox. The absolute URL of the sandbox may change, but your files are unaffected.

how to keep the files written by the previous version of the app

They are kept automatically. You don’t have to do anything.

(Having said all that, keep in mind that if you submit an app with a different bundle id, that is not a new version of your app. It is a totally different app. In that case you would have a very different problem to solve. This would be no different from any other problem of communicating files from one app to another. You’d need to put the files in a common location, make them available thru the Document Browser, make them exportable by the user, or whatever.)

Body:
My iOS app is writing to local files to:

/var/mobile/Containers/Data/Application/A.../Library/a.txt

When my app updates, it gets a new application container ID and folder:

/var/mobile/Containers/Data/Application/B...

What happens to all the files I wrote to container ID A?

Is there an "update hook" that will allow me to copy all the "A" container files to path "B"?

Can the new version of the app (B) read the old versions files (A)?

Is there any documentation around what happens to the filesystem during updates?

Is it possible to recover files from container A after B has been installed?