问:
How to stop mongodb server on Windows?
I'm using the nginx/PHP/MongoDB stack and trying to set up my development environment on Windows by creating two batch files.

start.bat

```<code>cd C:\www\nginx
start nginx
cd C:\www\php
start php-cgi.exe -b 127.0.0.1:9000
cd C:\www\mongodb
start mongod
</code>```

stop.bat

```<code>cd C:\www\nginx
nginx -s quit
cd C:\www\php
taskkill /F /IM php-cgi.exe
cd C:\www\mongodb
mongo --eval "use admin; db.shutdownServer(); quit"  # this doesn't work
mongo --eval stop_mongod.js  # this doesn't work either
</code>```

Using taskkill to stop mongod isn't an option, since that may lead to data corruption.
Any suggestions?

答:
From the Windows command line. I'm using MongoDB 3.4 Server on 64-bit Windows 7 Pro SP1.

The following links explain the steps:

configure-a-windows-service-for-mongodb-community-edition

manually-create-a-windows-service-for-mongodb-community-edition

The following console command line terminates MongoDB at start-up:

```<code>Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\System32>"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --remove
2017-12-06T08:15:47.883-0600 I CONTROL  [main] Trying to remove Windows service 'MongoDB'
2017-12-06T08:15:47.884-0600 I CONTROL  [main] Service 'MongoDB' removed
</code>```

The MongoDB service create command line (shown below) is located in the Windows registry here:

```<code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\MongoDB
</code>```

To check, do the following:

```<code>C:\Windows\System32>sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe\" --service --c
onfig=\"C:\Program Files\MongoDB\Server\3.4\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"
[SC] CreateService SUCCESS

C:\Windows\System32>net start MongoDB
The MongoDB service is starting.
The MongoDB service was started successfully.

C:\Windows\System32>net stop MongoDB
The MongoDB service is stopping.
The MongoDB service was stopped successfully.

C:\Windows\System32>"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --remove
2017-12-06T08:16:36.504-0600 I CONTROL  [main] Trying to remove Windows service 'MongoDB'
2017-12-06T08:16:36.505-0600 I CONTROL  [main] Service 'MongoDB' removed

C:\Windows\System32>
</code>```

Title: How to stop mongodb server on Windows?

Body:
I'm using the nginx/PHP/MongoDB stack and trying to set up my development environment on Windows by creating two batch files.

start.bat

cd C:\www\nginx
start nginx
cd C:\www\php
start php-cgi.exe -b 127.0.0.1:9000
cd C:\www\mongodb
start mongod

stop.bat

cd C:\www\nginx
nginx -s quit
cd C:\www\php
taskkill /F /IM php-cgi.exe
cd C:\www\mongodb
mongo --eval "use admin; db.shutdownServer(); quit"  # this doesn't work
mongo --eval stop_mongod.js  # this doesn't work either

Using taskkill to stop mongod isn't an option, since that may lead to data corruption.
Any suggestions?

Body:
From the Windows command line. I'm using MongoDB 3.4 Server on 64-bit Windows 7 Pro SP1.

The following links explain the steps:

configure-a-windows-service-for-mongodb-community-edition

manually-create-a-windows-service-for-mongodb-community-edition

The following console command line terminates MongoDB at start-up:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\System32>"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --remove
2017-12-06T08:15:47.883-0600 I CONTROL  [main] Trying to remove Windows service 'MongoDB'
2017-12-06T08:15:47.884-0600 I CONTROL  [main] Service 'MongoDB' removed

The MongoDB service create command line (shown below) is located in the Windows registry here:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\MongoDB

To check, do the following:

C:\Windows\System32>sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe\" --service --c
onfig=\"C:\Program Files\MongoDB\Server\3.4\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"
[SC] CreateService SUCCESS

C:\Windows\System32>net start MongoDB
The MongoDB service is starting.
The MongoDB service was started successfully.

C:\Windows\System32>net stop MongoDB
The MongoDB service is stopping.
The MongoDB service was stopped successfully.

C:\Windows\System32>"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --remove
2017-12-06T08:16:36.504-0600 I CONTROL  [main] Trying to remove Windows service 'MongoDB'
2017-12-06T08:16:36.505-0600 I CONTROL  [main] Service 'MongoDB' removed

C:\Windows\System32>


来源: stackexchange

问:
Fast binary parser algorithm

I'm writing a parser for binary files. The data is stored in consecutive 32 bit records. The files only have to be read once and as this is done it is fed into the analysis algorithm.

Now I am reading the file in chunks of 1024 records to avoid as much of the overhead from calling fread more frequently than necessary as possible. In the example below I use oflcorrection, timetag and channel as outputs for the algorithms and use the bool return value to check if the algorithm should stop. Also note that not all the records contain photons just those with positive values.

With this approach I can process  at up to 0.5GBps or 1.5 GBps  if I use the threaded version of the algorithms which break the file into pieces. I know my SSD can read at least a 40% faster. I was thinking of using SIMD to parse several records in parallel but I don't know how to do it with the conditional return clauses.

Do you know any other approach that would allow me to combine chunked reading and SIMD? Is there in general a better way of doing it?

Thanks

P.S. The records correspond to either photons arriving to detectors after going through a beam splitter or a special record that indicates an overflow condition. The latter is needed because Timetags are stored with picosecond resolution in uint64_t.

```<code> static inline bool next_photon(FILE* filehandle, uint64_t * RecNum,
                               uint64_t StopRecord, record_buf_t *buffer,
                               uint64_t *oflcorrection, uint64_t *timetag, int *channel)
{
    pop_record:
    while (__builtin_unpredictable(buffer->head < RECORD_CHUNK)) { // still have records on buffer
        ParseHHT2_HH2(buffer->records[buffer->head], channel, timetag, oflcorrection);
        buffer->head++;
        (*RecNum)++;

        if (*RecNum >= StopRecord) { // run out of records
            return false;
        }

        if (*channel >= 0) { // found a photon
            return true;
        }
    }
    // run out of buffer
    buffer->head = 0;
    fread(buffer->records, RECORD_CHUNK, sizeof(uint32_t), filehandle);
    goto pop_record;
}
</code>```

Please find below the parsing function. Keep in mind that I can't do anything about the file format. Thanks again, Guillem.

```<code>static inline void ParseHHT2_HH2(uint32_t record, int *channel,
                                 uint64_t *timetag, uint64_t *oflcorrection)
{
    const uint64_t T2WRAPAROUND_V2 = 33554432;
    union{
        uint32_t   allbits;
        struct{ unsigned timetag  :25;
            unsigned channel  :6;
            unsigned special  :1;
        } bits;
    } T2Rec;

    T2Rec.allbits = record;

    if(T2Rec.bits.special) {
        if(T2Rec.bits.channel==0x3F) {  //an overflow record
            if(T2Rec.bits.timetag!=0) {
                *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
            }
            else {  // if it is zero it is an old style single overflow
                *oflcorrection += T2WRAPAROUND_V2;  //should never happen with new Firmware!
            }
            *channel = -1;
        } else if(T2Rec.bits.channel == 0) {  //sync
            *channel = 0;
        } else if(T2Rec.bits.channel<=15) {  //markers
            *channel = -2;
        }
    } else {//regular input channel
        *channel = T2Rec.bits.channel + 1;
    }
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}
</code>```

I came up with an almost branchless parsing function, but it doesn't produce any speed up.

```<code>if(T2Rec.bits.channel==0x3F) {  //an overflow record
        *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
    }
    *channel = (!T2Rec.bits.special) * (T2Rec.bits.channel + 1) - T2Rec.bits.special * T2Rec.bits.channel;
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}
</code>```

答:
I/O is very likely to dominate the runtime of your function. That said, you should first measure the speed without parsing, i.e. just the fread. Probably it won't differ that much to the speed including parsing.

If so, you can concentrate on optimizing that bottleneck first. Look into the linux tool fio, in particular with different --ioenginge= (also libaio). In case you are using an NVMe disk, look into the Intel SPDK.

Apart from that, you can optimize the parsing further. You can avoid both the (*RecNum)++ and more importantly the first if-clause within the loop, since after the fread you know how many records you will read, so you can use that information.

Furthermore, I would not iterate over buffer->head but use a local variable for that, using a for-loop.

I also would use a local variable for *RecNum and only at the end assign to *RecNum. If you are aiming at parallel writing to *RecNum, your code would be buggy anyways, because neither your increment nor your read uses an atomic operation.

Not until then you should start thinking about SSE or AVX. If you have mostly zeroes in *channel, you could use SSE/AVX to check 16 or more bytes at once for greater or equal zero.

Update:

Now after you providing the code of your parse function, I can see that situation is different. Many branches there...

Update:

Here is an implementation of the optimizations for next_photon that I mean. If buffer->head == 0 is guaranteed when entering next_photon, it can be simplified. And I assume you don't check the return value of fread on purpose, because you want to handle that with StopRecord only. So I left it like that even though it's not safe.

```<code>static inline bool next_photon(FILE* filehandle, uint64_t *RecNum,
                            uint64_t StopRecord, record_buf_t *buffer,
                            uint64_t *oflcorrection, uint64_t *timetag,
                            int *channel)
{
    int recNum = *RecNum;
    int i = buffer->head;

    while (true) {
        int records;
        bool quit;

        if (StopRecord - recNum <= RECORD_CHUNK - i) {
            records = i + StopRecord - recNum;
            quit = true;
        } else {
            records = RECORD_CHUNK;
            quit = false;
        }

        const int i0 = i;

        for (; i < records; i++) { // still have records on buffer
            ParseHHT2_HH2(buffer->records[i], channel, timetag, oflcorrection);

            if (*channel >= 0) { // found a photon
                *RecNum = recNum + i - i0 + 1;
                buffer->head = i + 1;
                return true;
            }
        }

        recNum += records - i0;

        if (quit) {
            break;
        }

        // run out of buffer
        i = 0;
        fread(buffer->records, RECORD_CHUNK, sizeof(uint32_t), filehandle);
    }

    *RecNum = recNum;
    buffer->head = i;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Fast binary parser algorithm

Body:
I'm writing a parser for binary files. The data is stored in consecutive 32 bit records. The files only have to be read once and as this is done it is fed into the analysis algorithm.

Now I am reading the file in chunks of 1024 records to avoid as much of the overhead from calling fread more frequently than necessary as possible. In the example below I use oflcorrection, timetag and channel as outputs for the algorithms and use the bool return value to check if the algorithm should stop. Also note that not all the records contain photons just those with positive values.

With this approach I can process  at up to 0.5GBps or 1.5 GBps  if I use the threaded version of the algorithms which break the file into pieces. I know my SSD can read at least a 40% faster. I was thinking of using SIMD to parse several records in parallel but I don't know how to do it with the conditional return clauses.

Do you know any other approach that would allow me to combine chunked reading and SIMD? Is there in general a better way of doing it?

Thanks

P.S. The records correspond to either photons arriving to detectors after going through a beam splitter or a special record that indicates an overflow condition. The latter is needed because Timetags are stored with picosecond resolution in uint64_t.

 static inline bool next_photon(FILE* filehandle, uint64_t * RecNum,
                               uint64_t StopRecord, record_buf_t *buffer,
                               uint64_t *oflcorrection, uint64_t *timetag, int *channel)
{
    pop_record:
    while (__builtin_unpredictable(buffer->head < RECORD_CHUNK)) { // still have records on buffer
        ParseHHT2_HH2(buffer->records[buffer->head], channel, timetag, oflcorrection);
        buffer->head++;
        (*RecNum)++;

        if (*RecNum >= StopRecord) { // run out of records
            return false;
        }

        if (*channel >= 0) { // found a photon
            return true;
        }
    }
    // run out of buffer
    buffer->head = 0;
    fread(buffer->records, RECORD_CHUNK, sizeof(uint32_t), filehandle);
    goto pop_record;
}

Please find below the parsing function. Keep in mind that I can't do anything about the file format. Thanks again, Guillem.

static inline void ParseHHT2_HH2(uint32_t record, int *channel,
                                 uint64_t *timetag, uint64_t *oflcorrection)
{
    const uint64_t T2WRAPAROUND_V2 = 33554432;
    union{
        uint32_t   allbits;
        struct{ unsigned timetag  :25;
            unsigned channel  :6;
            unsigned special  :1;
        } bits;
    } T2Rec;

    T2Rec.allbits = record;

    if(T2Rec.bits.special) {
        if(T2Rec.bits.channel==0x3F) {  //an overflow record
            if(T2Rec.bits.timetag!=0) {
                *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
            }
            else {  // if it is zero it is an old style single overflow
                *oflcorrection += T2WRAPAROUND_V2;  //should never happen with new Firmware!
            }
            *channel = -1;
        } else if(T2Rec.bits.channel == 0) {  //sync
            *channel = 0;
        } else if(T2Rec.bits.channel<=15) {  //markers
            *channel = -2;
        }
    } else {//regular input channel
        *channel = T2Rec.bits.channel + 1;
    }
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}

I came up with an almost branchless parsing function, but it doesn't produce any speed up.

if(T2Rec.bits.channel==0x3F) {  //an overflow record
        *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
    }
    *channel = (!T2Rec.bits.special) * (T2Rec.bits.channel + 1) - T2Rec.bits.special * T2Rec.bits.channel;
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}

Body:
I/O is very likely to dominate the runtime of your function. That said, you should first measure the speed without parsing, i.e. just the fread. Probably it won't differ that much to the speed including parsing.

If so, you can concentrate on optimizing that bottleneck first. Look into the linux tool fio, in particular with different --ioenginge= (also libaio). In case you are using an NVMe disk, look into the Intel SPDK.

Apart from that, you can optimize the parsing further. You can avoid both the (*RecNum)++ and more importantly the first if-clause within the loop, since after the fread you know how many records you will read, so you can use that information.

Furthermore, I would not iterate over buffer->head but use a local variable for that, using a for-loop.

I also would use a local variable for *RecNum and only at the end assign to *RecNum. If you are aiming at parallel writing to *RecNum, your code would be buggy anyways, because neither your increment nor your read uses an atomic operation.

Not until then you should start thinking about SSE or AVX. If you have mostly zeroes in *channel, you could use SSE/AVX to check 16 or more bytes at once for greater or equal zero.

Update:

Now after you providing the code of your parse function, I can see that situation is different. Many branches there...

Update:

Here is an implementation of the optimizations for next_photon that I mean. If buffer->head == 0 is guaranteed when entering next_photon, it can be simplified. And I assume you don't check the return value of fread on purpose, because you want to handle that with StopRecord only. So I left it like that even though it's not safe.

static inline bool next_photon(FILE* filehandle, uint64_t *RecNum,
                            uint64_t StopRecord, record_buf_t *buffer,
                            uint64_t *oflcorrection, uint64_t *timetag,
                            int *channel)
{
    int recNum = *RecNum;
    int i = buffer->head;

    while (true) {
        int records;
        bool quit;

        if (StopRecord - recNum <= RECORD_CHUNK - i) {
            records = i + StopRecord - recNum;
            quit = true;
        } else {
            records = RECORD_CHUNK;
            quit = false;
        }

        const int i0 = i;

        for (; i < records; i++) { // still have records on buffer
            ParseHHT2_HH2(buffer->records[i], channel, timetag, oflcorrection);

            if (*channel >= 0) { // found a photon
                *RecNum = recNum + i - i0 + 1;
                buffer->head = i + 1;
                return true;
            }
        }

        recNum += records - i0;

        if (quit) {
            break;
        }

        // run out of buffer
        i = 0;
        fread(buffer->records, RECORD_CHUNK, sizeof(uint32_t), filehandle);
    }

    *RecNum = recNum;
    buffer->head = i;
}


问:
how do I get hs-minor-mode to load automatically on php-mode in emacs?
For my favorite modes, I use the following snippet to load hs-minor-mode on startup:

```<code>(add-hook '____-mode-hook 'hs-minor-mode)
</code>```

So far it's gotten working on css-mode, perl-mode, sh-mode (bash), and lisp-mode. But for some reason it won't load for php-mode, even if I can load it manually.

Here's my php-mode settings:

```<code>(defun php-overload-keys ()
 (let ((map php-mode-map))
  (define-key map "\t" 'dumb-indent-relative)
  (define-key map "\177" 'backward-delete-char)
  (define-key map "," nil)
  (define-key map ";" nil)
  (define-key map ":" nil)
  (define-key map "*" nil)
  (define-key map "{" nil)
  (define-key map "}" nil)
  (define-key map "(" nil)
  (define-key map ")" nil)
  (define-key map "/" nil)
  (use-local-map map)))

(add-hook 'php-mode-hook 'php-overload-keys)
(add-hook 'php-mode-hook 'hs-minor-mode)
</code>```

Am I doing anything wrong? I tried wrapping hs-minor-mode in a function and it still won't load. My overloaded keys, however, do. What's the deal?

答:
Mode functions typically accept a numeric argument to enable/disable them, and act as toggles if no argument is supplied, so as a general rule you should use:

(add-hook 'php-mode-hook (lambda () (hs-minor-mode 1)))

ContentLicense: CC BY-SA 2.5

Body:
For my favorite modes, I use the following snippet to load hs-minor-mode on startup:

(add-hook '____-mode-hook 'hs-minor-mode)

So far it's gotten working on css-mode, perl-mode, sh-mode (bash), and lisp-mode. But for some reason it won't load for php-mode, even if I can load it manually.

Here's my php-mode settings:

(defun php-overload-keys ()
 (let ((map php-mode-map))
  (define-key map "\t" 'dumb-indent-relative)
  (define-key map "\177" 'backward-delete-char)
  (define-key map "," nil)
  (define-key map ";" nil)
  (define-key map ":" nil)
  (define-key map "*" nil)
  (define-key map "{" nil)
  (define-key map "}" nil)
  (define-key map "(" nil)
  (define-key map ")" nil)
  (define-key map "/" nil)
  (use-local-map map)))

(add-hook 'php-mode-hook 'php-overload-keys)
(add-hook 'php-mode-hook 'hs-minor-mode)

Am I doing anything wrong? I tried wrapping hs-minor-mode in a function and it still won't load. My overloaded keys, however, do. What's the deal?


问:
Convert time duration (BigDecimal value + time units) to milliseconds long
I have to create a function that has 2 input parameters:
Time duration in BigDecimal (precision 38, scale 6)
and
TimeUnitsType enum (DAYS, HOURS, MINUTES or SECONDS).

And I need to get long value (milliseconds) as a result;
As I understand, the longValue() method from BigDecimal won't work precisely here as it set scale to 0, and longValueExact() will throw ArithmeticException("Overflow") (because precision - scale > 19)

```<code>public static long convertTimeToMillis(BigDecimal time, TimeUnitsType timeUnitsType) {
    long timeLong = time.longValue();
    switch (timeUnitsType) {
        case DAYS:
            return TimeUnit.DAYS.toMillis(timeLong);
        case HOURS:
            return TimeUnit.HOURS.toMillis(timeLong);
        case MINUTES:
            return TimeUnit.MINUTES.toMillis(timeLong);
        default:
            return TimeUnit.SECONDS.toMillis(timeLong);
    }
}
</code>```

So I need to make individual calculation for each case separately. Can you please help me? BigDecimal operations scares me a little, because I haven't work with them before :) And the precision is required in the rest of the task.

P.S. Java version is 1.6

答: There is a reason that you are allowing up to 6 decimal positions in the incoming value, so you can't just ignore them. Do the conversions yourself, creating a new BigDecimal that retains the decimal positions. Once you have milliseconds, round that BigDecimal. Finally, compare the BigDecimal to Long.MAX_VALUE and MIN_VALUE. If it is outside those bounds, throw an exception.</p>

Body:
I have to create a function that has 2 input parameters:
Time duration in BigDecimal (precision 38, scale 6)
and
TimeUnitsType enum (DAYS, HOURS, MINUTES or SECONDS).

And I need to get long value (milliseconds) as a result;
As I understand, the longValue() method from BigDecimal won't work precisely here as it set scale to 0, and longValueExact() will throw ArithmeticException("Overflow") (because precision - scale > 19)

public static long convertTimeToMillis(BigDecimal time, TimeUnitsType timeUnitsType) {
    long timeLong = time.longValue();
    switch (timeUnitsType) {
        case DAYS:
            return TimeUnit.DAYS.toMillis(timeLong);
        case HOURS:
            return TimeUnit.HOURS.toMillis(timeLong);
        case MINUTES:
            return TimeUnit.MINUTES.toMillis(timeLong);
        default:
            return TimeUnit.SECONDS.toMillis(timeLong);
    }
}

So I need to make individual calculation for each case separately. Can you please help me? BigDecimal operations scares me a little, because I haven't work with them before :) And the precision is required in the rest of the task.

P.S. Java version is 1.6


问:
Running Django server on localhost
I would like to run a Django server locally using a local IP.

I have localhost mapped here:

```<code>$ head -n 1 /etc/hosts
127.0.0.1   localhost
</code>```

I have this chunk of code in my settings.py:

```<code>import os
ALLOWED_HOSTS = ['HERE.IS.MY.IP', 'localhost', '127.0.0.1']
print "ALLOWED_HOSTS: {}".format(ALLOWED_HOSTS)
</code>```

In my mysql database I have this site table:

```<code>mysql> select * from django_site;
+----+--------------------+----------------+
| id | domain             | name           |
+----+--------------------+----------------+
|  1 | example.com        | example.com    |
|  5 | HERE.IS.MY.IP:8000 | projectsdb     |
|  8 | 127.0.0.1:8000     | projectsdb     |
|  9 | localhost:8000     | projectsdb     |
+----+--------------------+----------------+
</code>```

I run the server locally on 127.0.0.1:

```<code>$ python manage.py runserver 8000
ALLOWED_HOSTS: ['HERE.IS.MY.IP', 'localhost', '127.0.0.1']

Performing system checks...
# ...
Django version 1.10.5, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
</code>```

If I go to this address http://HERE.IS.MY.IP:8000 it works. But of course I'd like to open it using a local IP such as http://localhost:8000 or http://127.0.0.1:8000. But this does not work. What am I missing?

答:
Ok I solved it, silly me. I thought I was trying to access the server's page locally, but I wasn't. The server is running on a specific machine, and I was trying to access it locally from another machine (my laptop).

Explanations:
The server runs on HERE.IS.MY.IP:8000, only locally because I only gave the port 8000:

```<code>$ python manage.py runserver 8000
</code>```

I am trying to access the server from the web browser on my laptop, so the IP used is different than HERE.IS.MY.IP.
If I want to access the page on http://HERE.IS.MY.IP:8000 from my laptop I have no other choice than to allow the server access to external machines by running the server like this:

```<code>$ python manage.py runserver 0.0.0.0:8000
</code>```

or

```<code>$ python manage.py runserver HERE.IS.MY.IP:8000
</code>```

and then to access it on my laptop's browser with the full IP (unless I map it on /etc/hosts) on http://HERE.IS.MY.IP:8000

Now if I want to access the page locally only from the server side, I have to run

```<code>$ python manage.py runserver 8000
</code>```

, open a browser from the said server and then I can contact the pages http://HERE.IS.MY.IP:8000, http://127.0.0.1:8000 and http://localhost:8000 successfully.

So my mistake here was that I was accessing the server's page not from the server's browser itself but from another machine's.

Title: Running Django server on localhost

Body:
I would like to run a Django server locally using a local IP.

I have localhost mapped here:

$ head -n 1 /etc/hosts
127.0.0.1   localhost

I have this chunk of code in my settings.py:

import os
ALLOWED_HOSTS = ['HERE.IS.MY.IP', 'localhost', '127.0.0.1']
print "ALLOWED_HOSTS: {}".format(ALLOWED_HOSTS)

In my mysql database I have this site table:

mysql> select * from django_site;
+----+--------------------+----------------+
| id | domain             | name           |
+----+--------------------+----------------+
|  1 | example.com        | example.com    |
|  5 | HERE.IS.MY.IP:8000 | projectsdb     |
|  8 | 127.0.0.1:8000     | projectsdb     |
|  9 | localhost:8000     | projectsdb     |
+----+--------------------+----------------+

I run the server locally on 127.0.0.1:

$ python manage.py runserver 8000
ALLOWED_HOSTS: ['HERE.IS.MY.IP', 'localhost', '127.0.0.1']

Performing system checks...
# ...
Django version 1.10.5, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

If I go to this address http://HERE.IS.MY.IP:8000 it works. But of course I'd like to open it using a local IP such as http://localhost:8000 or http://127.0.0.1:8000. But this does not work. What am I missing?

Body:
Ok I solved it, silly me. I thought I was trying to access the server's page locally, but I wasn't. The server is running on a specific machine, and I was trying to access it locally from another machine (my laptop).

Explanations:
The server runs on HERE.IS.MY.IP:8000, only locally because I only gave the port 8000:

$ python manage.py runserver 8000

I am trying to access the server from the web browser on my laptop, so the IP used is different than HERE.IS.MY.IP.
If I want to access the page on http://HERE.IS.MY.IP:8000 from my laptop I have no other choice than to allow the server access to external machines by running the server like this:

$ python manage.py runserver 0.0.0.0:8000

or

$ python manage.py runserver HERE.IS.MY.IP:8000

and then to access it on my laptop's browser with the full IP (unless I map it on /etc/hosts) on http://HERE.IS.MY.IP:8000

Now if I want to access the page locally only from the server side, I have to run

$ python manage.py runserver 8000

, open a browser from the said server and then I can contact the pages http://HERE.IS.MY.IP:8000, http://127.0.0.1:8000 and http://localhost:8000 successfully.

So my mistake here was that I was accessing the server's page not from the server's browser itself but from another machine's.


问:
ajax won't correctly pull post using wp_query
I'm a beginner at using Ajax, and I'm trying to load a post using ajax onto a lightbox for a site i'm working on. This idea is when they click on the post in an archive page, it opens a post lightbox rather than going to a new page.

My Code is below:

In Functions.php

```<code>add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
function enqueue_scripts() {
    //other scripts
    wp_localize_script( 'ajax-postload', 'ajaxpostload', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));
}
add_action( 'wp_ajax_nopriv_ajax_postload', 'my_ajax_postload' );
add_action( 'wp_ajax_ajax_postload', 'my_ajax_postload' );

function my_ajax_postload() {

    $postid = $_POST['postid'];
    $args = array(
        'p' => $postid
    );

    $posts = new WP_Query( $args );

    if( ! $posts->have_posts() ) {
        ?>
        <div class="image-info">
            <p>There has been an issue loading this image, please try again.</p>
        </div>
        <?php
    }
    else {
        while ( $posts->have_posts() ) {
            $posts->the_post();
            ?>
            <div class="image-info">
                <h3>Image Name: </h3>
                <h4><?php the_title(); ?></h4>
                <h3>Image Description:</h3>
                <div class="description">
                    <?php the_content(); ?>
                </div>
            </div>
            <div class="lightbox-image">
                <?php the_post_thumbnail(); ?>
            </div>
            <?php
        }
    }

    die();
}
</code>```

In Javascript file:

```<code>(function($) {
    function find_post_ID( element ) {
        var link = $(element).parents('.post-link');
        return $(link).find('.post-id').attr('id').replace('lightbox-',"")
    }
    if (window.innerWidth > 767) {
    $(document).on( 'click', '.post-link', function( event ) {
        event.preventDefault();

        $wp_postid = find_post_ID( event.target );

        $.ajax({
            url: ajaxpostload.ajaxurl,
            type: 'post',
            data: {
                action: 'ajax_postload',
                postid: $wp_postid,
                query_vars: ajaxpostload.query_vars
            },
            beforeSend: function() {
                $('.lightbox .image-info').remove();
                $('.lightbox').append( '<div class="image-info" id="loader"><h3>Loading Image...</h3></div>' );
                $('.lightbox').css( 'display' , 'block');
            },
            success: function( html ) {
                $('.lightbox #loader').remove();
                $('.lightbox').append( html );
            }
        })
    });
    }
})(jQuery);
</code>```

My Issue is whenever I click on a post, the lightbox opens, but shows the no posts error message, am I missing something simple or have I messed up the ajax call?

答:
You should pass 'any' argument as a post_type for fetching post as below,

```<code> $postid = $_POST['postid'];
  $args = array(
        'p' => $postid,
        'post_type' => 'any'
    );
</code>```

If without ajax you have try to get post using only 'p' (one argument) that will return no posts.
So try that and check your result.

Body:
I'm a beginner at using Ajax, and I'm trying to load a post using ajax onto a lightbox for a site i'm working on. This idea is when they click on the post in an archive page, it opens a post lightbox rather than going to a new page.

My Code is below:

In Functions.php

add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
function enqueue_scripts() {
    //other scripts
    wp_localize_script( 'ajax-postload', 'ajaxpostload', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));
}
add_action( 'wp_ajax_nopriv_ajax_postload', 'my_ajax_postload' );
add_action( 'wp_ajax_ajax_postload', 'my_ajax_postload' );

function my_ajax_postload() {

    $postid = $_POST['postid'];
    $args = array(
        'p' => $postid
    );

    $posts = new WP_Query( $args );

    if( ! $posts->have_posts() ) {
        ?>

There has been an issue loading this image, please try again.

        <?php
    }
    else {
        while ( $posts->have_posts() ) {
            $posts->the_post();
            ?>

Image Name:

<?php the_title(); ?>

Image Description:

                    <?php the_content(); ?>

                <?php the_post_thumbnail(); ?>

            <?php
        }
    }

    die();
}

In Javascript file:

(function($) {
    function find_post_ID( element ) {
        var link = $(element).parents('.post-link');
        return $(link).find('.post-id').attr('id').replace('lightbox-',"")
    }
    if (window.innerWidth > 767) {
    $(document).on( 'click', '.post-link', function( event ) {
        event.preventDefault();

        $wp_postid = find_post_ID( event.target );

        $.ajax({
            url: ajaxpostload.ajaxurl,
            type: 'post',
            data: {
                action: 'ajax_postload',
                postid: $wp_postid,
                query_vars: ajaxpostload.query_vars
            },
            beforeSend: function() {
                $('.lightbox .image-info').remove();
                $('.lightbox').append( '

Loading Image...

' );
                $('.lightbox').css( 'display' , 'block');
            },
            success: function( html ) {
                $('.lightbox #loader').remove();
                $('.lightbox').append( html );
            }
        })
    });
    }
})(jQuery);

My Issue is whenever I click on a post, the lightbox opens, but shows the no posts error message, am I missing something simple or have I messed up the ajax call?

Body:
You should pass 'any' argument as a post_type for fetching post as below,

 $postid = $_POST['postid'];
  $args = array(
        'p' => $postid,
        'post_type' => 'any'
    );

If without ajax you have try to get post using only 'p' (one argument) that will return no posts.
So try that and check your result.


问:
Equivalent of specific template usage in C++ for Rust
Is there a feature in Rust that makes something like this possible?
As far as I know, this is not possible with Rust's generic functions because they work only with data types and not with values.

#include <iostream>

template<int T>
int foo(int a)
{
  return -1;
}
template<>
int foo<2>(int a)
{
  return a*a;
}
template<>
int foo<3>(int a)
{
  return a*a*a;
}

int main()
{
  std::cout << "foo<1>(3): "<<foo<1>(3) << std::endl;
  std::cout << "foo<2>(3): "<<foo<2>(3) << std::endl;
  std::cout << "foo<3>(3): "<<foo<3>(3) << std::endl;
  return 1;
}
```

<p>Result:</p>

<pre class="lang-none prettyprint-override"><code>foo<1>(3): -1
foo<2>(3): 9
foo<3>(3): 27
</code>```

答:
TL;DR: Not yet, maybe not ever.

Rust generics are not as powerful, yet, as C++ templates, and may never be.

Specifically here, two features are required:

RFC 2000: Const generics: which will enable non-type generic parameters,

RFC 2000: Specialization on const generics.

Note: it is unclear how advanced the specialization will be; in this specific case where you use full specialization it should be enough, however it is not clear whether partial specialization will be implemented, and how.

There are also other missing pieces, though not related to this case:

RFC 1598: Generic Associated Types: equivalent to nested template <...> using ... = ...; and allowing to emulate template template parameters,

variadics: there have been multiple RFCs, but none seems to have gain much foothold.

It would be easy to deride Rust developers, or shrug it off as a lack of maturity; it would also be incorrect.

As I mentioned, it is not clear that Rust will ever gain some of those features, not because the developers could not implement them, they certainly could, they certainly could have already, but because there is a strong focus in doing things right1.

For example, specialization is a nightmare in C++. It is Undefined Behavior to instantiate a template with a set of arguments A, and later (or in another translation unit) specialize it in a way that would match A. For functions, this generally manifests as the linker picking either the generic or the specialized version... randomly. It's not fun to debug.

Any modifications to generics has large potential repercussions on the rest of the type system, complex interactions with other language features, and significant changes about what a well-typed program means:

they are therefore heavily scrutinized,

and there is a strong push toward going slow and building incrementally, so as to evaluate those impacts, interactions and changes one at a time.

In short, Rust developers are attempting to build a well-principled generics system, and it's not easy.

1 There are also concerns about unnecessary complexity, so features are not added "just because", but require motivating use cases which should be compelling enough to justify the additional complexity in the language and the compiler; but that's another gate entirely.

Body:
Is there a feature in Rust that makes something like this possible?
As far as I know, this is not possible with Rust's generic functions because they work only with data types and not with values.

#include <iostream>

template<int T>
int foo(int a)
{
  return -1;
}
template<>
int foo<2>(int a)
{
  return a*a;
}
template<>
int foo<3>(int a)
{
  return a*a*a;
}

int main()
{
  std::cout << "foo<1>(3): "<<foo<1>(3) << std::endl;
  std::cout << "foo<2>(3): "<<foo<2>(3) << std::endl;
  std::cout << "foo<3>(3): "<<foo<3>(3) << std::endl;
  return 1;
}

Result:

foo<1>(3): -1
foo<2>(3): 9
foo<3>(3): 27


问:
How to solve this logic operation? (homework)
The teacher gave us this question and I couldn't answer it and I hope to get here some help.

Perform the following logic operation:

1- AB5D AND CD5F

2- DD1D XOR B159

And I want to know the step that I should follow to find the right answer.

答:
0xAB5D AND 0xCD5F = 0x895D

0xDD1D XOR 0xB159 = 06C44

Use 'calc' in windows or 'gnome-calculator' in GNOME linux or just Pyrhon / Ruby it.

UPD: if you wanna do this on the paper, follow next few easy steps:

convert your numbers to binary (for ex. 0xAB5D == 1010101101011101; 0xCD5F == 1100110101011111)

perform bitwise operation on those two binaries (1010101101011101 AND 1100110101011111 = 1000100101011101)

convert the result to hex or decimal


问:
InvokeRepeating not working in unity with .Net 4.6
I attached the below script to the camera

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sample : MonoBehaviour {

    int i=0;

    void Start () {
        Debug.Log("This is printed immediately");
        Debug.Log("Called invoke repating ");
        InvokeRepeating("test", 0.0f, 0.5f);
    }

    void test()
    {
        i++;
        Debug.Log("Called invoke repating "+i);
    }

    void Update () {
    }
}
</code>```

this is what i get in my console (it stops and doesn't get invoked repeatedly):

```<code>This is printed immediately
UnityEngine.Debug:Log(Object)
Sample:Start() (at Assets/Sample.cs:27)
Called invoke repating
UnityEngine.Debug:Log(Object)
Sample:Start() (at Assets/Sample.cs:28)
Called invoke repating 1
UnityEngine.Debug:Log(Object)
Sample:test() (at Assets/Sample.cs:36)
</code>```

Does anyone have a clue what is going on... I can't seem to spot any mistake here.

Screenshot -

答:
This worked -

Go to Edit > Project Settings > Time

Timescale has to be 1

Body:
I attached the below script to the camera

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sample : MonoBehaviour {

    int i=0;

    void Start () {
        Debug.Log("This is printed immediately");
        Debug.Log("Called invoke repating ");
        InvokeRepeating("test", 0.0f, 0.5f);
    }

    void test()
    {
        i++;
        Debug.Log("Called invoke repating "+i);
    }

    void Update () {
    }
}

this is what i get in my console (it stops and doesn't get invoked repeatedly):

This is printed immediately
UnityEngine.Debug:Log(Object)
Sample:Start() (at Assets/Sample.cs:27)
Called invoke repating
UnityEngine.Debug:Log(Object)
Sample:Start() (at Assets/Sample.cs:28)
Called invoke repating 1
UnityEngine.Debug:Log(Object)
Sample:test() (at Assets/Sample.cs:36)

Does anyone have a clue what is going on... I can't seem to spot any mistake here.

Screenshot -


问:
How to get correct price based on quantity in list using Cakephp2.x?
I have a listing page where I got item name,price,quantity.Now,I want if someone increase the quantity of item from list then price also increase according th actual price.Here is my file view_item.ctp</p>

```<code><?php
  foreach($result as $k=>$v) { ?>

  <tr class="hide_me_<?php echo $v['Inventory']['id']; ?> ">
  <td><i class="fa fa-chevron-right"></i></td>
  <td><?php echo $v['Inventory']['item_name']; ?></td>
  <td class="text-center">
  <span class="box-plush" id='plusbutton' onclick="itemQty(<?php echo
   $v['Inventory']['id']; ?>,'incr')"><i class="fa fa-plus"></i></span>

  <span class="box-dgt" id='att_<?php echo $v['Inventory']['id']; ?
  >'>1</span>

 <span class="box-minus" id='minusbutton' onclick="itemQty(<?php echo
 $v['Inventory']['id']; ?>,'decr')"><i class="fa fa-minus"></i> </span>
 </td>

 <td class="text-center" id='price_<?php echo $v['Inventory']['id']; ?>'><?
 php echo $v['Inventory']['item_price']; ?></td>

 <td class="text-right"><?php echo  $v['Inventory']['item_price']; ?></td>

 <td class="text-center">
     <a class="btn btn-danger btn-sm close-box" href="javascript:void(0)"
     onclick="menuItem(<?php echo $v['Inventory']['id']; ?>)">
      <i class="fa fa-times" ></i>
     </a>
 </td>
 </tr>
 <?php } ?>

 <script type="text/javascript">
   function menuItem(id){
   $('.hide_me_'+id).hide();
 }

  function itemQty(id,action){
    var qty = $('#att_'+id).text();
    qty = parseInt(qty);

  if(action=="incr"){
    $qty1 = qty+1;
  }else{
    $qty1 = qty-1;
  }

    $('#att_'+id).text($qty1);
  }
  </script>
</code>```

答:
Replace onclick="itemQty(<?php echo $v['Inventory']['id']; ?>,'decr')" with data-row="<?php echo $v['Inventory']['id']; ?>"

add id="total_<?php echo  $v['Inventory']['item_price']; ?>

to this line
<?php echo  $v['Inventory']['item_price']; ?>

so it becomes <td class="text-right" id="total_<?php echo  $v['Inventory']['item_price']; ?>"><?php echo  $v['Inventory']['item_price']; ?>

modify your itemQty function to calculate price

```<code>function itemQty(id, action) {
    let qty = $('#att_' + id).html();
    qty = parseInt(qty);

    if (action == "incr") {
      qty++;
    } else {
      qty--;
    }

    $('#att_' + id).html(qty);

    let price = parseFloat($('#price_' + id).html());
    let total = price * qty;
    $('#total_' + id).html(total.toFixed(2))
  }
</code>```

and then add this lines at the bottom

```<code>  $(document).ready(function() {
    $('#plusbutton').on('click', function() {
      itemQty($(this).data('row'), 'incr')
    })

    $('#minusbutton').on('click', function() {
      itemQty($(this).data('row'), 'decr')
    })
  })
</code>```

demo here: https://jsfiddle.net/shahonseven/gn8sees8/

Body:
I have a listing page where I got item name,price,quantity.Now,I want if someone increase the quantity of item from list then price also increase according th actual price.Here is my file view_item.ctp

<?php
  foreach($result as $k=>$v) { ?>

  <tr class="hide_me_<?php echo $v['Inventory']['id']; ?> ">

  <?php echo $v['Inventory']['item_name']; ?>

  <span class="box-plush" id='plusbutton' onclick="itemQty(<?php echo
   $v['Inventory']['id']; ?>,'incr')">

  <span class="box-dgt" id='att_<?php echo $v['Inventory']['id']; ?
  >'>1

 <span class="box-minus" id='minusbutton' onclick="itemQty(<?php echo
 $v['Inventory']['id']; ?>,'decr')">

 <td class="text-center" id='price_<?php echo $v['Inventory']['id']; ?>'><?
 php echo $v['Inventory']['item_price']; ?>

 <?php echo  $v['Inventory']['item_price']; ?>

     <a class="btn btn-danger btn-sm close-box" href="javascript:void(0)"
     onclick="menuItem(<?php echo $v['Inventory']['id']; ?>)">

 <?php } ?>

Body:
Replace onclick="itemQty(<?php echo $v['Inventory']['id']; ?>,'decr')" with data-row="<?php echo $v['Inventory']['id']; ?>"

add id="total_<?php echo  $v['Inventory']['item_price']; ?>

to this line
<td class="text-right"><?php echo  $v['Inventory']['item_price']; ?></td>

so it becomes <td class="text-right" id="total_<?php echo  $v['Inventory']['item_price']; ?>"><?php echo  $v['Inventory']['item_price']; ?></td>

modify your itemQty function to calculate price

function itemQty(id, action) {
    let qty = $('#att_' + id).html();
    qty = parseInt(qty);

    if (action == "incr") {
      qty++;
    } else {
      qty--;
    }

    $('#att_' + id).html(qty);

    let price = parseFloat($('#price_' + id).html());
    let total = price * qty;
    $('#total_' + id).html(total.toFixed(2))
  }

and then add this lines at the bottom

  $(document).ready(function() {
    $('#plusbutton').on('click', function() {
      itemQty($(this).data('row'), 'incr')
    })

    $('#minusbutton').on('click', function() {
      itemQty($(this).data('row'), 'decr')
    })
  })

demo here: https://jsfiddle.net/shahonseven/gn8sees8/


问:
Getting error when run react-native run-android
```<code>A problem occurred configuring project ':app'.
   > Could not resolve all dependencies for configuration ':app:_debugApk'.
     > A problem occurred configuring project ':react-native-fbsdk'.
       > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.react:react-native:0.46.4
         > Could not find com.android.support:support-annotations:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:support-core-utils:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:cardview-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:customtabs:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:support-v4:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
</code>```

compileSdkVersion 25

buildToolsVersion "25.0.0"

targetSdkVersion 25

答:
Updating Android studio solved this for me...

Below are the steps I followed

Updated android-sdk(downloaded platform and build tools for version 27 and other auto suggests)

Updated Android Studio

Synced the dependency projects

Android Studio automatically asked for updating gradle

Running react-native run-android auto downloaded dependencies from gradle-4.1-all.zip which was auto added into my "gradle-wrapper.properties" file because of gradle update from the above step

Body:
A problem occurred configuring project ':app'.
   > Could not resolve all dependencies for configuration ':app:_debugApk'.
     > A problem occurred configuring project ':react-native-fbsdk'.
       > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.react:react-native:0.46.4
         > Could not find com.android.support:support-annotations:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:support-core-utils:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:cardview-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:customtabs:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:support-v4:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0

compileSdkVersion 25

buildToolsVersion "25.0.0"

targetSdkVersion 25


问:
Simpler formula for a 5 nested if command
I have been scouring forums for a solution but am striking out so far.  I want to do a countA of all non empty cells -1.  The data I'm pulling from is in Q:U, and I want to do a count based on the header of the columns in row 2.  Because of where the data comes from in Q:U, the column order is not always going to be the same.

I have the following string which works where I can replace each instance of "Test" with the particular header I am looking for.  Is there a simpler command using a combination if Index and Match that would work?  Or even a better solution?

```<code>=IF($Q$2="Test",COUNTIF($Q$3:$Q$150,">0")-1,IF($R$2="Test",COUNTIF($R$3:$R$150,">0")-1,IF($S$2="Test",COUNTIF($S$3:$S$150,">0")-1,IF($T$2="Test",COUNTIF($T$3:$T$150,">0")-1,IF($U$2="Test",COUNTIF($U$3:$U$150,">0")-1,0)))))
</code>```

答:
use:

```<code>=COUNTIF(INDEX($Q$3:$U$150,0,MATCH("Test",$Q$2:$U$2,0)),">0")-1
</code>```

You can replace "Test" with a cell reference that you then can change to look up different columns by their name.

Body:
I have been scouring forums for a solution but am striking out so far.  I want to do a countA of all non empty cells -1.  The data I'm pulling from is in Q:U, and I want to do a count based on the header of the columns in row 2.  Because of where the data comes from in Q:U, the column order is not always going to be the same.

I have the following string which works where I can replace each instance of "Test" with the particular header I am looking for.  Is there a simpler command using a combination if Index and Match that would work?  Or even a better solution?

=IF($Q$2="Test",COUNTIF($Q$3:$Q$150,">0")-1,IF($R$2="Test",COUNTIF($R$3:$R$150,">0")-1,IF($S$2="Test",COUNTIF($S$3:$S$150,">0")-1,IF($T$2="Test",COUNTIF($T$3:$T$150,">0")-1,IF($U$2="Test",COUNTIF($U$3:$U$150,">0")-1,0)))))

Body:
use:

=COUNTIF(INDEX($Q$3:$U$150,0,MATCH("Test",$Q$2:$U$2,0)),">0")-1

You can replace "Test" with a cell reference that you then can change to look up different columns by their name.


问:
In c# how to prevent a class from being modified
Let's say I have an interface:

```<code>interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
   bool Alive { get; set; }
}
</code>```

and a Class:

```<code>public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
}
</code>```

That would not compile since Person does not implement the Alive Property.

What I would like to know is if there is a way to have the same behaviour, if Person adds an extra property that is not found in its interface.

```<code>interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
}
</code>```

and a Class:

```<code>public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
   public bool Alive { get; set; }  <---- This should prevent it from compiling as well.
}
</code>```

I would want it to not compile as well, or at the very least give me a compile warning.

答: No.  Interfaces define what members an object must implement.  They cannot define members that an object can't implement.  You could potentially use your own custom, or third party code analysis tools, to identify cases like this, but there is nothing in the language itself that would support it.

Body:
Let's say I have an interface:

interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
   bool Alive { get; set; }
}

and a Class:

public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
}

That would not compile since Person does not implement the Alive Property.

What I would like to know is if there is a way to have the same behaviour, if Person adds an extra property that is not found in its interface.

interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
}

and a Class:

public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
   public bool Alive { get; set; }  <---- This should prevent it from compiling as well.
}

I would want it to not compile as well, or at the very least give me a compile warning.


问:
SQL Splitting strings
I have the following two strings in a table:

```<code>CN=ABCDEFG,OU=7SOE,OU=TEMP,OU=Sydney,OU=Australia,DC=LDAP,DC=COM
CN=ABCDEFGHIJ,OU=7SOEFHU,OU=TEST,OU=TEMP,OU=London,OU=Europe,DC=LDAP,DC=COM
</code>```

I want to extract the following information from these two:

```<code>Sydney
London
</code>```

I started using RIGHT, SUBSTRING and CHARINDEX but couldn't get the pattern correct from the right splitting it up essentially via the 'OU=' from the right. Looks messy and can't see an elegant way of splitting strings as you could in C#. - SQL 2014.

答:
Looks like you want the next to last instance of OU=. Here's how you can do that.

```<code>declare @table table (c1 varchar(256))
insert into @table
values
('CN=ABCDEFG,OU=7SOE,OU=TEMP,OU=Sydney,OU=Australia,DC=LDAP,DC=COM'),
('CN=ABCDEFGHIJ,OU=7SOEFHU,OU=TEST,OU=TEMP,OU=London,OU=Europe,DC=LDAP,DC=COM')

select
    right(left(c1, len(c1) - charindex('UO',reverse(c1)) - 2),charindex('UO',reverse(left(c1, len(c1) - charindex('UO',reverse(c1)) - 2))) - 2)
from @table
</code>```

Just replace c1 and @table with your column name and table name, respectively.

If you want a slick way to split stuff, here is a function that will do that which is extremely fast, thanks to Jeff Moden.

```<code>CREATE FUNCTION [dbo].[DelimitedSplit8K] (@pString VARCHAR(8000), @pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE!  IT WILL KILL PERFORMANCE!

RETURNS TABLE WITH SCHEMABINDING AS
RETURN

/* "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
enough to cover VARCHAR(8000)*/

  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;

GO
</code>```

Here is how you could use it in your situation:

```<code>select
    t.c1
    ,x.ItemNumber                   --this represents the item number in the string.
    ,x.Item                         --this is the value of that item
    ,RN = row_number() over (partition by c1 order by x.ItemNumber desc)
from
    @table t
    cross apply
    dbo.DelimitedSplit8K(c1,',') x
--where
--  left(x.Item,2) = 'OU'           --uncomment this out to see how the RN will be used in the CTE below
order by
    t.c1,
    x.ItemNumber
</code>```

So, to only get the results you want, we would apply a row_number() only to those items which begin with OU and order them decending. Thus, the row_number() that = 2 (next to last) would be the value you want.

```<code>;with cte as(
select
    *
    ,RN = row_number() over (partition by c1 order by x.ItemNumber desc)
from
    @table
    cross apply
    dbo.DelimitedSplit8K(c1,',') x
where
    left(x.Item,2) = 'OU')

select
    c1,
    YourExtract = right(Item,len(Item) - 3)
from
    cte
where
    RN = 2
</code>```

Title: SQL Splitting strings

Body:
I have the following two strings in a table:

CN=ABCDEFG,OU=7SOE,OU=TEMP,OU=Sydney,OU=Australia,DC=LDAP,DC=COM
CN=ABCDEFGHIJ,OU=7SOEFHU,OU=TEST,OU=TEMP,OU=London,OU=Europe,DC=LDAP,DC=COM

I want to extract the following information from these two:

Sydney
London

I started using RIGHT, SUBSTRING and CHARINDEX but couldn't get the pattern correct from the right splitting it up essentially via the 'OU=' from the right. Looks messy and can't see an elegant way of splitting strings as you could in C#. - SQL 2014.

Body:
Looks like you want the next to last instance of OU=. Here's how you can do that.

declare @table table (c1 varchar(256))
insert into @table
values
('CN=ABCDEFG,OU=7SOE,OU=TEMP,OU=Sydney,OU=Australia,DC=LDAP,DC=COM'),
('CN=ABCDEFGHIJ,OU=7SOEFHU,OU=TEST,OU=TEMP,OU=London,OU=Europe,DC=LDAP,DC=COM')

select
    right(left(c1, len(c1) - charindex('UO',reverse(c1)) - 2),charindex('UO',reverse(left(c1, len(c1) - charindex('UO',reverse(c1)) - 2))) - 2)
from @table

Just replace c1 and @table with your column name and table name, respectively.

If you want a slick way to split stuff, here is a function that will do that which is extremely fast, thanks to Jeff Moden.

CREATE FUNCTION [dbo].[DelimitedSplit8K] (@pString VARCHAR(8000), @pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE!  IT WILL KILL PERFORMANCE!

RETURNS TABLE WITH SCHEMABINDING AS
RETURN

/* "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
enough to cover VARCHAR(8000)*/

  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;

GO

Here is how you could use it in your situation:

select
    t.c1
    ,x.ItemNumber                   --this represents the item number in the string.
    ,x.Item                         --this is the value of that item
    ,RN = row_number() over (partition by c1 order by x.ItemNumber desc)
from
    @table t
    cross apply
    dbo.DelimitedSplit8K(c1,',') x
--where
--  left(x.Item,2) = 'OU'           --uncomment this out to see how the RN will be used in the CTE below
order by
    t.c1,
    x.ItemNumber

So, to only get the results you want, we would apply a row_number() only to those items which begin with OU and order them decending. Thus, the row_number() that = 2 (next to last) would be the value you want.

;with cte as(
select
    *
    ,RN = row_number() over (partition by c1 order by x.ItemNumber desc)
from
    @table
    cross apply
    dbo.DelimitedSplit8K(c1,',') x
where
    left(x.Item,2) = 'OU')

select
    c1,
    YourExtract = right(Item,len(Item) - 3)
from
    cte
where
    RN = 2


问:
Any good 2d engines with a GUI system?
I'm trying to develop a simple app ( it will resemble something like a powerpoint presentation) that will require some simple GUI controls: button, textbox, slider and listbox.

And i would want to be able to skin the controls.
So i'm looking for an easy to learn 2d engine that will aid me in doing what i want.

Any recommendation for such engine?

It can be in python or .net (xna) preferable or if not c/c++ will be ok i guess.

L.E.: I'm looking for a graphic rendering engine that has specified gui controls available.
For example Irrlicht.

答:
I am not fully sure what the requirement is. Are you trying to render GUI widgets using some 2D engine, or are you looking for GUI library that also has 2D graphics support?
Most GUI libraries have decent graphics support. See Java's 2D Graphics tutorial for example. For skin, take a look at Java's Substance or Modzilla XUL Runner and its star child Songbird.

If you want to do more, you could embed OpenGL into WinForm, Java, Delphi, etc.  See Creating an OpenGL view on a Windows Form.

OwnerDisplayName: daniels

Title: Any good 2d engines with a GUI system?

LastEditorDisplayName: daniels


问:
Mercurial: Exclude django settings.py after intitial commit
In my Django project, I want the settings.py file to be included in the initial commit so that other developers can clone the repository and change the original settings to work with there local setup. But, after that I don't want to manually exclude the file at every commit, and the ignore file wont work because it's already tracked.

So, how can I get mercurial to automatically exclude the settings.py while maintaining the original file tracked?

Appreciate any help :)

答:
There is an alternative, probably more flexible approach to this. Don't exclude the settings.py file.

Instead, do something like this:

```<code>try:
  from localsettings import *
except ImportError:
  pass
</code>```

That way, if you ever need to actually change your settings.py file, others can pick up the changes. You can supply reasonable defaults, so long as any settings you may want to override locally are above the localsettings import.

You can change your localsettings.py file as much as you need (I tend to use it for turning on DEBUG, setting my database settings, and making sure I'm just using local memory as my cache backend).

Just make sure you exclude the localsettings.py file from your commits.

Body:
There is an alternative, probably more flexible approach to this. Don't exclude the settings.py file.

Instead, do something like this:

try:
  from localsettings import *
except ImportError:
  pass

That way, if you ever need to actually change your settings.py file, others can pick up the changes. You can supply reasonable defaults, so long as any settings you may want to override locally are above the localsettings import.

You can change your localsettings.py file as much as you need (I tend to use it for turning on DEBUG, setting my database settings, and making sure I'm just using local memory as my cache backend).

Just make sure you exclude the localsettings.py file from your commits.


问:
get first letter of a String (sentence) given in a column and create a new column in python
I have a column in pandas dataframe which has items like following,

```<code>SubBrand
Sam William Mathew
Jonty Rodes
Chris Gayle
</code>```

I want to create a new column (SubBrand_new) such as

```<code>  SubBrand_new
0 SWM
1 JR
2 CG
</code>```

I am using this piece of code,

```<code>df1["SubBrand_new"] = "".join([x[0] for x in (df1["SubBrand"].str.split())])
</code>```

but not able to get what I am looking for. Can anybody help?

答:
We can do split with expand and sum i.e </p>

```<code>df['SubBrand'].str.split(expand=True).apply(lambda x : x.str[0]).fillna('').sum(1)

0    SWM
1     JR
2     CG
dtype: object
</code>```

Body:
I have a column in pandas dataframe which has items like following,

SubBrand
Sam William Mathew
Jonty Rodes
Chris Gayle

I want to create a new column (SubBrand_new) such as

  SubBrand_new
0 SWM
1 JR
2 CG

I am using this piece of code,

df1["SubBrand_new"] = "".join([x[0] for x in (df1["SubBrand"].str.split())])

but not able to get what I am looking for. Can anybody help?

Body:
We can do split with expand and sum i.e

df['SubBrand'].str.split(expand=True).apply(lambda x : x.str[0]).fillna('').sum(1)

0    SWM
1     JR
2     CG
dtype: object


问:
Java generics - compile error on method parameter and method return type
Say I've got two interfaces:

```<code>public interface IObjectOne<T>
{
    List<T> digest(final List<T> myList);
}

public interface IObjectTwo<T>
{
    List<T> create();
}
</code>```

And an object which manages concrete implementations of these two interfaces, which must work over the same type.

```<code>public class Entity<T>
{
  private IObjectOne<T> objectOne;
  private IObjectTwo<T> objectTwo;

  ... setters

  public IObjectOne<T> getObjectOne() {
     return objectOne;
  }

  public IObjectTwo<T> getObjectTwo() {
     return objectTwo;
  }
}
</code>```

These Entitys are stored in a Map, and I retrive one of them by a key:

```<code>final Entity<?> entity = entities.get(key);
</code>```

Why cannot I do that?

```<code>entity.getObjectOne().digest(entity.getObjectTwo().create());
</code>```

答:
Here:

```<code>final Entity<?> entity = entities.get(key);
</code>```

you are saying: you absolutely do not care about the exact type of an entity. Reminder: wildcard means "I don't know" about the exact type.

And one consequence of using the wildcard for generics, as described here:

If you want to enforce some relationship on the different types of method arguments, you can't do that with wildcards, you have to use type parameters.

In other words: by using the wildcard like this, the compiler is unable to correlate the generic types.

Body:
Say I've got two interfaces:

public interface IObjectOne<T>
{
    List<T> digest(final List<T> myList);
}

public interface IObjectTwo<T>
{
    List<T> create();
}

And an object which manages concrete implementations of these two interfaces, which must work over the same type.

public class Entity<T>
{
  private IObjectOne<T> objectOne;
  private IObjectTwo<T> objectTwo;

  ... setters

  public IObjectOne<T> getObjectOne() {
     return objectOne;
  }

  public IObjectTwo<T> getObjectTwo() {
     return objectTwo;
  }
}

These Entitys are stored in a Map, and I retrive one of them by a key:

final Entity<?> entity = entities.get(key);

Why cannot I do that?

entity.getObjectOne().digest(entity.getObjectTwo().create());

Body:
Here:

final Entity<?> entity = entities.get(key);

you are saying: you absolutely do not care about the exact type of an entity. Reminder: wildcard means "I don't know" about the exact type.

And one consequence of using the wildcard for generics, as described here:

If you want to enforce some relationship on the different types of method arguments, you can't do that with wildcards, you have to use type parameters.

In other words: by using the wildcard like this, the compiler is unable to correlate the generic types.


问:
Set a Property in a ViewModel from Another ViewModel
I am trying to pass a value to a view model from another view model before navigating to the page attached to that view model.
I was previously passing it to the view, then passing it to the view model. This seems like a clumsy way of doing things.
I am not using any kind of framework so that is not an option.
At the moment the property is set as static and this works but im not sure if this is good practice.
The code:

View model 1:

This command opens the new page:

```<code>public void OpenRouteDetails()
{
   RouteStopPopOverViewModel.RouteName = "TestRoute";
   App.Page.Navigation.PushAsync(new RouteStopPopOverView());
}
</code>```

View model 2: (RouteStopPopOverViewModel)

```<code>public static string RouteName { get; set; }
</code>```

This does work but I would prefer not to use static as a way to achieve this.
Is there some way to set the RouteName property without using static or passing it through view-> view model.
I have seen some answers about this but they don't seem to answer to question clearly.

答:
If there is a hierarchy you could express that in a parent to both of them.</p>

```<code>public class Route
{
    private string Name;
}

public class RouteSelectedArgs : EventArgs
{
    public Route Selected { get; set; }
}

public interface IRouteSelection
{
    event EventHandler<RouteSelectedArgs> RouteSelected;
}

public interface IRouteDetails { }

public class RouteWizard
{
    public UserControl view { get; set; }

    private IRouteSelection _selection;
    private IRouteDetails _details;

    public RouteWizard(IRouteSelection selection, IRouteDetails details)
    {
        _selection = selection;
        _details = details;
        _selection.RouteSelected += Selection_RouteSelected;
        view = MakeView(_selection);
    }

    private void Selection_RouteSelected(object sender, RouteSelectedArgs e)
    {
        _selection.RouteSelected -= Selection_RouteSelected;
        view = MakeView(_details, e.Selected);

    }

    private UserControl MakeView(params object[] args)
    {
        ////magic
        throw new NotImplementedException();
    }
}
</code>```

Body:
I am trying to pass a value to a view model from another view model before navigating to the page attached to that view model.
I was previously passing it to the view, then passing it to the view model. This seems like a clumsy way of doing things.
I am not using any kind of framework so that is not an option.
At the moment the property is set as static and this works but im not sure if this is good practice.
The code:

View model 1:

This command opens the new page:

public void OpenRouteDetails()
{
   RouteStopPopOverViewModel.RouteName = "TestRoute";
   App.Page.Navigation.PushAsync(new RouteStopPopOverView());
}

View model 2: (RouteStopPopOverViewModel)

public static string RouteName { get; set; }

This does work but I would prefer not to use static as a way to achieve this.
Is there some way to set the RouteName property without using static or passing it through view-> view model.
I have seen some answers about this but they don't seem to answer to question clearly.

Body:
If there is a hierarchy you could express that in a parent to both of them.

public class Route
{
    private string Name;
}

public class RouteSelectedArgs : EventArgs
{
    public Route Selected { get; set; }
}

public interface IRouteSelection
{
    event EventHandler<RouteSelectedArgs> RouteSelected;
}

public interface IRouteDetails { }

public class RouteWizard
{
    public UserControl view { get; set; }

    private IRouteSelection _selection;
    private IRouteDetails _details;

    public RouteWizard(IRouteSelection selection, IRouteDetails details)
    {
        _selection = selection;
        _details = details;
        _selection.RouteSelected += Selection_RouteSelected;
        view = MakeView(_selection);
    }

    private void Selection_RouteSelected(object sender, RouteSelectedArgs e)
    {
        _selection.RouteSelected -= Selection_RouteSelected;
        view = MakeView(_details, e.Selected);

    }

    private UserControl MakeView(params object[] args)
    {
        ////magic
        throw new NotImplementedException();
    }
}


问:
Updating a wp_postmeta field not working in wordpress
I cannot update a wp_postmeta field called 'alive_days' and making its value equal to zero, in wordpress. I have tried all the two following solutions but still not working:

$alive_days='alive_days';$mypostid=$_REQUEST['pid'];

global $wpdb;

$wpdb->query("update
  $wpdb->wp_postmeta set meta_value==\"$ziro\" where
  post_id=\"$mypostid\" and meta_key=\"$alive_days\"");

$ziro=0;

$mypostid=$_REQUEST['pid'];

update_post_meta($mypostid, 'alive_days',$ziro);

The field value will not change after the execution.

答:
try with this code</p>

```<code>update_post_meta( $post_id,'alive_days', 0 );
</code>```

Body:
try with this code

update_post_meta( $post_id,'alive_days', 0 );


问:
With pure JavaScript, is there an easy way to attach an event listener to a class?
I'm looking for the JavaScript equivalent of

```<code>$(".class-name").on(eventName, eventHandler);
</code>```

first I tried

```<code>document.querySelectorAll(".class-name").addEventListener(eventName, eventHandler);
</code>```

but it didn't work. Is there an easy way to do it in JavaScript?

------Update------

Many answers suggested a loop, but originally I was looking for a solution with a single listener to save memory (suppose I had 1000 items in that class).
However, one answer reminded me: does the jQuery version also create 1000 listeners in the memory?

答:
Store all elements in array and bind event to all of them. Here document.getElementsByClassName returns array of element having class class-name.

var classes= document.getElementsByClassName("class-name");

 Array.from(classes).forEach(function(element) {
      element.addEventListener('click', function(){alert('clicked'+   this.innerHTML)});
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="class-name">
First div  1
</div>

<div class="class-name">
Second div    2
</div>

<div class="class-name">
third div   3
</div>
.
.
.
<div class="class-name">
nth div     n
</div></code>```

Edit

getElementsByClassName doesnt return an array, but a HTMLCollection in most, or a NodeList is some browsers (Mozila ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)

Body:
I'm looking for the JavaScript equivalent of

$(".class-name").on(eventName, eventHandler);

first I tried

document.querySelectorAll(".class-name").addEventListener(eventName, eventHandler);

but it didn't work. Is there an easy way to do it in JavaScript?

------Update------

Many answers suggested a loop, but originally I was looking for a solution with a single listener to save memory (suppose I had 1000 items in that class).
However, one answer reminded me: does the jQuery version also create 1000 listeners in the memory?

Body:
Store all elements in array and bind event to all of them. Here document.getElementsByClassName returns array of element having class class-name.

var classes= document.getElementsByClassName("class-name");

 Array.from(classes).forEach(function(element) {
      element.addEventListener('click', function(){alert('clicked'+   this.innerHTML)});
    });

<div class="class-name">
First div  1
</div>

<div class="class-name">
Second div    2
</div>

<div class="class-name">
third div   3
</div>
.
.
.
<div class="class-name">
nth div     n
</div>

Edit

getElementsByClassName doesnt return an array, but a HTMLCollection in most, or a NodeList is some browsers (Mozila ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)


答:
The issues is querySelectorAll returns a nodeList, if you only looked for one class using querySelector, your code would work, but only bind to one element.

Option 1: Iterate over NodeList + Bind

One option is to iterate over all the nodes in the nodelist and bind the event to them:

let eventName = 'click';
let elements  = document.querySelectorAll('.foo');
[...elements].forEach(el=>el.addEventListener(eventName, eventHandler));

function eventHandler (){
  console.log(`Clicked: "${this.textContent}"`);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="foo">Click Me</div>
<div class="foo">Or this</div></code>```

Note: the above uses ES6 syntax, if you need an iteration method that is a little more compliant, you can try:
[].forEach.call(elements, function(el) { ... });

Option 2: Bind Once to Common Ancestor

Another option would be to find the closest common ancestor and bind one event to that, then see if the class you care about is the target and call the function, if so.

Title: With pure JavaScript, is there an easy way to attach an event listener to a class?

Body:
The issues is querySelectorAll returns a nodeList, if you only looked for one class using querySelector, your code would work, but only bind to one element.

Option 1: Iterate over NodeList + Bind

One option is to iterate over all the nodes in the nodelist and bind the event to them:

let eventName = 'click';
let elements  = document.querySelectorAll('.foo');
[...elements].forEach(el=>el.addEventListener(eventName, eventHandler));

function eventHandler (){
  console.log(`Clicked: "${this.textContent}"`);
}

<div class="foo">Click Me</div>
<div class="foo">Or this</div>

Note: the above uses ES6 syntax, if you need an iteration method that is a little more compliant, you can try:
[].forEach.call(elements, function(el) { ... });

Option 2: Bind Once to Common Ancestor

Another option would be to find the closest common ancestor and bind one event to that, then see if the class you care about is the target and call the function, if so.


答:
How are you creating the Map<String, Entity<YOUR_TYPE>>

You should parameterize your Entity<> since it is generic.

```<code>Map<String, Entity<YOUR_TYPE>> entities = new HashMap<>();
final Entity<YourType> entity = entities.get(key);
</code>```

Title: Java generics - compile error on method parameter and method return type

Body:
How are you creating the Map<String, Entity<YOUR_TYPE>>

You should parameterize your Entity<> since it is generic.

Map<String, Entity<YOUR_TYPE>> entities = new HashMap<>();
final Entity<YourType> entity = entities.get(key);


问:
tflearn KeyError: '[23566... not in index exception
I am using tflearn to build a simple neural network and passing the public adult income data to it for training. When I get the error:

```<code>Exception in thread Thread-6:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tflearn/data_flow.py", line 187, in fill_feed_dict_queue
    data = self.retrieve_data(batch_ids)
  File "/usr/local/lib/python2.7/dist-packages/tflearn/data_flow.py", line 222, in retrieve_data
    utils.slice_array(self.feed_dict[key], batch_ids)
  File "/usr/local/lib/python2.7/dist-packages/tflearn/utils.py", line 187, in slice_array
    return X[start]
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 1958, in __getitem__
    return self._getitem_array(key)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 2002, in _getitem_array
    indexer = self.loc._convert_to_indexer(key, axis=1)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexing.py", line 1231, in _convert_to_indexer
    raise KeyError('%s not in index' % objarr[mask])
KeyError: '[23566 22547 27149 12793 17126 30292 18889 15170 31777  8499 24748 15401\n  7317 11624  8017 10984] not in index'
</code>```

Here is my code:

```<code>import pandas as pd
import copy
df_train = pd.read_csv('adult.data', header = None)
X_train_orig = df_train.drop(df_train.columns[[14]], axis=1, inplace=False)
Y_train_orig = df_train[[14]]
df_test = pd.read_csv('adult.test', header = None)
X_test_orig = df_test.drop(df_test.columns[[14]], axis=1, inplace=False)
Y_test_orig = df_test[[14]]
dataset = pd.concat(objs=[X_train_orig, X_test_orig], axis = 0)
data = pd.get_dummies(dataset)              # get one hot encoding
X_train = copy.copy(data[:len(X_train_orig)])
X_test = copy.copy(data[len(X_train_orig):])
Y_train = pd.get_dummies(Y_train_orig)      # get one hot encoding
Y_test = pd.get_dummies(Y_test_orig)        # get one hot encoding
print "X train shape = " + str(X_train.shape)
print "Y train shape = " + str(Y_train.shape)
print "X test shape = " + str(X_test.shape)
print "Y test  shape = " + str(Y_test.shape)
import tflearn
import tensorflow as tf
tf.reset_default_graph()
network = tflearn.input_data([None, 108])
network = tflearn.fully_connected(network, 10)
network = tflearn.fully_connected(network, 10)
network = tflearn.fully_connected(network, 2, activation='softmax')
network = tflearn.regression(network, loss='categorical_crossentropy')
model = tflearn.DNN(network)
model.fit(X_train, Y_train, show_metric=True, batch_size=16, n_epoch=5000, snapshot_epoch=False)
</code>```

I am already doing:

```<code>import tensorflow as tf
tf.reset_default_graph()
</code>```

as suggested by some related posts. What am I missing here?

答:
I have had the same problem.

I found this solution: https://github.com/fchollet/keras/issues/2262

It states that you need to convert your input to numpy arrays. If you do this when you call fit:

```<code>model.fit(np.array(X_train), np.array(Y_train), show_metric=True, batch_size=16, n_epoch=5000, snapshot_epoch=False)
</code>```

Hope it solves your problem.

Body:
I am using tflearn to build a simple neural network and passing the public adult income data to it for training. When I get the error:

Exception in thread Thread-6:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tflearn/data_flow.py", line 187, in fill_feed_dict_queue
    data = self.retrieve_data(batch_ids)
  File "/usr/local/lib/python2.7/dist-packages/tflearn/data_flow.py", line 222, in retrieve_data
    utils.slice_array(self.feed_dict[key], batch_ids)
  File "/usr/local/lib/python2.7/dist-packages/tflearn/utils.py", line 187, in slice_array
    return X[start]
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 1958, in __getitem__
    return self._getitem_array(key)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 2002, in _getitem_array
    indexer = self.loc._convert_to_indexer(key, axis=1)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexing.py", line 1231, in _convert_to_indexer
    raise KeyError('%s not in index' % objarr[mask])
KeyError: '[23566 22547 27149 12793 17126 30292 18889 15170 31777  8499 24748 15401\n  7317 11624  8017 10984] not in index'

Here is my code:

import pandas as pd
import copy
df_train = pd.read_csv('adult.data', header = None)
X_train_orig = df_train.drop(df_train.columns[[14]], axis=1, inplace=False)
Y_train_orig = df_train[[14]]
df_test = pd.read_csv('adult.test', header = None)
X_test_orig = df_test.drop(df_test.columns[[14]], axis=1, inplace=False)
Y_test_orig = df_test[[14]]
dataset = pd.concat(objs=[X_train_orig, X_test_orig], axis = 0)
data = pd.get_dummies(dataset)              # get one hot encoding
X_train = copy.copy(data[:len(X_train_orig)])
X_test = copy.copy(data[len(X_train_orig):])
Y_train = pd.get_dummies(Y_train_orig)      # get one hot encoding
Y_test = pd.get_dummies(Y_test_orig)        # get one hot encoding
print "X train shape = " + str(X_train.shape)
print "Y train shape = " + str(Y_train.shape)
print "X test shape = " + str(X_test.shape)
print "Y test  shape = " + str(Y_test.shape)
import tflearn
import tensorflow as tf
tf.reset_default_graph()
network = tflearn.input_data([None, 108])
network = tflearn.fully_connected(network, 10)
network = tflearn.fully_connected(network, 10)
network = tflearn.fully_connected(network, 2, activation='softmax')
network = tflearn.regression(network, loss='categorical_crossentropy')
model = tflearn.DNN(network)
model.fit(X_train, Y_train, show_metric=True, batch_size=16, n_epoch=5000, snapshot_epoch=False)

I am already doing:

import tensorflow as tf
tf.reset_default_graph()

as suggested by some related posts. What am I missing here?

Body:
I have had the same problem.

I found this solution: https://github.com/fchollet/keras/issues/2262

It states that you need to convert your input to numpy arrays. If you do this when you call fit:

model.fit(np.array(X_train), np.array(Y_train), show_metric=True, batch_size=16, n_epoch=5000, snapshot_epoch=False)

Hope it solves your problem.