问:
MySql syntax error on procedure parameter
I am trying to write a simple procedure but am encountering a syntax error at the first parameter. As best I can tell I'm following the syntax of CREATE PROCEDURE correctly.

I am limited to accessing my database with phpMyAdmin. Here is the create script I'm trying to run:

```<code>DROP PROCEDURE IF EXISTS product_index_swap/
CREATE PROCEDURE product_index_swap (@id INT, @oldIndex INT, @newIndex INT)
BEGIN
    DECLARE @swapID;
    SET @swapID = (SELECT `id` FROM `product` WHERE `order_index` = @newIndex LIMIT 1);
    UPDATE `products` SET `order_index` = (CASE WHEN `id` = @id THEN @newIndex
                                                WHEN `id` = @swapID THEN @oldIndex END)
    WHERE `id` IN (@id, @swapID);
END
</code>```

I am using the option on phpMyAdmin to change the delimiter to /.

I receive a syntax error "near '@id INT, @oldIndex INT....". I thought I may encounter more delimiter errors since I'm not entirely clear on the scope of them. I believe if that was the problem the error would be on a new line in the procedure when it failed to understand a semicolon, not at the parameters declaration.

答:
You're using the Microsoft SQL Server convention of putting @ before all the parameters and local variables. MySQL doesn't do this.

In MySQL syntax, procedure parameters have no sigil.

Also parameters are typically declared IN or OUT or INOUT.

```<code>CREATE PROCEDURE product_index_swap (IN id INT, IN oldIndex INT, IN newIndex INT)
BEGIN
    DECLARE swapID;
    ...
</code>```

MySQL variables that have the @ sigil are session variables.

See also:

https://dev.mysql.com/doc/refman/5.7/en/create-procedure.html

https://dev.mysql.com/doc/refman/5.7/en/declare-local-variable.html

https://dev.mysql.com/doc/refman/5.7/en/set-variable.html

Body:
I am trying to write a simple procedure but am encountering a syntax error at the first parameter. As best I can tell I'm following the syntax of CREATE PROCEDURE correctly.

I am limited to accessing my database with phpMyAdmin. Here is the create script I'm trying to run:

DROP PROCEDURE IF EXISTS product_index_swap/
CREATE PROCEDURE product_index_swap (@id INT, @oldIndex INT, @newIndex INT)
BEGIN
    DECLARE @swapID;
    SET @swapID = (SELECT `id` FROM `product` WHERE `order_index` = @newIndex LIMIT 1);
    UPDATE `products` SET `order_index` = (CASE WHEN `id` = @id THEN @newIndex
                                                WHEN `id` = @swapID THEN @oldIndex END)
    WHERE `id` IN (@id, @swapID);
END

I am using the option on phpMyAdmin to change the delimiter to /.

I receive a syntax error "near '@id INT, @oldIndex INT....". I thought I may encounter more delimiter errors since I'm not entirely clear on the scope of them. I believe if that was the problem the error would be on a new line in the procedure when it failed to understand a semicolon, not at the parameters declaration.

Body:
You're using the Microsoft SQL Server convention of putting @ before all the parameters and local variables. MySQL doesn't do this.

In MySQL syntax, procedure parameters have no sigil.

Also parameters are typically declared IN or OUT or INOUT.

CREATE PROCEDURE product_index_swap (IN id INT, IN oldIndex INT, IN newIndex INT)
BEGIN
    DECLARE swapID;
    ...

MySQL variables that have the @ sigil are session variables.

See also:

https://dev.mysql.com/doc/refman/5.7/en/create-procedure.html

https://dev.mysql.com/doc/refman/5.7/en/declare-local-variable.html

https://dev.mysql.com/doc/refman/5.7/en/set-variable.html


来源: stackexchange

问:
If statement syntax error in JS
I am trying to use an if/else and I can't figure out where I'm going wrong with the syntax. I want the payload to only submit school_ids if the role isn't p_admin. Thank you for your help!

```<code>const createUser = (payload) => request.postJSON(
    '/register',
    excludeObjNullValue({
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
        if (role !== 'p_admin'){
        school_ids: payload.schoolIds
        }
    })
);
</code>```

答:
I see 2-3 options depending on your excludeObjNullValue function:

You can either break that expression up in to a couple of statements, or

Or use property spread notation and the conditional operator, or

If excludeObjNullValue does what the name suggests, you can use a conditional without spread notation and rely on excludeObjNullValue to exclude it

Option 3 may well be your best bet, but I'll give them in order:

Option 1: The multi-statement way:

```<code>const createUser = (payload) => {
    const options = {
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
    };
    if (role !== 'p_admin') {
        options.school_ids = payload.schoolIds;
    }
    return request.postJSON('/register', excludeObjNullValue(options));
};
</code>```

Option 2: Property spread and the conditional operator

Property spread is a Stage 3 proposal but support for it is already shipping in Chrome and Firefox, and if you're transpiling you can tell your transpiler to support it. That would look like this:

```<code>const createUser = (payload) => request.postJSON(
    '/register',
    excludeObjNullValue({
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
        {...(role !== 'p_admin' ? {school_ids: payload.schoolIds} : {}}
        }
    })
);
</code>```

Whether it's a good idea even if supported is your call. :-) It does briefly create an extra object and iterator.

Option 3: Rely on excludeObjNullValue to exclude properties with null values:

If it really does what the name suggests, then it will remove school_ids if we give the value null to it. So:

```<code>const createUser = (payload) => request.postJSON(
    '/register',
    excludeObjNullValue({
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
        school_ids: role !== 'p_admin' ? payload.schoolIds : null
        }
    })
);
</code>```

ContentLicense: CC BY-SA 3.0

Title: If statement syntax error in JS

Body:
I am trying to use an if/else and I can't figure out where I'm going wrong with the syntax. I want the payload to only submit school_ids if the role isn't p_admin. Thank you for your help!

const createUser = (payload) => request.postJSON(
    '/register',
    excludeObjNullValue({
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
        if (role !== 'p_admin'){
        school_ids: payload.schoolIds
        }
    })
);

Body:
I see 2-3 options depending on your excludeObjNullValue function:

You can either break that expression up in to a couple of statements, or

Or use property spread notation and the conditional operator, or

If excludeObjNullValue does what the name suggests, you can use a conditional without spread notation and rely on excludeObjNullValue to exclude it

Option 3 may well be your best bet, but I'll give them in order:

Option 1: The multi-statement way:

const createUser = (payload) => {
    const options = {
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
    };
    if (role !== 'p_admin') {
        options.school_ids = payload.schoolIds;
    }
    return request.postJSON('/register', excludeObjNullValue(options));
};

Option 2: Property spread and the conditional operator

Property spread is a Stage 3 proposal but support for it is already shipping in Chrome and Firefox, and if you're transpiling you can tell your transpiler to support it. That would look like this:

const createUser = (payload) => request.postJSON(
    '/register',
    excludeObjNullValue({
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
        {...(role !== 'p_admin' ? {school_ids: payload.schoolIds} : {}}
        }
    })
);

Whether it's a good idea even if supported is your call. :-) It does briefly create an extra object and iterator.

Option 3: Rely on excludeObjNullValue to exclude properties with null values:

If it really does what the name suggests, then it will remove school_ids if we give the value null to it. So:

const createUser = (payload) => request.postJSON(
    '/register',
    excludeObjNullValue({
        username: payload.username,
        email: payload.email,
        password: payload.password,
        first_name: payload.firstName,
        last_name: payload.lastName,
        role: payload.role,
        district_id: payload.districtId,
        school_ids: role !== 'p_admin' ? payload.schoolIds : null
        }
    })
);


问:
Translate multiple numbers enclosed within double quotes (XSLT 1.0)
Is it possible to process a variable with multiple numbers enclosed within double quotes? Ie. Translate function in xslt 1.0 returns an error when I translate the quote to a period. A sequence of more than one item is not allowed as the first argument of translate() ("2", "1", ”1”)

I would like (“2”,”1”,”1”) translated to (.2.1.1.)

XML

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<Project type="cim" version="0.1">
   <Projects>
     <WBSs>
       <WBS GUID=”2”>
         <WBSs>
            <WBS GUID=”1”>
             </WBS>
               <WBSs>
                <WBS GUID=”1”>
                </WBS>
              </WBSs>
            <WBS GUID=”2”>
            </WBS>
            <WBS GUID=”3”>
              <WBSs>
                <WBS GUID=”4”>
                </WBS>
              </WBSs>
            </WBS>
         </WBSs>
       <WBS GUID=”4”>
          <WBSs>
            <WBS GUID=”5”>
            </WBS>
            <WBS GUID=”8”>
            </WBS>
            <WBS GUID=”2”>
            </WBS>
            <WBS GUID=”10”>
            </WBS>
         </WBSs>
       </WBS>
     </WBSs>
   </Projects>
</Project>
</code>```

xslt

```<code><xsl:variable name="NETWORK ">
  <xsl:apply-templates select=".//WBS" mode="I_NETWORK">
    <xsl:with-param name="ProjectId" select="$ProjectId"/>
  </xsl:apply-templates>
</xsl:variable>

<xsl:template match="WBS" mode="I_NETWORK">
  <xsl:param name="ProjectId"/>

<xsl:variable name="wbsCode" select="@GUID"/>
<xsl:variable name="quot">"</xsl:variable>

<xsl:variable name="var1">
  <xsl:value-of select="translate($wbsCode,$quot,'.')"/>

</xsl:template>
</code>```

答:
```<code>You have to use the real double quotes in your XML, "2", rather than the curvy double quotes, “2”.  Once you have real double quotes in XML use the escape character to do your translate.  Your editor may be putting the curvy double quotes in.

<xsl:variable name="test">
  <xsl:value-of select="'("2","1","1")'"/>
</xsl:variable>

<xsl:variable name="result">
  <xsl:value-of select="translate($test,'"','.')"/>
</xsl:variable>
</code>```

Body:
Is it possible to process a variable with multiple numbers enclosed within double quotes? Ie. Translate function in xslt 1.0 returns an error when I translate the quote to a period. A sequence of more than one item is not allowed as the first argument of translate() ("2", "1", ”1”)

I would like (“2”,”1”,”1”) translated to (.2.1.1.)

XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<Project type="cim" version="0.1">
   <Projects>
     <WBSs>
       <WBS GUID=”2”>
         <WBSs>
            <WBS GUID=”1”>
             </WBS>
               <WBSs>
                <WBS GUID=”1”>
                </WBS>
              </WBSs>
            <WBS GUID=”2”>
            </WBS>
            <WBS GUID=”3”>
              <WBSs>
                <WBS GUID=”4”>
                </WBS>
              </WBSs>
            </WBS>
         </WBSs>
       <WBS GUID=”4”>
          <WBSs>
            <WBS GUID=”5”>
            </WBS>
            <WBS GUID=”8”>
            </WBS>
            <WBS GUID=”2”>
            </WBS>
            <WBS GUID=”10”>
            </WBS>
         </WBSs>
       </WBS>
     </WBSs>
   </Projects>
</Project>

xslt

<xsl:variable name="NETWORK ">
  <xsl:apply-templates select=".//WBS" mode="I_NETWORK">
    <xsl:with-param name="ProjectId" select="$ProjectId"/>
  </xsl:apply-templates>
</xsl:variable>

<xsl:template match="WBS" mode="I_NETWORK">
  <xsl:param name="ProjectId"/>

<xsl:variable name="wbsCode" select="@GUID"/>
<xsl:variable name="quot">"</xsl:variable>

<xsl:variable name="var1">
  <xsl:value-of select="translate($wbsCode,$quot,'.')"/>

</xsl:template>

Body:
You have to use the real double quotes in your XML, "2", rather than the curvy double quotes, “2”.  Once you have real double quotes in XML use the escape character to do your translate.  Your editor may be putting the curvy double quotes in.

<xsl:variable name="test">
  <xsl:value-of select="'(&quot;2&quot;,&quot;1&quot;,&quot;1&quot;)'"/>
</xsl:variable>

<xsl:variable name="result">
  <xsl:value-of select="translate($test,'&quot;','.')"/>
</xsl:variable>


问:
MongoDB - shutting down with code:100
I've been trying to set up MongoDB on my Ubuntu 16.04.2 LTS (GNU/Linux 4.4.0-22-generic x86_64) VPS and I've been running into a few problems. I am running as a user on my server that has root access but not using the root account itself.

I started to notice the problem when I was executing db.createUser() on the admin database so I could add other users and I was getting this error:
not authorized to execute command

So I then proceeded to uninstall and install again using the tutorial as provided on the website: https://docs.mongodb.com/v3.2/tutorial/install-mongodb-on-ubuntu/

Now when I'm on stage 2 Verify that MongoDB has started successfully on the Run MongoDB Community Edition section, that is I look at my output from the file /var/log/mongodb/mongod.log, I get the following:

```<code>2017-04-14T14:23:09.309+0200 I CONTROL  [main] ***** SERVER RESTARTED *****
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] MongoDB starting : pid=9691 port=27017 dbpath=/var/lib/mongodb 64-bit host=vps338741
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] db version v3.4.3
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] git version: f07437fb5a6cca07c10bafa78365456eb1d6d5e1
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.2g  1 Mar 2016
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] allocator: tcmalloc
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] modules: none
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] build environment:
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten]     distmod: ubuntu1604
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten]     distarch: x86_64
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten]     target_arch: x86_64
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1", port: 27017 }, storage: { dbPath: "/var/lib/mongodb", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log", quiet: true } }
2017-04-14T14:23:09.349+0200 I STORAGE  [initandlisten]
2017-04-14T14:23:09.349+0200 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-04-14T14:23:09.349+0200 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-04-14T14:23:09.349+0200 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=464M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2017-04-14T14:23:09.366+0200 E STORAGE  [initandlisten] WiredTiger error (2) [1492172589:366629][9691:0x7f1755946cc0], file:WiredTiger.wt, connection: /var/lib/mongodb/WiredTiger.wt: handle-open: open: No such file or directory
2017-04-14T14:23:09.367+0200 I -        [initandlisten] Assertion: 28595:2: No such file or directory src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp 267
2017-04-14T14:23:09.367+0200 I STORAGE  [initandlisten] exception in initAndListen: 28595 2: No such file or directory, terminating
2017-04-14T14:23:09.367+0200 I NETWORK  [initandlisten] shutdown: going to close listening sockets...
2017-04-14T14:23:09.367+0200 I NETWORK  [initandlisten] removing socket file: /tmp/mongodb-27017.sock
2017-04-14T14:23:09.367+0200 I NETWORK  [initandlisten] shutdown: going to flush diaglog...
2017-04-14T14:23:09.367+0200 I CONTROL  [initandlisten] now exiting
2017-04-14T14:23:09.367+0200 I CONTROL  [initandlisten] shutting down with code:100
</code>```

I've looked around and it is not the same error as found here, because that is to do with the fact there isn't an /data/db folder which I have. From that log I can see it is something to do with this line:

```<code>2017-04-14T14:23:09.366+0200 E STORAGE  [initandlisten] WiredTiger error (2) [1492172589:366629][9691:0x7f1755946cc0], file:WiredTiger.wt, connection: /var/lib/mongodb/WiredTiger.wt: handle-open: open: No such file or directory
</code>```

Which is true, when I go to /var/lib/mongodb and do ls -l it results with:

```<code>drwxr-xr-x 2 mongodb mongodb 4096 Apr 14 14:10 journal
-rw-r--r-- 1 mongodb mongodb    0 Apr 14 14:02 mongod.lock
-rw-r--r-- 1 mongodb mongodb    0 Apr 14 14:10 WiredTiger
-rw-r--r-- 1 mongodb mongodb   21 Apr 14 14:10 WiredTiger.lock
-rw-r--r-- 1 mongodb mongodb 1004 Apr 14 14:10 WiredTiger.turtle
</code>```

But I don't know if I should manually create that file as not seen this problem elsewhere. I made sure that mongodb user has permissions on these files too as stated in the answer to this question, but still no luck.

I'm really at a loss as to what to do, any help would be very appreciated as this is my like fifth attempt at getting it working!

Thanks!

答:
for me the 'answer' was to execute the following command (since service mongod start and just mongod failed)

```<code>sudo mongod --fork --port 27017 --replSet admin --logpath /data/log/mongo.log
</code>```

I did not need to turn off wired tiger

Title: MongoDB - shutting down with code:100

Body:
I've been trying to set up MongoDB on my Ubuntu 16.04.2 LTS (GNU/Linux 4.4.0-22-generic x86_64) VPS and I've been running into a few problems. I am running as a user on my server that has root access but not using the root account itself.

I started to notice the problem when I was executing db.createUser() on the admin database so I could add other users and I was getting this error:
not authorized to execute command

So I then proceeded to uninstall and install again using the tutorial as provided on the website: https://docs.mongodb.com/v3.2/tutorial/install-mongodb-on-ubuntu/

Now when I'm on stage 2 Verify that MongoDB has started successfully on the Run MongoDB Community Edition section, that is I look at my output from the file /var/log/mongodb/mongod.log, I get the following:

2017-04-14T14:23:09.309+0200 I CONTROL  [main] ***** SERVER RESTARTED *****
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] MongoDB starting : pid=9691 port=27017 dbpath=/var/lib/mongodb 64-bit host=vps338741
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] db version v3.4.3
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] git version: f07437fb5a6cca07c10bafa78365456eb1d6d5e1
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.2g  1 Mar 2016
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] allocator: tcmalloc
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] modules: none
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] build environment:
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten]     distmod: ubuntu1604
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten]     distarch: x86_64
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten]     target_arch: x86_64
2017-04-14T14:23:09.316+0200 I CONTROL  [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1", port: 27017 }, storage: { dbPath: "/var/lib/mongodb", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log", quiet: true } }
2017-04-14T14:23:09.349+0200 I STORAGE  [initandlisten]
2017-04-14T14:23:09.349+0200 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-04-14T14:23:09.349+0200 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-04-14T14:23:09.349+0200 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=464M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2017-04-14T14:23:09.366+0200 E STORAGE  [initandlisten] WiredTiger error (2) [1492172589:366629][9691:0x7f1755946cc0], file:WiredTiger.wt, connection: /var/lib/mongodb/WiredTiger.wt: handle-open: open: No such file or directory
2017-04-14T14:23:09.367+0200 I -        [initandlisten] Assertion: 28595:2: No such file or directory src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp 267
2017-04-14T14:23:09.367+0200 I STORAGE  [initandlisten] exception in initAndListen: 28595 2: No such file or directory, terminating
2017-04-14T14:23:09.367+0200 I NETWORK  [initandlisten] shutdown: going to close listening sockets...
2017-04-14T14:23:09.367+0200 I NETWORK  [initandlisten] removing socket file: /tmp/mongodb-27017.sock
2017-04-14T14:23:09.367+0200 I NETWORK  [initandlisten] shutdown: going to flush diaglog...
2017-04-14T14:23:09.367+0200 I CONTROL  [initandlisten] now exiting
2017-04-14T14:23:09.367+0200 I CONTROL  [initandlisten] shutting down with code:100

I've looked around and it is not the same error as found here, because that is to do with the fact there isn't an /data/db folder which I have. From that log I can see it is something to do with this line:

2017-04-14T14:23:09.366+0200 E STORAGE  [initandlisten] WiredTiger error (2) [1492172589:366629][9691:0x7f1755946cc0], file:WiredTiger.wt, connection: /var/lib/mongodb/WiredTiger.wt: handle-open: open: No such file or directory

Which is true, when I go to /var/lib/mongodb and do ls -l it results with:

drwxr-xr-x 2 mongodb mongodb 4096 Apr 14 14:10 journal
-rw-r--r-- 1 mongodb mongodb    0 Apr 14 14:02 mongod.lock
-rw-r--r-- 1 mongodb mongodb    0 Apr 14 14:10 WiredTiger
-rw-r--r-- 1 mongodb mongodb   21 Apr 14 14:10 WiredTiger.lock
-rw-r--r-- 1 mongodb mongodb 1004 Apr 14 14:10 WiredTiger.turtle

But I don't know if I should manually create that file as not seen this problem elsewhere. I made sure that mongodb user has permissions on these files too as stated in the answer to this question, but still no luck.

I'm really at a loss as to what to do, any help would be very appreciated as this is my like fifth attempt at getting it working!

Thanks!

Body:
for me the 'answer' was to execute the following command (since service mongod start and just mongod failed)

sudo mongod --fork --port 27017 --replSet admin --logpath /data/log/mongo.log

I did not need to turn off wired tiger


问:
Return a Message with HTTP Error Response Code in Flask?
How can a message body be added to a 404 response in flask?

The following attempts will generate a 404 but without the message:

```<code>@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        return "I don't care what they say, tomato is not a fruit", 404

    return "yummy"

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        flask.abort(404,"I don't care what they say, tomato is not a fruit")

    return "yummy"
</code>```

Thank you in advance for your consideration and response.

答:
Hellow !

I saw that you have already mentioned this issue as resolved. any way...

you can add a description parameter in flask.abord()

so it make sens to:
falsk.abord(404, description="Lorem ipsum dolor...")

```<code>    @app.errorhandler(404)
    def page_not_found(e):
        return "{}, {}".format(e.message, e.description)
</code>```

Body:
How can a message body be added to a 404 response in flask?

The following attempts will generate a 404 but without the message:

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        return "I don't care what they say, tomato is not a fruit", 404

    return "yummy"

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        flask.abort(404,"I don't care what they say, tomato is not a fruit")

    return "yummy"

Thank you in advance for your consideration and response.

Body:
Hellow !

I saw that you have already mentioned this issue as resolved. any way...

you can add a description parameter in flask.abord()

so it make sens to:
falsk.abord(404, description="Lorem ipsum dolor...")

    @app.errorhandler(404)
    def page_not_found(e):
        return "{}, {}".format(e.message, e.description)

ContentLicense: CC BY-SA 4.0


问:
Android SDK Manager Not Installing Components
Not sure what I'm doing wrong here. I installed the Android SDK Manager, and am now trying to install a platform like the Android Dev website suggests. Once I clicked install I got an error stating that the Manager could not create a temp folder within the Android directory. So I created it. Now I'm getting this error:

Downloading SDK Platform Android 2.3,
  API 9, revision 1 File not found:
  C:\Program Files
  (x86)\Android\android-sdk-windows\temp\android-2.3_r01-linux.zip
  (Access is denied)

There is also a little message under the progress bar that says "Done. Nothing was installed."

I'm running Windows 7 Ultimate, in case that's of any use.

答:
Try running Android Studio as an administrator, by right-clicking on the .exe and selecting "Run As Administrator".

Also, some anti-virus programs have been known to interfere with SDK Manager.

ContentLicense: CC BY-SA 2.5


问:
How can I automatically highlight a field with jQuery?
I need to have a field it automatically underline as the user is typing. The line follows the characters, and when the person leaves the field, I want the livery to fill it all up. Because it means that the user has finished filling that field.

Does anyone know how to do this?

答:
Honestly, Your question is not clear. But, I think you want to make user typing status. So let's do this. I use jQuery for it.

$(document).ready(function(){

setInterval(function(){

 if($("#target").val()!=""){
  $('span').show();
  }else{
     $('span').hide();
  }},1000);

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="write" id="target">
<span style="display:none;">Typing</span></code>```

Body:
Honestly, Your question is not clear. But, I think you want to make user typing status. So let's do this. I use jQuery for it.

$(document).ready(function(){

setInterval(function(){

 if($("#target").val()!=""){
  $('span').show();
  }else{
     $('span').hide();
  }},1000);

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="write" id="target">
<span style="display:none;">Typing</span>


问:
fgets from stdin with unpredictable input size
I'm trying to read a line from stdin but I don't know to properly handle the cases when input size is at least equal to the limit. Example code:

```<code>void myfun() {
    char buf[5];
    char somethingElse;

    printf("\nInsert string (max 4 characters): ");
    fgets (buf, 5, stdin);

    ...

    printf("\nInsert char: ");
    somethingElse = getchar();
}
</code>```

Now, the user can do three things:

Input less than 4 characters (plus newline): in this case there's nothing left in stdin and the subsequent getchar() correctly waits for user input;

Input exactly 4 characters (plus newline): in this case there's a newline left in stdin and the subsequent getchar() reads it;

Input more than 4 characters (plus newline): in this case there's at least another character left in stdin and the subsequent getchar() reads it, leaving at least a newline in.

Cases 2 and 3 would require emptying stdin using something like while(getchar() != '\n'), whereas case 1 doesn't require any additional action. As I understand from reading answers to similar questions and c-faq, there's no standard/portable way to know whether the actual scenario is the one described in 1 or not.

Did I get it well? Or there actually is a portable way to do it? Or maybe a totally different approach?

答:
If ones assumes that a null character '\0' is never read, then @dbush answer will work.

If a null character is read, then strrchr(buf, '\n') does not find any  '\n' that may have been read.

Code could pre-set the buffer to see if a '\n' was read in the end.

```<code>buf[sizeof buf - 2] = '\n';
if (fgets (buf, sizeof buf, stdin)) {
  if (strrchr(buf, '\n') == NULL) {
    // incomplete line read.  (the usual detection)
  } else if (buf[sizeof buf - 2] != '\n') {
    // incomplete line read with prior null character  (see below note).
  }
}
</code>```

Yet the C standard does not specify that data past what was read in buf[] is unchanged, pre-filling the buffer with some pattern is not sufficient to detect if a null character '\0' was read.

is a portable way to do it?

The most portable way is to use repeated calls to fgetc() or the like instead of fgets().

maybe a totally different approach?

I recommend fgetc() or the common but not C standard getline()

Another alternative: Use scanf("%4[^\n]%n", buf, &n):  It is very cumbersome, yet a portable way is possible.  It keeps track of the number of characters read before the '\n' even if some are null characters.

```<code>  int n = 0;
  cnt = scanf("%4[^\n]%n", buf, &n);  // Cumbersome to get that 4 here.
  // Lots of TBD code now needed:
  // Handle if cnt != 1 (\n to be read or EOF condition)
  // Handle if n == sizeof buf - 1, (0 or more to read)
  // Handle if n < sizeof buf - 1, (done, now get \n)
  // A \n may still need to be consumed
  // Handle EOF conditions
</code>```

Body:
I'm trying to read a line from stdin but I don't know to properly handle the cases when input size is at least equal to the limit. Example code:

void myfun() {
    char buf[5];
    char somethingElse;

    printf("\nInsert string (max 4 characters): ");
    fgets (buf, 5, stdin);

    ...

    printf("\nInsert char: ");
    somethingElse = getchar();
}

Now, the user can do three things:

Input less than 4 characters (plus newline): in this case there's nothing left in stdin and the subsequent getchar() correctly waits for user input;

Input exactly 4 characters (plus newline): in this case there's a newline left in stdin and the subsequent getchar() reads it;

Input more than 4 characters (plus newline): in this case there's at least another character left in stdin and the subsequent getchar() reads it, leaving at least a newline in.

Cases 2 and 3 would require emptying stdin using something like while(getchar() != '\n'), whereas case 1 doesn't require any additional action. As I understand from reading answers to similar questions and c-faq, there's no standard/portable way to know whether the actual scenario is the one described in 1 or not.

Did I get it well? Or there actually is a portable way to do it? Or maybe a totally different approach?

Body:
If ones assumes that a null character '\0' is never read, then @dbush answer will work.

If a null character is read, then strrchr(buf, '\n') does not find any  '\n' that may have been read.

Code could pre-set the buffer to see if a '\n' was read in the end.

buf[sizeof buf - 2] = '\n';
if (fgets (buf, sizeof buf, stdin)) {
  if (strrchr(buf, '\n') == NULL) {
    // incomplete line read.  (the usual detection)
  } else if (buf[sizeof buf - 2] != '\n') {
    // incomplete line read with prior null character  (see below note).
  }
}

Yet the C standard does not specify that data past what was read in buf[] is unchanged, pre-filling the buffer with some pattern is not sufficient to detect if a null character '\0' was read.

is a portable way to do it?

The most portable way is to use repeated calls to fgetc() or the like instead of fgets().

maybe a totally different approach?

I recommend fgetc() or the common but not C standard getline()

Another alternative: Use scanf("%4[^\n]%n", buf, &n):  It is very cumbersome, yet a portable way is possible.  It keeps track of the number of characters read before the '\n' even if some are null characters.

  int n = 0;
  cnt = scanf("%4[^\n]%n", buf, &n);  // Cumbersome to get that 4 here.
  // Lots of TBD code now needed:
  // Handle if cnt != 1 (\n to be read or EOF condition)
  // Handle if n == sizeof buf - 1, (0 or more to read)
  // Handle if n < sizeof buf - 1, (done, now get \n)
  // A \n may still need to be consumed
  // Handle EOF conditions


问:
How can I make browser use same outgoing port, when browsing one site?
When I inspect the connection with wireshark, every time the browser send request to host, it uses different port.
It is like that, even when browsing in a same tab, same site.
Can I make it use the same port?</p>

答:
Short answer is you can't (not on Windows anyway and not on *nix without sacrificing speed and possibly breaking things.).

Long answer is while it is technically possible while developing an application to create the logic to request specific port from OS when establishing connection, for a good reason this is not usually how it's done.

In the case of a browser, when it renders a site it establishes multiple connections, each with different outgoing unique port number (OS provided). The pool of available ports is OS managed and it's called Ephemeral Ports. If you are to limit the Ephemeral Poll to a single port (possible on *nix systems) just when executing the process and quickly reversing the change you may be able to force the Browser to use that specific outgoing port, but somehow I don't think this will work very well.


问:
Counting frequency of specific dataframe cells
I need to count the specific number of times a number is seen within a specific cell.

DataFrame ScreenShot

The values are between 1 to 7.

In this column Entity_Types, the first occurrence has     7,7,6,7,6,7,1,7,7,7,2. I think I need to create 7 additional empty columns and count the frequency of each occurrence(for each number) and append them to a new column labeled Entity_Types_1,Entity_Types_2...etc.

Example: New column 7 would have each count of 7 while New Column 1 would have the count of all 1's in that respective cell. I have a table that has 30,000 rows so I was wondering how to run it in a loop to fill out the rest of the dataset.

I can easily do it in excel using this formula

```<code>=SUMPRODUCT(LEN(O2)-LEN(SUBSTITUTE(O2,"2","")))
</code>```

Where O2 is Entity_Types and "2" = the number we are looking to find.

End Example

答:
It looks like Entity_Types is a column of strings in you data frame df.  If that is the case, you can use:

```<code>for i in range(8):
    df['Entity_Types_{}'.format(i)] = df.Entity_Types.str.count(str(i))
</code>```

Body:
I need to count the specific number of times a number is seen within a specific cell.

DataFrame ScreenShot

The values are between 1 to 7.

In this column Entity_Types, the first occurrence has     7,7,6,7,6,7,1,7,7,7,2. I think I need to create 7 additional empty columns and count the frequency of each occurrence(for each number) and append them to a new column labeled Entity_Types_1,Entity_Types_2...etc.

Example: New column 7 would have each count of 7 while New Column 1 would have the count of all 1's in that respective cell. I have a table that has 30,000 rows so I was wondering how to run it in a loop to fill out the rest of the dataset.

I can easily do it in excel using this formula

=SUMPRODUCT(LEN(O2)-LEN(SUBSTITUTE(O2,"2","")))

Where O2 is Entity_Types and "2" = the number we are looking to find.

End Example

Body:
It looks like Entity_Types is a column of strings in you data frame df.  If that is the case, you can use:

for i in range(8):
    df['Entity_Types_{}'.format(i)] = df.Entity_Types.str.count(str(i))


问:
Calculating Diff To Specific Value Within Groups
I need to calculate the differences within groups for thousands of simulated experiments. Here is a simplified version of the data:

```<code>import pandas as pd

data = {
    'experiment':['exp_1','exp_1','exp_1','exp_2','exp_2','exp_3','exp_3','exp_3','exp_3'],
    'variation':['control','variation_1','variation_2','control','variation_1','control','variation_1','variation_2','variation_3'],
    'revenue': [100,120,155,50,95,300,500,350,610]
}
df = pd.DataFrame(data,columns=['experiment','variation','revenue'])

In [16]: df
Out[16]:
  experiment    variation  revenue
0      exp_1      control      100
1      exp_1  variation_1       90
2      exp_1  variation_2      155
3      exp_2      control       50
4      exp_2  variation_1       95
5      exp_3      control      300
6      exp_3  variation_1      500
7      exp_3  variation_2      250
8      exp_3  variation_3      610
</code>```

Notice that each experiment does not have a fixed number number of variations--there can be just an A/B test, or an A/B/C/D test.

The goal is to calculate the diffs by comparing each variation to the control within each experiment. That would give the following results for the example data:

```<code>In [17]: df
Out[17]:
  experiment    variation  revenue  diffs
0      exp_1      control      100    NaN
1      exp_1  variation_1       90    -10
2      exp_1  variation_2      155     55
3      exp_2      control       50    NaN
4      exp_2  variation_1       95     45
5      exp_3      control      300    NaN
6      exp_3  variation_1      500    200
7      exp_3  variation_2      250    -50
8      exp_3  variation_3      610    310
</code>```

This answer is really close, but it is a cumulative diff at each point in time, rather than to a comparison to the first value in each group.

答:
IIUC, we can using transform and fillna

```<code>df['diff']=np.nan

df['diff']=df.loc[df.variation!='control','diff'].\
                fillna(df.revenue-df.groupby('experiment').revenue.transform('first'))
df
Out[498]:
  experiment    variation  revenue   diff
0      exp_1      control      100    NaN
1      exp_1  variation_1       90  -10.0
2      exp_1  variation_2      155   55.0
3      exp_2      control       50    NaN
4      exp_2  variation_1       95   45.0
5      exp_3      control      300    NaN
6      exp_3  variation_1      500  200.0
7      exp_3  variation_2      250  -50.0
8      exp_3  variation_3      610  310.0
</code>```

Body:
I need to calculate the differences within groups for thousands of simulated experiments. Here is a simplified version of the data:

import pandas as pd

data = {
    'experiment':['exp_1','exp_1','exp_1','exp_2','exp_2','exp_3','exp_3','exp_3','exp_3'],
    'variation':['control','variation_1','variation_2','control','variation_1','control','variation_1','variation_2','variation_3'],
    'revenue': [100,120,155,50,95,300,500,350,610]
}
df = pd.DataFrame(data,columns=['experiment','variation','revenue'])

In [16]: df
Out[16]:
  experiment    variation  revenue
0      exp_1      control      100
1      exp_1  variation_1       90
2      exp_1  variation_2      155
3      exp_2      control       50
4      exp_2  variation_1       95
5      exp_3      control      300
6      exp_3  variation_1      500
7      exp_3  variation_2      250
8      exp_3  variation_3      610

Notice that each experiment does not have a fixed number number of variations--there can be just an A/B test, or an A/B/C/D test.

The goal is to calculate the diffs by comparing each variation to the control within each experiment. That would give the following results for the example data:

In [17]: df
Out[17]:
  experiment    variation  revenue  diffs
0      exp_1      control      100    NaN
1      exp_1  variation_1       90    -10
2      exp_1  variation_2      155     55
3      exp_2      control       50    NaN
4      exp_2  variation_1       95     45
5      exp_3      control      300    NaN
6      exp_3  variation_1      500    200
7      exp_3  variation_2      250    -50
8      exp_3  variation_3      610    310

This answer is really close, but it is a cumulative diff at each point in time, rather than to a comparison to the first value in each group.

Body:
IIUC, we can using transform and fillna

df['diff']=np.nan

df['diff']=df.loc[df.variation!='control','diff'].\
                fillna(df.revenue-df.groupby('experiment').revenue.transform('first'))
df
Out[498]:
  experiment    variation  revenue   diff
0      exp_1      control      100    NaN
1      exp_1  variation_1       90  -10.0
2      exp_1  variation_2      155   55.0
3      exp_2      control       50    NaN
4      exp_2  variation_1       95   45.0
5      exp_3      control      300    NaN
6      exp_3  variation_1      500  200.0
7      exp_3  variation_2      250  -50.0
8      exp_3  variation_3      610  310.0


问:
How to get Arduino to read serial from Python?

Specific problem

I am trying to communicate between a Python script and my Arduino Pro Mini using serial with a USB cable. In Python I can read what the Arduino writes but the Arduino can either not read what the Python writes or it is reading it in a form that I can't process. The most obvious way this manifests itself is when I try to write what the Arduino has just read from Python, to Python. Nothing gets displayed in Python.

My Arduino sketch appears to work just fine when I work with it in the Serial Monitor, i.e. it can read and write so I suspect it is something at the Python end. What's causing this?

Details

I want to be able test how quickly I can send 64 byte-long pieces of information to my Arduino. To do this I wrote a Python script that could should be able to periodically send various information to my Arduino. I can change the period and thus test what kind of speed I can get.

However, despite the fact that my Arduino sketch works just fine with Serial Monitor, i.e. I can send it information and read information from it, I can't get it to work with Python.

With my Python script I can open the connection and read what the Arduino writes, but for some reason there is a problem with writing from Python. I have tried the following but none of them have worked:

Using an Uno instead of a Pro Mini.

Putting a Serial.println() statement in my get_data() function. Nothing gets printed.

Sending a string with the format "T(number);" and using sscanf() to extract the number. Using an if statement to examine the number and turn an onboard LED on. Did not work.

Sending a string beginning with "T" and using an if statement to see if it is stored in raw_data[]. It isn't.

Writing the data from Python at different times (i.e. using a longer delay).

Writing from Python using device.write(b"mystring") and device.write("mystring".encode())

I'm at a loss for what to try next…

Python (2.7) code

import serial, time, random, string

device = serial.Serial('/dev/tty.usbserial-A105YOZX', baudrate = 38400)

initial_time = time.time()
current_time = time.time()

counter = 0
control = 0

while counter < 1000:
    current_time = time.time()
    if current_time - initial_time > 0.1:
        initial_time = current_time
        counter += 1
        device.read()
    if current_time - initial_time > 1 and control == 0:
        device.write(b"Message being sent")
        control = 1
```

<h1>Arduino code</h1>

<pre class="lang-cpp prettyprint-override"><code>#define RAW_LEN 64 //max length of incoming string (buffer size is only 64 bytes)

//variables for incoming data
char raw_data[RAW_LEN];
int raw_data_i = 0; //index

unsigned long my_time;
int control = 0;
int for_print;

int get_data(int i) {
  //fills up raw_data[] with serial data. Clears raw_data if it gets too long
  if (Serial.available()>0) {
    raw_data[i] = Serial.read();
    Serial.println(raw_data[i]);
    //Serial.println(raw_data[i]);
    if (i<RAW_LEN-1){
      i++;
    }
  }
  return i;
}

void clear_data() {
  //clears raw_data and resets raw_data_i
  raw_data_i = 0;
  memset(raw_data,'\0',RAW_LEN-1);
}

//print functions
void raw_print(char data[]) {
  Serial.println("Received data: ");
  //if (raw_data[0] == 'T') {digitalWrite(LED_BUILTIN, HIGH);}
  for (int i=0; i< RAW_LEN;i++) {
    Serial.println(data[i]);
  }
}

void setup() {
  Serial.begin(38400);
  Serial.println("Restart");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop() {
  my_time = millis();
  raw_data_i = get_data(raw_data_i);
  //clear raw_data if it gets full
  if (raw_data_i == RAW_LEN-1) {
    clear_data();
  }

  if (my_time > 5000 && control == 0) {
    Serial.println("Here");
    raw_print(raw_data);
    control = 1;
  }
}
</code>```

答:
The problem turned out to be in the Python code. In while loop the first if statement is True after 0.1s, and then executes 9 more times before the second if statement is True.

The problem with this is that device.read() just hangs if it does not receive a character. Because I wasn't sending enough characters from the Arduino the Python code paused at the device.read() and never got to the second if statement.

An annoying mistake that took a while to figure out, hopefully this question and answer will save someone else a lot of debugging time.

Body:
Specific problem

I am trying to communicate between a Python script and my Arduino Pro Mini using serial with a USB cable. In Python I can read what the Arduino writes but the Arduino can either not read what the Python writes or it is reading it in a form that I can't process. The most obvious way this manifests itself is when I try to write what the Arduino has just read from Python, to Python. Nothing gets displayed in Python.

My Arduino sketch appears to work just fine when I work with it in the Serial Monitor, i.e. it can read and write so I suspect it is something at the Python end. What's causing this?

Details

I want to be able test how quickly I can send 64 byte-long pieces of information to my Arduino. To do this I wrote a Python script that could should be able to periodically send various information to my Arduino. I can change the period and thus test what kind of speed I can get.

However, despite the fact that my Arduino sketch works just fine with Serial Monitor, i.e. I can send it information and read information from it, I can't get it to work with Python.

With my Python script I can open the connection and read what the Arduino writes, but for some reason there is a problem with writing from Python. I have tried the following but none of them have worked:

Using an Uno instead of a Pro Mini.

Putting a Serial.println() statement in my get_data() function. Nothing gets printed.

Sending a string with the format "T(number);" and using sscanf() to extract the number. Using an if statement to examine the number and turn an onboard LED on. Did not work.

Sending a string beginning with "T" and using an if statement to see if it is stored in raw_data[]. It isn't.

Writing the data from Python at different times (i.e. using a longer delay).

Writing from Python using device.write(b"mystring") and device.write("mystring".encode())

I'm at a loss for what to try next…

Python (2.7) code

import serial, time, random, string

device = serial.Serial('/dev/tty.usbserial-A105YOZX', baudrate = 38400)

initial_time = time.time()
current_time = time.time()

counter = 0
control = 0

while counter < 1000:
    current_time = time.time()
    if current_time - initial_time > 0.1:
        initial_time = current_time
        counter += 1
        device.read()
    if current_time - initial_time > 1 and control == 0:
        device.write(b"Message being sent")
        control = 1

Arduino code

#define RAW_LEN 64 //max length of incoming string (buffer size is only 64 bytes)

//variables for incoming data
char raw_data[RAW_LEN];
int raw_data_i = 0; //index

unsigned long my_time;
int control = 0;
int for_print;

int get_data(int i) {
  //fills up raw_data[] with serial data. Clears raw_data if it gets too long
  if (Serial.available()>0) {
    raw_data[i] = Serial.read();
    Serial.println(raw_data[i]);
    //Serial.println(raw_data[i]);
    if (i<RAW_LEN-1){
      i++;
    }
  }
  return i;
}

void clear_data() {
  //clears raw_data and resets raw_data_i
  raw_data_i = 0;
  memset(raw_data,'\0',RAW_LEN-1);
}

//print functions
void raw_print(char data[]) {
  Serial.println("Received data: ");
  //if (raw_data[0] == 'T') {digitalWrite(LED_BUILTIN, HIGH);}
  for (int i=0; i< RAW_LEN;i++) {
    Serial.println(data[i]);
  }
}

void setup() {
  Serial.begin(38400);
  Serial.println("Restart");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop() {
  my_time = millis();
  raw_data_i = get_data(raw_data_i);
  //clear raw_data if it gets full
  if (raw_data_i == RAW_LEN-1) {
    clear_data();
  }

  if (my_time > 5000 && control == 0) {
    Serial.println("Here");
    raw_print(raw_data);
    control = 1;
  }
}


问:
Looking for good bonus quiz to test efficiency (specifically efficiency related to time)
I am doing a Introductory to Computer Science lab once a week.  I was hoping to have a quick contest at the end of my next lab.  I want to give them a block of code like this:

```<code>public class EfficientCode{

    public static void main(){
        long startTime, endTime, executionTime;
        startTime = System.currentTimeMillis();

        yourEfficientMethod():
        endTime = System.currentTimeMillis();
        executionTime = endTime – startTime;

    }

    public static void doSomething(){
        // you do this part.
    }

}
</code>```

They will implement the doSomething method and the person with the fastest code will get a handful of bonus marks.

The problem is that the question needs to be somewhat simple.  The students have a good grasp of: loops, if/else, Strings, adding, arrays, etc.

Here are my ideas for what the question could be:

find all the perfect numbers between 1 and 1,000,000.  (A perfect number is a number where all of the number's factors add up to the number.  Ie: 6 = 3 + 2 + 1)

find all prime numbers between 1 and 1,000,000

I think in order for there to be a measurable difference in performance between methods you must do something many times.

答:
Agreed about 'many times' for short operations, but for longer ones, once might be enough on its own.

I suggest looking into Project Euler, an excellent collection of programming questions. The best part is that the problems are designed with a "one minute rule" in mind, that most problems should take a moderate computer less than one minute to execute an efficient algorithm to find the answers. So an excellent place to start. :)

Body:
I am doing a Introductory to Computer Science lab once a week.  I was hoping to have a quick contest at the end of my next lab.  I want to give them a block of code like this:

public class EfficientCode{

    public static void main(){
        long startTime, endTime, executionTime;
        startTime = System.currentTimeMillis();

        yourEfficientMethod():
        endTime = System.currentTimeMillis();
        executionTime = endTime – startTime;

    }

    public static void doSomething(){
        // you do this part.
    }

}

They will implement the doSomething method and the person with the fastest code will get a handful of bonus marks.

The problem is that the question needs to be somewhat simple.  The students have a good grasp of: loops, if/else, Strings, adding, arrays, etc.

Here are my ideas for what the question could be:

find all the perfect numbers between 1 and 1,000,000.  (A perfect number is a number where all of the number's factors add up to the number.  Ie: 6 = 3 + 2 + 1)

find all prime numbers between 1 and 1,000,000

I think in order for there to be a measurable difference in performance between methods you must do something many times.


问:
How to get latest commit date - Github API
I'm currently writing a small database of git reps and im wondering how i would go ahead and get the date of the latest commit if i have the rep listed in my database.

I've never worked with the github API and im having a bit of a hard time wrapping my head around it.

If anyone could help me figure it out i'd much appreciate it. PHP or JS prefereably as all the examples ive found has been in ruby.

答:
Old question but I wanted to point out (at least with api v3) you could use the branches api to get the latest commit date for a particular branch. I assume in your case you're interested in master.

Which would look like:

```<code>https://api.github.com/repos/:owner/:repo/branches/master
</code>```

See https://developer.github.com/v3/repos/branches/

Body:
Old question but I wanted to point out (at least with api v3) you could use the branches api to get the latest commit date for a particular branch. I assume in your case you're interested in master.

Which would look like:

https://api.github.com/repos/:owner/:repo/branches/master

See https://developer.github.com/v3/repos/branches/


问:
Concatenate variable number of element string values via XPath 1.0?
I'm trying to use XPath 1.0 to select all of the text within these li elements, except for the last one with class="detailCrumb".

I'd like my result to look like:

```<code>Home Photography Memory Cards & Accessories Memory Cards
</code>```

These breadcrumbs will be dynamic based on the level of the site I'm at, so I can't specify positional requests, such as li[4]. How can I achieve this?

```<code><div class="breadcrums-cont">
    <ul id="breadcrumbs" ">
        <li class="first">Home</li>
        <li>Photography</li>
        <li>Memory Cards & Accessories</li>
        <li>Memory Cards</li>
        <li class="detailCrumb">SanDisk Extreme Pro</li>
    </ul>
</div>
</code>```

答:
To exept li tags with class "detailCrumb", use not() function</p>

```<code>//ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")]
</code>```

Body:
I'm trying to use XPath 1.0 to select all of the text within these li elements, except for the last one with class="detailCrumb".

I'd like my result to look like:

Home Photography Memory Cards & Accessories Memory Cards

These breadcrumbs will be dynamic based on the level of the site I'm at, so I can't specify positional requests, such as li[4]. How can I achieve this?

Home

Photography

Memory Cards & Accessories

Memory Cards

SanDisk Extreme Pro

Body:
To exept li tags with class "detailCrumb", use not() function

//ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")]


问:
Stacks in C++: Runtime error if the "or" condition is switched
I have often found this weird while using Stacks in C++ and I'm not sure what the exact root of the problem is. It would be better explained with a snippet of the code: (I am trying to get the minimum value of a stack and pushing/popping etc. as usual)

```<code>class MinStack {
private:
    stack<int> ans;
    stack<int> min_collector;

public:
    void push(int x) {
        ans.push(x);
        if (min_collector.empty() || getMin()>=x) {
            min_collector.push(x);
        }
    }

    void pop() {
        if (ans.top()==getMin()) {
            min_collector.pop();
        }
        ans.pop();
    }

    int top() {
        return ans.top();
    }

    int getMin() {
        return min_collector.top();
    }
</code>```

};

The above code works fine. However, in the push(int x) function, if I edit the "if" condition like this:

```<code>(getMin()>=x  || min_collector.empty())
</code>```

I get a runtime error, has anyone else faced this issue? Why should the order in a "or" condition matter?

答:
These conditions are evaluated from left to right, and execution aborts once the first term has returned true.

For logic && execution aborts once the first term has returned false.

You get a runtime error because it is illegal to attempt to access the top() element of a stack when it's empty - there is no top element.

Body:
I have often found this weird while using Stacks in C++ and I'm not sure what the exact root of the problem is. It would be better explained with a snippet of the code: (I am trying to get the minimum value of a stack and pushing/popping etc. as usual)

class MinStack {
private:
    stack<int> ans;
    stack<int> min_collector;

public:
    void push(int x) {
        ans.push(x);
        if (min_collector.empty() || getMin()>=x) {
            min_collector.push(x);
        }
    }

    void pop() {
        if (ans.top()==getMin()) {
            min_collector.pop();
        }
        ans.pop();
    }

    int top() {
        return ans.top();
    }

    int getMin() {
        return min_collector.top();
    }

};

The above code works fine. However, in the push(int x) function, if I edit the "if" condition like this:

(getMin()>=x  || min_collector.empty())

I get a runtime error, has anyone else faced this issue? Why should the order in a "or" condition matter?


问:
Rails Disable devise flash messages
How I can disable all Devise gem flash messages ("successfully signed in","you logged out")? Thanks.</p>

答:
For Rails 5.0.6 this code will work.

app/controllers/sessions_controller.rb

```<code>class SessionsController < Devise::SessionsController

  def new
    flash.clear
    super
  end
end
</code>```

Do not forget the routes.

config/routes.rb

devise_for :users, controllers: { sessions: 'sessions' }

Title: Rails Disable devise flash messages

Body:
For Rails 5.0.6 this code will work.

app/controllers/sessions_controller.rb

class SessionsController < Devise::SessionsController

  def new
    flash.clear
    super
  end
end

Do not forget the routes.

config/routes.rb

devise_for :users, controllers: { sessions: 'sessions' }


问:
Exporting as stand alone application
I exported Processing application as a standalone application with embedded Java, but the exe does not work in computers where Java/Processing is not installed. Even if the Windows 64 bits works with Java embedded, the 32 bits does not work with Java embedded or not. The computers that do not have Java already installed open the Windows 64 bits exe but not the Windows 32 exe (with java embedded in its exporting process). Here's the post in Processing forum: https://forum.processing.org/two/discussion/25373/no-export#latest
Can it be resolved? Thanks.</p>

答:
You can only include the Java version for the type of machine you're running on.

If you're on a 64-bit Windows machine, then you can only include Java in the 64-bit Windows application. If you're on a 32-bit Linux machine, then you can only include Java in the 32-bit Linux application.

If you really want to include Java for a bunch of different machines, then your best bet is to find each type of machine and do the export from them. Find a 32-bit Windows machine and do the export there, then find a 64-bit Linux machine and do the export there, etc.

You might be able to hack something together by downloading the JRE for each type of machine and manually including it, but that might get pretty tricky. Note that this is not as simple as just copying a folder into your application directory. You're going to have to change the run script file as well.

Shameless self-promotion: I've written a tutorial on exporting applications from Processing available here.

Title: Exporting as stand alone application


问:
Class 'SigninActivity' must either be declared abstract or implement abstract method 'doInBackground(Params...)' in 'AsyncTask'
Main Activity :

```<code>package com.example.phpmysql;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private EditText usernameField,passwordField;
    private TextView status,role,method;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        usernameField = (EditText)findViewById(R.id.editText1);
        passwordField = (EditText)findViewById(R.id.editText2);

        status = (TextView)findViewById(R.id.textView6);
        role = (TextView)findViewById(R.id.textView7);
        method = (TextView)findViewById(R.id.textView9);
    }

    public void login(View view){
        String username = usernameField.getText().toString();
        String password = passwordField.getText().toString();
        method.setText("Get Method");
        new SigninActivity(this,status,role,0).execute(username,password);

    }

    public void loginPost(View view){
        String username = usernameField.getText().toString();
        String password = passwordField.getText().toString();
        method.setText("Post Method");
        new SigninActivity(this,status,role,1).execute(username,password);
    }
}
</code>```

SigninActivity:

```<code>package com.example.phpmysql;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;

public class SigninActivity  extends AsyncTask{

    private TextView statusField,roleField;
    private Context context;
    private int byGetOrPost = 0;

    //flag 0 means get and 1 means post.(By default it is get.)

    public SigninActivity(Context context,TextView statusField,TextView
      roleField,int flag) {
        this.context = context;
        this.statusField = statusField;
        this.roleField = roleField;
        byGetOrPost = flag;
    }

    protected void onPreExecute(){
    }

    @Override
    protected String doInBackground(String... arg0) {
        if(byGetOrPost == 0){ //means by Get Method

            try{
                String username = (String)arg0[0];
                String password = (String)arg0[1];
                String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password;

                URL url = new URL(link);
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(link));
                HttpResponse response = client.execute(request);
                BufferedReader in = new BufferedReader(new
                        InputStreamReader(response.getEntity().getContent()));

                StringBuffer sb = new StringBuffer("");
                String line="";

                while ((line = in.readLine()) != null) {
                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();
            } catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }
        } else{
            try{
                String username = (String)arg0[0];
                String password = (String)arg0[1];

                String link="http://myphpmysqlweb.hostei.com/loginpost.php";
                String data  = URLEncoder.encode("username", "UTF-8") + "=" +
                        URLEncoder.encode(username, "UTF-8");
                data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
                        URLEncoder.encode(password, "UTF-8");

                URL url = new URL(link);
                URLConnection conn = url.openConnection();

                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

                wr.write( data );
                wr.flush();

                BufferedReader reader = new BufferedReader(new
                        InputStreamReader(conn.getInputStream()));

                StringBuilder sb = new StringBuilder();
                String line = null;

                // Read Server Response
                while((line = reader.readLine()) != null) {
                    sb.append(line);
                    break;
                }

                return sb.toString();
            } catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }
        }
    }

    @Override
    protected void onPostExecute(String result){
        this.statusField.setText("Login Successful");
        this.roleField.setText(result);
    }
}
</code>```

The public class SigninActivity extends AsyncTask is shown in red underline saying Class SigninActivity must either be declared abstract or implement abstract method doInBackground(Params...) in AsyncTask?

I tried adding the doInBackground but it says that it is never used?
I tried making it adbstract but then i could not call the class from mainactivity

答:
You need to provide the generic parameters as

```<code>public class SigninActivity  extends AsyncTask<String, Void, String>
</code>```

otherwise the parameter type will be of raw-type and signature won't match

Body:
Main Activity :

package com.example.phpmysql;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private EditText usernameField,passwordField;
    private TextView status,role,method;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        usernameField = (EditText)findViewById(R.id.editText1);
        passwordField = (EditText)findViewById(R.id.editText2);

        status = (TextView)findViewById(R.id.textView6);
        role = (TextView)findViewById(R.id.textView7);
        method = (TextView)findViewById(R.id.textView9);
    }

    public void login(View view){
        String username = usernameField.getText().toString();
        String password = passwordField.getText().toString();
        method.setText("Get Method");
        new SigninActivity(this,status,role,0).execute(username,password);

    }

    public void loginPost(View view){
        String username = usernameField.getText().toString();
        String password = passwordField.getText().toString();
        method.setText("Post Method");
        new SigninActivity(this,status,role,1).execute(username,password);
    }
}

SigninActivity:

package com.example.phpmysql;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;

public class SigninActivity  extends AsyncTask{

    private TextView statusField,roleField;
    private Context context;
    private int byGetOrPost = 0;

    //flag 0 means get and 1 means post.(By default it is get.)

    public SigninActivity(Context context,TextView statusField,TextView
      roleField,int flag) {
        this.context = context;
        this.statusField = statusField;
        this.roleField = roleField;
        byGetOrPost = flag;
    }

    protected void onPreExecute(){
    }

    @Override
    protected String doInBackground(String... arg0) {
        if(byGetOrPost == 0){ //means by Get Method

            try{
                String username = (String)arg0[0];
                String password = (String)arg0[1];
                String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password;

                URL url = new URL(link);
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(link));
                HttpResponse response = client.execute(request);
                BufferedReader in = new BufferedReader(new
                        InputStreamReader(response.getEntity().getContent()));

                StringBuffer sb = new StringBuffer("");
                String line="";

                while ((line = in.readLine()) != null) {
                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();
            } catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }
        } else{
            try{
                String username = (String)arg0[0];
                String password = (String)arg0[1];

                String link="http://myphpmysqlweb.hostei.com/loginpost.php";
                String data  = URLEncoder.encode("username", "UTF-8") + "=" +
                        URLEncoder.encode(username, "UTF-8");
                data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
                        URLEncoder.encode(password, "UTF-8");

                URL url = new URL(link);
                URLConnection conn = url.openConnection();

                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

                wr.write( data );
                wr.flush();

                BufferedReader reader = new BufferedReader(new
                        InputStreamReader(conn.getInputStream()));

                StringBuilder sb = new StringBuilder();
                String line = null;

                // Read Server Response
                while((line = reader.readLine()) != null) {
                    sb.append(line);
                    break;
                }

                return sb.toString();
            } catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }
        }
    }

    @Override
    protected void onPostExecute(String result){
        this.statusField.setText("Login Successful");
        this.roleField.setText(result);
    }
}

The public class SigninActivity extends AsyncTask is shown in red underline saying Class SigninActivity must either be declared abstract or implement abstract method doInBackground(Params...) in AsyncTask?

I tried adding the doInBackground but it says that it is never used?
I tried making it adbstract but then i could not call the class from mainactivity

Body:
You need to provide the generic parameters as

public class SigninActivity  extends AsyncTask<String, Void, String>

otherwise the parameter type will be of raw-type and signature won't match


问:
Countdown asp using VBS
I'm trying to make a Countdown Page, it shall show each counted number, it takes the numbers from a user entry, inside a table.

In the end it shall show for example from 10 to 1, the numbers 10,9,8,7,6,5,4,3,2,1.

Meanwhile i get Results, but only for counting up, but how do i get it to count down, it goes into my loop but it shows only the first Number, how do i display the rest?

```<code>          <%
response.flush
l_start = request.querystring("f_start")
l_goal = request.querystring("f_goal")

%>

<form action = "countdown.asp" method = "get">
   <h1 align = "center">Dies ist ein Zähler!<h1>
    <table border = "1" align = "center">
      <tr>
        <td>
          Bitte einen Startwert eingeben.
        </td>
        <td>
          <input type = "number" name = "f_start" value = "<%=l_start%>"
        </td>
        <td width = "100">

        </td>
        <td>
          Bitte einen Zielwert eingeben.
        </td>
        <td>
          <input type = "number" name = "f_goal" value = "<%=l_goal%>"
        </td>
        <td>
          <input type = "submit" value = "Go!" \>
        </td>
      </tr>
      <tr>
        <td>
          Gezählte Zahlen:
        </td>
        <td>
          <%
            if request.querystring(("f_start")) < request.querystring(("f_goal")) then
              For i = l_start To l_goal
                response.write("" & i & ",")
              Next
            else
                counter = l_start
              while counter > l_goal
                response.write(counter)
                response.write(",")
                counter = l_start - 1
              wend
            end if
          %>
        </td>
      </tr>
    </table>
</form>
</code>```

答:
There are a number of things wrong here. First, you only go into the then clause of the if statement if f_start is greater then f_goal, then you only go into the body of the while if f_start is less than or equal to f_goal. The conditions are similar for the else clause.

But it's worse than that because you use variables called f_start, f_goal and f_count that aren't defined. I think you intend to use values from Request.QueryString, but that's not what you're doing.

You assign values to l_start, l_goal and l_count but never change them. You modify the values in x and y but never use them. You put the unchanged l_start and l_goal back into the form.

Finally, there appears to be a cognitive disconnect in your understanding of where this code executes and how the variables in the script are related to the form. This is executing on the server. The values you enter in the form get submitted to the server. The script runs and does not do anything with the values passed to it from the form. It then puts those values right back onto the form.

Title: Countdown asp using VBS

Body:
I'm trying to make a Countdown Page, it shall show each counted number, it takes the numbers from a user entry, inside a table.

In the end it shall show for example from 10 to 1, the numbers 10,9,8,7,6,5,4,3,2,1.

Meanwhile i get Results, but only for counting up, but how do i get it to count down, it goes into my loop but it shows only the first Number, how do i display the rest?

          <%
response.flush
l_start = request.querystring("f_start")
l_goal = request.querystring("f_goal")

%>

<form action = "countdown.asp" method = "get">

Dies ist ein Zähler!

          Bitte einen Startwert eingeben.

          <input type = "number" name = "f_start" value = "<%=l_start%>"

          Bitte einen Zielwert eingeben.

          <input type = "number" name = "f_goal" value = "<%=l_goal%>"

          <input type = "submit" value = "Go!" \>

          Gezählte Zahlen:

          <%
            if request.querystring(("f_start")) < request.querystring(("f_goal")) then
              For i = l_start To l_goal
                response.write("" & i & ",")
              Next
            else
                counter = l_start
              while counter > l_goal
                response.write(counter)
                response.write(",")
                counter = l_start - 1
              wend
            end if
          %>

</form>


问:
document.getElementById() is returning null, despite being called inside $(document).ready
I am working on the lap feature for a stopwatch on a web page. The idea is that there is a div to which the current time will be appended whenever you click to record a lap. However, I'm getting null back from the getElementById function when I try to reference the lapLog div. I know that the page must be fully loaded for all elements to be discoverable, which is why I placed the function called by the button inside a $(document).ready block, but in spite of this it's still returning null.

Relevant JavaScript (timer.js):

$(document).ready(function(){
    $('#lapClkBtn').click(function(){
        // Only allow laps to be recorded if the timer is running
        if (ClkTimer.isAlive() == true) {
            var newEntry = ClkTimer.recordLap();
            lapLog = document.getElementById('lapLog');
            lapLog.innerHTML.append(newEntry);
            lapLog.animate({
                scrollTop: lapLog.prop('scrollHeight')
            }, 100);
        }
    });
})

function clkTimer(text, updateinterval) {
    this.recordLap = function() {
        this.lapNum = this.lapNum + 1;
        return String(this.lapNum) + "| " + this.formattedTime() + "
";
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="lapClkBtn">Lap</button>
<div class="lapLog"></div></code>```

答:
Your laplog is used as class. getElementById finds the element by the given id, not class. Replace it with id.

```<code><div id="lapLog"></div>
</code>```

Body:
I am working on the lap feature for a stopwatch on a web page. The idea is that there is a div to which the current time will be appended whenever you click to record a lap. However, I'm getting null back from the getElementById function when I try to reference the lapLog div. I know that the page must be fully loaded for all elements to be discoverable, which is why I placed the function called by the button inside a $(document).ready block, but in spite of this it's still returning null.

Relevant JavaScript (timer.js):

$(document).ready(function(){
    $('#lapClkBtn').click(function(){
        // Only allow laps to be recorded if the timer is running
        if (ClkTimer.isAlive() == true) {
            var newEntry = ClkTimer.recordLap();
            lapLog = document.getElementById('lapLog');
            lapLog.innerHTML.append(newEntry);
            lapLog.animate({
                scrollTop: lapLog.prop('scrollHeight')
            }, 100);
        }
    });
})

function clkTimer(text, updateinterval) {
    this.recordLap = function() {
        this.lapNum = this.lapNum + 1;
        return String(this.lapNum) + "| " + this.formattedTime() + "
";
    }
}

<button type="button" id="lapClkBtn">Lap</button>

Body:
Your laplog is used as class. getElementById finds the element by the given id, not class. Replace it with id.

<div id="lapLog"></div>


问:
TypeError: 'question_text' is an invalid keyword argument for this function in django 2.0 tutorial
I am fairly new to django and I am trying to follow the tutorial ( https://docs.djangoproject.com/en/2.0/intro/tutorial02/ ) but have encountered the above error.

Here is my code for the models.py

```<code>import datetime

from django.db import models
from django.utils import timezone

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200),
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE),
    choice_text = models.CharField(max_length=200),
    votes = models.IntegerField(default=0)

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

Also the question text and choice text is not appearing on the django-admin page

答: This error appears when you don't have that field in your table. As you show me there are only two fields registered (Id, pub_date). Please make migrations and migrate again if that didn't work, delete everything in the folder migrations and make migrations again

Body:
I am fairly new to django and I am trying to follow the tutorial ( https://docs.djangoproject.com/en/2.0/intro/tutorial02/ ) but have encountered the above error.

Here is my code for the models.py

import datetime

from django.db import models
from django.utils import timezone

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200),
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE),
    choice_text = models.CharField(max_length=200),
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

Also the question text and choice text is not appearing on the django-admin page


问:
dplyr::count() not working on MacOS
I'm trying to run a simple command from the dplyr package and I can't for the life of me make it work. This is what I get when executing one of the examples in dplyr::count()'s documentation:

```<code>dplyr::count(mtcars, cyl)
#> Error in quo_is_missing(wt) || quo_is_null(wt) :
#>   invalid 'y' type in 'x || y'
</code>```

This is my session info:

```<code>sessionInfo()
#> R version 3.4.2 (2017-09-28)
#> Platform: x86_64-apple-darwin15.6.0 (64-bit)
#> Running under: macOS Sierra 10.12.5

#> Matrix products: default
#> BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base

#> loaded via a namespace (and not attached):
#> [1] compiler_3.4.2 tools_3.4.2    yaml_2.1.15
</code>```

And these are the session info and conflicts after loading dplyr:

```<code>sessionInfo()
#> R version 3.4.2 (2017-09-28)
#> Platform: x86_64-apple-darwin15.6.0 (64-bit)
#> Running under: macOS Sierra 10.12.5

#> Matrix products: default
#> BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base

#> other attached packages:
#> [1] dplyr_0.7.4.9000

#> loaded via a namespace (and not attached):
#>  [1] tidyselect_0.2.3 compiler_3.4.2   magrittr_1.5     assertthat_0.2.0 R6_2.2.2
#>  [6] tools_3.4.2      bindrcpp_0.2     glue_1.2.0.9000  tibble_1.3.4     yaml_2.1.15
#> [11] Rcpp_0.12.14     knitr_1.17       pkgconfig_2.0.1  rlang_0.1.4.9000 purrr_0.2.4.9000
#> [16] bindr_0.1

conflicts(detail=TRUE)
#> $`package:dplyr`
#> [1] "filter"    "lag"       "intersect" "setdiff"   "setequal"  "union"

#> $`package:stats`
#> [1] "filter" "lag"

#> $`package:methods`
#> [1] "body<-"    "kronecker"

#> $`package:base`
#> [1] "body<-"    "intersect" "kronecker" "setdiff"   "setequal"  "union"
</code>```

答: I had the development version (purrr_0.2.4.9000) of purrr installed. I'm not sure how this would affect the dplyr::count() function, but installing the CRAN version of purrr solved the problem.

Title: dplyr::count() not working on MacOS

Body:
I'm trying to run a simple command from the dplyr package and I can't for the life of me make it work. This is what I get when executing one of the examples in dplyr::count()'s documentation:

dplyr::count(mtcars, cyl)
#> Error in quo_is_missing(wt) || quo_is_null(wt) :
#>   invalid 'y' type in 'x || y'

This is my session info:

sessionInfo()
#> R version 3.4.2 (2017-09-28)
#> Platform: x86_64-apple-darwin15.6.0 (64-bit)
#> Running under: macOS Sierra 10.12.5

#> Matrix products: default
#> BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base

#> loaded via a namespace (and not attached):
#> [1] compiler_3.4.2 tools_3.4.2    yaml_2.1.15

And these are the session info and conflicts after loading dplyr:

sessionInfo()
#> R version 3.4.2 (2017-09-28)
#> Platform: x86_64-apple-darwin15.6.0 (64-bit)
#> Running under: macOS Sierra 10.12.5

#> Matrix products: default
#> BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base

#> other attached packages:
#> [1] dplyr_0.7.4.9000

#> loaded via a namespace (and not attached):
#>  [1] tidyselect_0.2.3 compiler_3.4.2   magrittr_1.5     assertthat_0.2.0 R6_2.2.2
#>  [6] tools_3.4.2      bindrcpp_0.2     glue_1.2.0.9000  tibble_1.3.4     yaml_2.1.15
#> [11] Rcpp_0.12.14     knitr_1.17       pkgconfig_2.0.1  rlang_0.1.4.9000 purrr_0.2.4.9000
#> [16] bindr_0.1

conflicts(detail=TRUE)
#> $`package:dplyr`
#> [1] "filter"    "lag"       "intersect" "setdiff"   "setequal"  "union"

#> $`package:stats`
#> [1] "filter" "lag"

#> $`package:methods`
#> [1] "body<-"    "kronecker"

#> $`package:base`
#> [1] "body<-"    "intersect" "kronecker" "setdiff"   "setequal"  "union"


问:
What Exception to throw if (arg1 > arg2) should be fulfilled?
I do not really have a problem to solve, I would just like to know if there is a common way to deal with the following:

I have a constructor that takes two arguments (both int). The constructor itself only initializes attributes of my object. However, if (arg1 > arg2) is not fulfilled, there will be problems later on. Therefore I want to throw an Exception here because this is the place where a potential problem originates.

Is there a common Exception to throw in this case? Or would you rather throw a custom Exception? If so, how would you call that?

答:
Is there a common Exception to throw in this case?

According to the documentation, an IllegalArgumentException can be thrown:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Or would you rather throw a custom Exception?

It's not the case for throwing own exception unless you already have one and there are a few similar situations where you have thrown it.

Try to answer the following questions, they are gonna point you to the answer:

Is that an important case to handle?

Is that a usual validation case?

Will I encounter similar cases later?


问:
Kotlin IllegalAccessError with += and -= for delegated Interface
I've defined this class:

```<code>class NeverNullMap<K, V>(private val backing: MutableMap<K, V> = mutableMapOf(), val default: () -> V): MutableMap<K, V> by backing {
    override operator fun get(key: K): V = backing.getOrPut(key, default)
}
</code>```

And I can use it perfectly fine like this:

```<code>fun main(args: Array<String>) {
    val myMap = NeverNullMap<String, Int> {0}
    println(myMap["test"])
    myMap["test"] = myMap["test"] + 10
    println(myMap["test"])
}
</code>```

as expected the output is:

```<code>0
10
</code>```

But when I try to change it to:

```<code>fun main(args: Array<String>) {
    val myMap = NeverNullMap<String, Int> {0}
    println(myMap["test"])
    myMap["test"] += 10
    println(myMap["test"])
}
</code>```

I get:

```<code>Exception in thread "main" java.lang.IllegalAccessError: tried to access method kotlin.collections.MapsKt__MapsKt.set(Ljava/util/Map;Ljava/lang/Object;Ljava/lang/Object;)V from class Day08Kt
    at Day08Kt.main(Day08.kt:10)
</code>```

Why is this happening?

Edit:

Digging a bit into decompiled code both get compiled to completly diffrent code.

In the working version without the += it gets compiled to:

```<code>  Map var2 = (Map)myMap;
  String var3 = "test";
  Integer var4 = ((Number)myMap.get("test")).intValue() + 10;
  var2.put(var3, var4);
</code>```

The non working version gets compiled to:

```<code>MapsKt.set(myMap, "test", ((Number)myMap.get("test")).intValue() + 10);
</code>```

So it calles this function: https://github.com/JetBrains/kotlin/blob/1.2.0/libraries/stdlib/src/kotlin/collections/Maps.kt#L175

I still have no idea why that produces the Error, just why the first version behaves diffrently.

Edit: YouTrack link to the report

答:
Edit: yes, this is a bug, it has been merged with KT-14227:

Incorrect code is generated when using MutableMap.set with plusAssign operator

After compilation (or decompilation, in this case), MapsKt.set is turned into a private method:

```<code>@InlineOnly
private static final void set(@NotNull Map $receiver, Object key, Object value) {
    Intrinsics.checkParameterIsNotNull($receiver, "$receiver");
    $receiver.put(key, value);
}
</code>```

This explains the IllegalAccessError.

<s>Now, as to why it is private, I'm only speculating, but I feel like it may be due to this:</s>

@usbpc102 pointed out that @InlineOnly is indeed the reason for the method being private.

@InlineOnly specifies that the method should never be called directly:

Specifies that this function should not be called directly without inlining

so I feel like this is a case where the call to set should have been inlined, but it was not.

Had the call been inlined, you would have ended up with compiled code that is practically identical to the working version, since the method only contains a call to put.

I suspect this is due to a compiler bug.

Body:
I've defined this class:

class NeverNullMap<K, V>(private val backing: MutableMap<K, V> = mutableMapOf(), val default: () -> V): MutableMap<K, V> by backing {
    override operator fun get(key: K): V = backing.getOrPut(key, default)
}

And I can use it perfectly fine like this:

fun main(args: Array<String>) {
    val myMap = NeverNullMap<String, Int> {0}
    println(myMap["test"])
    myMap["test"] = myMap["test"] + 10
    println(myMap["test"])
}

as expected the output is:

0
10

But when I try to change it to:

fun main(args: Array<String>) {
    val myMap = NeverNullMap<String, Int> {0}
    println(myMap["test"])
    myMap["test"] += 10
    println(myMap["test"])
}

I get:

Exception in thread "main" java.lang.IllegalAccessError: tried to access method kotlin.collections.MapsKt__MapsKt.set(Ljava/util/Map;Ljava/lang/Object;Ljava/lang/Object;)V from class Day08Kt
    at Day08Kt.main(Day08.kt:10)

Why is this happening?

Edit:

Digging a bit into decompiled code both get compiled to completly diffrent code.

In the working version without the += it gets compiled to:

  Map var2 = (Map)myMap;
  String var3 = "test";
  Integer var4 = ((Number)myMap.get("test")).intValue() + 10;
  var2.put(var3, var4);

The non working version gets compiled to:

MapsKt.set(myMap, "test", ((Number)myMap.get("test")).intValue() + 10);

So it calles this function: https://github.com/JetBrains/kotlin/blob/1.2.0/libraries/stdlib/src/kotlin/collections/Maps.kt#L175

I still have no idea why that produces the Error, just why the first version behaves diffrently.

Edit: YouTrack link to the report

Body:
Edit: yes, this is a bug, it has been merged with KT-14227:

Incorrect code is generated when using MutableMap.set with plusAssign operator

After compilation (or decompilation, in this case), MapsKt.set is turned into a private method:

@InlineOnly
private static final void set(@NotNull Map $receiver, Object key, Object value) {
    Intrinsics.checkParameterIsNotNull($receiver, "$receiver");
    $receiver.put(key, value);
}

This explains the IllegalAccessError.

<s>Now, as to why it is private, I'm only speculating, but I feel like it may be due to this:</s>

@usbpc102 pointed out that @InlineOnly is indeed the reason for the method being private.

@InlineOnly specifies that the method should never be called directly:

Specifies that this function should not be called directly without inlining

so I feel like this is a case where the call to set should have been inlined, but it was not.

Had the call been inlined, you would have ended up with compiled code that is practically identical to the working version, since the method only contains a call to put.

I suspect this is due to a compiler bug.


问:
Qt screen names?
I've found this article. But lets say I have three monitors, how can I distinguish between them? Can I get the screen name (e.g. Samsung) somewhere?</p>

答: Qt5 has QGuiApplication::screens(i) with QScreen::name() and (from 5.9 on) even ::model().

Title: Qt screen names?


问:
How to time javascript actions so that they happen at the right order
I am trying to figure out how to time this for statement so it happens every second or so. What ends up happening is that the x prints 5 for all logs because the for loop is looping before the Timeout happens. How can I time the loops so every iteration happens after the setTimeout finishes.

for (x = 0; x < 5; x++) {
  var wait = setTimeout( function() {
    console.log(x,"x");
  }, 800);
}```

答:
Use let x = 0 to make sure x is block scoped in the loop and multiply delay times index in order to increment each delay time

for (let x = 0; x < 5; x++) {
  setTimeout(function() {
    console.log(x, " x")
  }, (x + 1) * 800);
}```


问:
Using R to create a new variables based on the counts of categorical variables
I have a dataset that contains an identifier variable (census_tract_number) and a categorical variable (action_taken_name) that contains five categories. I am trying to figure out how to create a new data frame that will break each category into a variable and show the frequency for each of these categories by census_tract_number. I have figured out how to create a frequency variable with count but I want each category to be an individual variable with the counts underneath.

答:
```<code>library(tidyr)
df <- data.frame(census_tract_number=c(1,1,1,2,2,2,2,2,2),
                 action_take_name=c('a','b','c','d','a','b','e','c','f'),
                 freq=c(2,2,4,5,28,20,5,40,23))

results <- df %>% spread(action_take_name,freq,fill=0)

results
  census_tract_number  a  b  c d e  f
1                   1  2  2  4 0 0  0
2                   2 28 20 40 5 5 23
</code>```