问:
Casting to base class without knowing name of class in C#
I've been implementing visitor pattern in C#. What I have is:

Hierarchy of classes:

```<code>public class A {
  public virtual void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
}

public class B : A {
  public override void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
}
</code>```

The Visitor class:

```<code>public abstract class Visitor {
  public virtual void Visit(A item) {
    //...
  }
  public virtual void Visit(B item) {
    Visit(item as A);
  }
}
</code>```

Concrete Visitor class:

```<code>public class ConcreteVisitor : Visitor {
  public override void Visit(B item) {
    // do something
    // and call Visit for base class
    Visit(item as A); // I need to know type A.
  }
}
</code>```

Is there any way to call Visit for item's base class without knowing its direct base class name? I would like to be able to change hierarchy without changing ConcreteVisitor class.

Thank you

答:
I really believe that there's a simpler solution which involves changing visitor's method identifiers:

```<code>public class ConcreteVisitor : Visitor {
  public override void VisitB(B item) {
    VisitA(item);
  }
}
</code>```

As B is A, the upcast is implicit.

For example, a real case might be:

```<code>public abstract class CarVisitor
{
     public virtual Engine VisitEngine(Engine engine) => engine;

     public virtual DieselEngine VisitDieselEngine(DieselEngine engine) => engine;
}

public sealed class MyCarVisitor : CarVisitor
{
     public override DieselEngine VisitDieselEngine(DieselEngine engine)
     {
          VisitEngine(engine);

          return engine;
     }
}
</code>```

Body:
I've been implementing visitor pattern in C#. What I have is:

Hierarchy of classes:

public class A {
  public virtual void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
}

public class B : A {
  public override void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
}

The Visitor class:

public abstract class Visitor {
  public virtual void Visit(A item) {
    //...
  }
  public virtual void Visit(B item) {
    Visit(item as A);
  }
}

Concrete Visitor class:

public class ConcreteVisitor : Visitor {
  public override void Visit(B item) {
    // do something
    // and call Visit for base class
    Visit(item as A); // I need to know type A.
  }
}

Is there any way to call Visit for item's base class without knowing its direct base class name? I would like to be able to change hierarchy without changing ConcreteVisitor class.

Thank you

Body:
I really believe that there's a simpler solution which involves changing visitor's method identifiers:

public class ConcreteVisitor : Visitor {
  public override void VisitB(B item) {
    VisitA(item);
  }
}

As B is A, the upcast is implicit.

For example, a real case might be:

public abstract class CarVisitor
{
     public virtual Engine VisitEngine(Engine engine) => engine;

     public virtual DieselEngine VisitDieselEngine(DieselEngine engine) => engine;
}

public sealed class MyCarVisitor : CarVisitor
{
     public override DieselEngine VisitDieselEngine(DieselEngine engine)
     {
          VisitEngine(engine);

          return engine;
     }
}


来源: stackexchange

问:
PHP - file not uploaded into the database using prepared statements
I made an upload file code without prepared statements. The file is successfully uploaded. But when I add prepared statements to the code, the contents of the file is not uploaded. Only the file name, size and type and uploaded in the database.

This is the code:

PHP:

```<code><?php
include("config.php");
error_reporting( ~E_NOTICE );
if(isset($_POST['submit'])  ){

//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

    if(in_array($ext, $allowed)){

        if($filesize < 2000000) {

            //$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')"; <- old code line

            $query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES (?,?,?,?)";

            $stmt = $con->prepare($query);
            $stmt->bind_param("sbsi", $filename, $filedata, $filetype,$filesize);
            $stmt->execute();

            if ($stmt->errno){
            echo "FAILURE!!! " . $stmt->error;
            } else {
            echo "<br>Inserted";
            }
            $stmt->close();

            /* if ($con->query($query) === TRUE) <- old code line
            {
            echo "Uploaded<br>";

            } else {
            echo "Error! <br>" . $con->error;
            }   */

        } else {

        $errorMsg = "Sorry, your file is too large. Only 2MB is allowed";
        }

    }else{
        $errorMsg = "Sorry, only zip, rar, pdf, doc & docx are allowed.";
    }

//if user has no file to upload then proceed to this else statement
} else {

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

//$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')"; <- old code line

$query = "INSERT INTO contracts(`filename`,`filetype`,`filesize`) VALUES (?,?,?)";

            $stmt = $con->prepare($query);
            $stmt->bind_param("ssi", $filename, $filetype,$filesize);
            $stmt->execute();

            if ($stmt->errno){
            echo "FAILURE!!! " . $stmt->error;
            } else {
            echo "<br>Inserted";
            }
            $stmt->close();

        /*  if ($con->query($query) === TRUE) <- old code line
            {
            echo "Uploaded<br>";

            } else {
            echo "Error! <br>" . $con->error;
            }   */

}

$con->close();
}

?>
</code>```

HTML:

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

<form method="post" action="" enctype="multipart/form-data">
<?php echo $errorMsg; ?>
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
</code>```

Why is the contents of the file is not uploaded and missing in the database with prepared statements? What is wrong with my code?

答:
Have you considered using http://php.net/manual/en/mysqli-stmt.send-long-data.php ((PHP 5, PHP 7) (Assuming your $conn object is good and working).

```<code>$stmt = $con->prepare($query);
$null = NULL;
$stmt->bind_param("sbsi", $filename, $filedata, $filetype,$filesize);
$stmt->send_long_data(1, file_get_contents($_FILES['upload']['tmp_name']));
$stmt->execute();
</code>```

PS : 1 represent the bind argument associated staring from 0, in your case the blob (b) is 2nd, so 1 on a 0 count.

THis is untested and i never used it, i just knew i could be done. Hopefully it will help.

More on the oracle blog : https://blogs.oracle.com/oswald/entry/php_s_mysqli_extension_storing

You might want to escape your binary, see Inserting Binary into MySQL BLOB

Another version from php.net :

```<code>$stmt = $con->prepare($query);
$null = NULL;
$stmt->bind_param("sbsi", $filename, $filedata, $filetype,$filesize);
$fp = fopen($_FILES['upload']['tmp_name'], "r");
while (!feof($fp)) {
    $stmt->send_long_data(1, fread($fp,$filesize));
}
fclose($fp);
$stmt->execute();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I made an upload file code without prepared statements. The file is successfully uploaded. But when I add prepared statements to the code, the contents of the file is not uploaded. Only the file name, size and type and uploaded in the database.

This is the code:

PHP:

<?php
include("config.php");
error_reporting( ~E_NOTICE );
if(isset($_POST['submit'])  ){

//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

    if(in_array($ext, $allowed)){

        if($filesize < 2000000) {

            //$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')"; <- old code line

            $query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES (?,?,?,?)";

            $stmt = $con->prepare($query);
            $stmt->bind_param("sbsi", $filename, $filedata, $filetype,$filesize);
            $stmt->execute();

            if ($stmt->errno){
            echo "FAILURE!!! " . $stmt->error;
            } else {
            echo "
Inserted";
            }
            $stmt->close();

            /* if ($con->query($query) === TRUE) <- old code line
            {
            echo "Uploaded
";

            } else {
            echo "Error!
" . $con->error;
            }   */

        } else {

        $errorMsg = "Sorry, your file is too large. Only 2MB is allowed";
        }

    }else{
        $errorMsg = "Sorry, only zip, rar, pdf, doc & docx are allowed.";
    }

//if user has no file to upload then proceed to this else statement
} else {

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

//$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')"; <- old code line

$query = "INSERT INTO contracts(`filename`,`filetype`,`filesize`) VALUES (?,?,?)";

            $stmt = $con->prepare($query);
            $stmt->bind_param("ssi", $filename, $filetype,$filesize);
            $stmt->execute();

            if ($stmt->errno){
            echo "FAILURE!!! " . $stmt->error;
            } else {
            echo "
Inserted";
            }
            $stmt->close();

        /*  if ($con->query($query) === TRUE) <- old code line
            {
            echo "Uploaded
";

            } else {
            echo "Error!
" . $con->error;
            }   */

}

$con->close();
}

?>

HTML:

<form method="post" action="" enctype="multipart/form-data">
<?php echo $errorMsg; ?>
Upload File:
<input type="file" name="upload" />

<input type="submit" name="submit" value="Submit"/>
</form>

Why is the contents of the file is not uploaded and missing in the database with prepared statements? What is wrong with my code?

Body:
Have you considered using http://php.net/manual/en/mysqli-stmt.send-long-data.php ((PHP 5, PHP 7) (Assuming your $conn object is good and working).

$stmt = $con->prepare($query);
$null = NULL;
$stmt->bind_param("sbsi", $filename, $filedata, $filetype,$filesize);
$stmt->send_long_data(1, file_get_contents($_FILES['upload']['tmp_name']));
$stmt->execute();

PS : 1 represent the bind argument associated staring from 0, in your case the blob (b) is 2nd, so 1 on a 0 count.

THis is untested and i never used it, i just knew i could be done. Hopefully it will help.

More on the oracle blog : https://blogs.oracle.com/oswald/entry/php_s_mysqli_extension_storing

You might want to escape your binary, see Inserting Binary into MySQL BLOB

Another version from php.net :

$stmt = $con->prepare($query);
$null = NULL;
$stmt->bind_param("sbsi", $filename, $filedata, $filetype,$filesize);
$fp = fopen($_FILES['upload']['tmp_name'], "r");
while (!feof($fp)) {
    $stmt->send_long_data(1, fread($fp,$filesize));
}
fclose($fp);
$stmt->execute();


问:
Why does webpack create extra files when I place entries in folders?
If I specify a folder structure for my files like below:

```<code>entry: {
        "lib/polyfill": ["./src/lib/polyfill.ts"],
        "lib/vendor-angular": ["./src/lib/vendor-angular.ts"],
        "lib/vendor-rxjs": ["./src/lib/vendor-rxjs.ts"],
        "app/app": ["./src/main.ts"]
    },
output: {
        path: path.resolve(__dirname, "wwwroot"),
        filename: "[name].js",
        chunkFilename: "[id].chunk.js",
        publicPath: "http://localhost:8080/"
    },
</code>```

The folder structure that gets created is strange, with small files in both locations... in the root and where I specified. Haven't yet been able to find anything about this.

```<code>wwwroot
|--app
|  |--
|  |  |--app.js
|--lib
|  |--
|  |  |--polyfill.js
|  |  |--vendor-angular.js
|  |  |--vendor-rxjs.js
|--app.js
|--polyfill.js
|--vendor-angular.js
|--vendor-rxjs.js
</code>```

I want to keep that root path clean. How do I do that?

webpackJsonp([4,5,6,7],[]); is an example of what is in some of these files in the wwwroot.

答:
The right way to specify a folder in which you want webpack to put its generated files, is specifying it in the "path" entry in the "output".

You made webpack put the generated files in "wwwroot" directory, instead of "lib", but you also gave the entries names with directories, which caused webpack put the generated files in this directories as well.

You should change the entries to be just names, without any relative path, and define the directory you want for the generated files in the "path" entry.

Body:
If I specify a folder structure for my files like below:

entry: {
        "lib/polyfill": ["./src/lib/polyfill.ts"],
        "lib/vendor-angular": ["./src/lib/vendor-angular.ts"],
        "lib/vendor-rxjs": ["./src/lib/vendor-rxjs.ts"],
        "app/app": ["./src/main.ts"]
    },
output: {
        path: path.resolve(__dirname, "wwwroot"),
        filename: "[name].js",
        chunkFilename: "[id].chunk.js",
        publicPath: "http://localhost:8080/"
    },

The folder structure that gets created is strange, with small files in both locations... in the root and where I specified. Haven't yet been able to find anything about this.

wwwroot
|--app
|  |--
|  |  |--app.js
|--lib
|  |--
|  |  |--polyfill.js
|  |  |--vendor-angular.js
|  |  |--vendor-rxjs.js
|--app.js
|--polyfill.js
|--vendor-angular.js
|--vendor-rxjs.js

I want to keep that root path clean. How do I do that?

webpackJsonp([4,5,6,7],[]); is an example of what is in some of these files in the wwwroot.


问:
VBA identify first and last rows with data
I want first and last rows with non-blank cells.
My last row works fine, the first row is bust. Suggestions appreciated.</p>

```<code>Sub idDataRange()

Dim firstRow As Long
Dim lastRow As Long

Sheets("fileNames").Select

' this has been adapted from a Stack overflow answer. lastRow unedited
' first row I changed Up to Down = NOT the solution!
With ActiveSheet
    firstRow = .Range("B" & .Rows.Count).End(xlDown).row
    lastRow = .Range("B" & .Rows.Count).End(xlUp).row
    End With

    MsgBox "the first row is " & firstRow
    MsgBox "last row is " & lastRow

End Sub
</code>```

答:
if values in column B are not derived from formulas, then you can use SpecialCells():

```<code>Dim firstRow As Long
Dim lastRow As Long

With Sheets("fileNames").Columns("B") '<--| reference your sheet (activating it is bad practice!) column "B" range
    If WorksheetFunction.CountA(.Cells) = 0 Then '<--| if no data whatever
        MsgBox "Sorry: no data"
    Else
        With .SpecialCells(xlCellTypeConstants) '<--| reference its cells with constant (i.e, not derived from formulas) values)
            firstRow = .Areas(1).Row
            lastRow = .Areas(.Areas.Count).Cells(.Areas(.Areas.Count).Rows.Count).Row
        End With
        MsgBox "the first row is " & firstRow
        MsgBox "last row is " & lastRow
    End If
End With
</code>```

Body:
I want first and last rows with non-blank cells.
My last row works fine, the first row is bust. Suggestions appreciated.

Sub idDataRange()

Dim firstRow As Long
Dim lastRow As Long

Sheets("fileNames").Select

' this has been adapted from a Stack overflow answer. lastRow unedited
' first row I changed Up to Down = NOT the solution!
With ActiveSheet
    firstRow = .Range("B" & .Rows.Count).End(xlDown).row
    lastRow = .Range("B" & .Rows.Count).End(xlUp).row
    End With

    MsgBox "the first row is " & firstRow
    MsgBox "last row is " & lastRow

End Sub

Body:
if values in column B are not derived from formulas, then you can use SpecialCells():

Dim firstRow As Long
Dim lastRow As Long

With Sheets("fileNames").Columns("B") '<--| reference your sheet (activating it is bad practice!) column "B" range
    If WorksheetFunction.CountA(.Cells) = 0 Then '<--| if no data whatever
        MsgBox "Sorry: no data"
    Else
        With .SpecialCells(xlCellTypeConstants) '<--| reference its cells with constant (i.e, not derived from formulas) values)
            firstRow = .Areas(1).Row
            lastRow = .Areas(.Areas.Count).Cells(.Areas(.Areas.Count).Rows.Count).Row
        End With
        MsgBox "the first row is " & firstRow
        MsgBox "last row is " & lastRow
    End If
End With


问:
Java 8 - Xmx and XX:MaxHeapSize do not match
I have set the Xmx parameter for JVM to 5120 but when the java process(tomcat) runs, I see that the MaxHeapSize does not match the Xmx value, it is stuck at 2570, which is strange to me, any thoughts on this are much appreciated!!

Output of ps:

/usr/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Xms1536m -Xmx5120 -Dorg.apache.catalina.STRICT_SERVLET_COMPLIANCE=true -Djava.net.preferIPv4Stack=true -DSHUTDOWN_PORT=8005 -DHTTP_PORT=8080 -DHTTPS_PORT=8443 -DAJP_PORT=8009 -XX:InitialHeapSize=2570m -XX:MaxHeapSize=2570m -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m -XX:+DisableExplicitGC -Djava.endorsed.dirs=/usr/local/tomcat/endorsed -classpath /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar -Dcatalina.base=/app/tomcat/default -Dcatalina.home=/usr/local/tomcat -Djava.io.tmpdir=/app/tomcat/default/temp org.apache.catalina.

答:
The -Xmx option is equivalent to -XX:MaxHeapSize.

(https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html)

So -Xmx5120 means 5120 Bytes but is superseeded by -XX:MaxHeapSize=2570m. That is the reason you are stuck by this.

Just provide only one of these settings and choose the proper value, e.g.

```<code>-Xmx5120m
</code>```

Body:
The -Xmx option is equivalent to -XX:MaxHeapSize.

(https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html)

So -Xmx5120 means 5120 Bytes but is superseeded by -XX:MaxHeapSize=2570m. That is the reason you are stuck by this.

Just provide only one of these settings and choose the proper value, e.g.

-Xmx5120m


问:
Regex Image url
I'm trying to pre replace to get dynamic url,

Code is:

```<code><span>
  <img src="/List/Detail/c0954c57-57ca-4f32-841d-de2b61a5087c/5358455" />
</span>
</code>```

I need to extract: only /List/Detail/c0954c57-57ca-4f32-841d-de2b61a5087c/5358455

Ive tried: \/Listing\/AdDetail\/

答:
Try with this:</p>

```<code>preg_match("/<img src=\"(.*)\"/", $input_line, $output_array);
</code>```

Title: Regex Image url

Body:
I'm trying to pre replace to get dynamic url,

Code is:

I need to extract: only /List/Detail/c0954c57-57ca-4f32-841d-de2b61a5087c/5358455

Ive tried: \/Listing\/AdDetail\/

Body:
Try with this:

preg_match("/<img src=\"(.*)\"/", $input_line, $output_array);


问:
how to know that clients disconnects server in socket
I am working on socket programming and I have to keep the track of all the clients that join the server.

So I am just keeping them an list:

```<code>client = []
</code>```

and appending the client to it whenever they connect to the server.
Now, I have to remove the client from the list whenever the client disconnects.
The trouble is how can a server know if a client has disconnected from that server.

For connecting server, I am using:

```<code>s = socket.socket()
s.bind((host, port))
client = []
while True:
   c, addr = s.accept()
   client.append(addr)
s.close()
</code>```

答:
Normally, when a socket is disconnected, it raises a socket.error if written to, and also returns b"" when read from.

So what you can do is, you can catch that exception and remove the client if writing to, and check if the data is empty if reading from.

Btw, you need to use the socket as the client, not its addr.

Like this:

```<code>try:
    sock.send(data)
except socket.error:
    client.remove(sock)

data = sock.receive(1024)
if not data:
    sock.close()
    client.remove(sock)
</code>```

Body:
I am working on socket programming and I have to keep the track of all the clients that join the server.

So I am just keeping them an list:

client = []

and appending the client to it whenever they connect to the server.
Now, I have to remove the client from the list whenever the client disconnects.
The trouble is how can a server know if a client has disconnected from that server.

For connecting server, I am using:

s = socket.socket()
s.bind((host, port))
client = []
while True:
   c, addr = s.accept()
   client.append(addr)
s.close()

Body:
Normally, when a socket is disconnected, it raises a socket.error if written to, and also returns b"" when read from.

So what you can do is, you can catch that exception and remove the client if writing to, and check if the data is empty if reading from.

Btw, you need to use the socket as the client, not its addr.

Like this:

try:
    sock.send(data)
except socket.error:
    client.remove(sock)

data = sock.receive(1024)
if not data:
    sock.close()
    client.remove(sock)


问:
On delete cascade error - How can I solve it with trigger?
My query to create some tables in SQL Server 2012 are as following:

```<code>create table Poll_Question_Table (
    PollQuestionId int primary key,
    PollQuestionTex varchar(max),
    PollStatus int ,
    PollStartDate date,
    PollEndDate date,
    PollCatagoryId int foreign key references Poll_Catagory_Table on update cascade on delete cascade
)

create table Poll_Catagory_Table(
    PollCatagoryId int primary key,
    PollCatagoryName varchar(100),
    PollCatagoryDescription varchar(max)
)

create table Poll_Answer_Table(
    PollAnswerId int primary key,
    PollAnswerText varchar(max),
    PollQuestionId int foreign key references Poll_Question_Table on update cascade on delete cascade
)

create table Poll_Vote_Table (
    PollVoteId int primary key,
    PollQuestionId int foreign key references Poll_Question_Table on update cascade on delete cascade ,
    PollAnswerId int foreign key references Poll_Answer_Table on update cascade on delete cascade,
    PollCount int
)
</code>```

and the error is

Introducing FOREIGN KEY constraint 'FK__Poll_Vote__PollA__5A3A55A2' on
  table 'Poll_Vote_Table' may cause cycles or multiple cascade paths.
  Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
  FOREIGN KEY constraints.
  how can i solve this one

答:
Their is many ways to solve your problem. I will present only two solutions:

1- The simpliest one: Changing your table Poll_Vote_Table into 2 table one for Questions, one for Answers.

2- Use trigger instead of delete/update. It's actually what you want, but please consider solution 1. Now the code to use trigger (for reference):

(I'll just illustrate for the Question part. For Answer, it's the same.)

First you will have to recreate your FK as follow (after delete) :

```<code>ALTER TABLE [dbo].[Poll_Vote_Table]  WITH CHECK
ADD CONSTRAINT [FK_Vote_Question] FOREIGN KEY([PollQuestionId])
REFERENCES [dbo].[Poll_Question_Table] ([PollQuestionId])
</code>```

Then you will need to create the triggers :

```<code>CREATE TRIGGER [DELETE_Question_Vote]
   ON dbo.[Poll_Question_Table]
   INSTEAD OF DELETE
AS
BEGIN
 SET NOCOUNT ON;
 DELETE FROM [Poll_Vote_Table] WHERE PollQuestionId IN (SELECT PollQuestionId FROM DELETED)
 DELETE FROM [Poll_Question_Table] WHERE PollQuestionId IN (SELECT PollQuestionId FROM DELETED)
END
GO
</code>```

The update part is usually of no use, so I won't write about it but it's basicly the same as DELETE.

Body:
My query to create some tables in SQL Server 2012 are as following:

create table Poll_Question_Table (
    PollQuestionId int primary key,
    PollQuestionTex varchar(max),
    PollStatus int ,
    PollStartDate date,
    PollEndDate date,
    PollCatagoryId int foreign key references Poll_Catagory_Table on update cascade on delete cascade
)

create table Poll_Catagory_Table(
    PollCatagoryId int primary key,
    PollCatagoryName varchar(100),
    PollCatagoryDescription varchar(max)
)

create table Poll_Answer_Table(
    PollAnswerId int primary key,
    PollAnswerText varchar(max),
    PollQuestionId int foreign key references Poll_Question_Table on update cascade on delete cascade
)

create table Poll_Vote_Table (
    PollVoteId int primary key,
    PollQuestionId int foreign key references Poll_Question_Table on update cascade on delete cascade ,
    PollAnswerId int foreign key references Poll_Answer_Table on update cascade on delete cascade,
    PollCount int
)

and the error is

Introducing FOREIGN KEY constraint 'FK__Poll_Vote__PollA__5A3A55A2' on
  table 'Poll_Vote_Table' may cause cycles or multiple cascade paths.
  Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
  FOREIGN KEY constraints.
  how can i solve this one

Body:
Their is many ways to solve your problem. I will present only two solutions:

1- The simpliest one: Changing your table Poll_Vote_Table into 2 table one for Questions, one for Answers.

2- Use trigger instead of delete/update. It's actually what you want, but please consider solution 1. Now the code to use trigger (for reference):

(I'll just illustrate for the Question part. For Answer, it's the same.)

First you will have to recreate your FK as follow (after delete) :

ALTER TABLE [dbo].[Poll_Vote_Table]  WITH CHECK
ADD CONSTRAINT [FK_Vote_Question] FOREIGN KEY([PollQuestionId])
REFERENCES [dbo].[Poll_Question_Table] ([PollQuestionId])

Then you will need to create the triggers :

CREATE TRIGGER [DELETE_Question_Vote]
   ON dbo.[Poll_Question_Table]
   INSTEAD OF DELETE
AS
BEGIN
 SET NOCOUNT ON;
 DELETE FROM [Poll_Vote_Table] WHERE PollQuestionId IN (SELECT PollQuestionId FROM DELETED)
 DELETE FROM [Poll_Question_Table] WHERE PollQuestionId IN (SELECT PollQuestionId FROM DELETED)
END
GO

The update part is usually of no use, so I won't write about it but it's basicly the same as DELETE.


问:
CDI: get manually instance of bean of class which is declared with generics
This is the way how I get manually instance of cdi bean:

```<code>Bean<?> bean = (Bean<?>)beanManager.resolve(beanManager.getBeans(Foo.class));
Foo foo=(Foo) beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean));
</code>```

if I declare Foo class this way:

```<code>@Dependent
public class Foo{
   ...
}
</code>```

everything works. However, if I declare class Foo this way

```<code>@Dependent
public class Foo<T>{
   ...
}
</code>```

cdi container can't create cdi bean. How can I get manually cdi bean of class declared with generics (Foo)?

答:
What you are looking for is probably javax.enterprise.util.TypeLiteral.
It is a utility class allowing you to specify a (bean) type along with the type variable. It then allows to retrieve the raw type as well as the actual type parameter inside. Here is a code snippet:

```<code>// define the type you want
TypeLiteral<Foo<Bar>> typeLiteral = new TypeLiteral<Foo<Bar>>() {};

// now search for beans; note that getBeans allows to specify Annotations as well!
Set<Bean<?>> beans = beanManager.getBeans(typeLiteral.getType());

// and apply resolution - you should get the one you want here
Bean<?> bean = beanManager.resolve(beans);
</code>```

Body:
This is the way how I get manually instance of cdi bean:

Bean<?> bean = (Bean<?>)beanManager.resolve(beanManager.getBeans(Foo.class));
Foo foo=(Foo) beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean));

if I declare Foo class this way:

@Dependent
public class Foo{
   ...
}

everything works. However, if I declare class Foo this way

@Dependent
public class Foo<T>{
   ...
}

cdi container can't create cdi bean. How can I get manually cdi bean of class declared with generics (Foo)?

Body:
What you are looking for is probably javax.enterprise.util.TypeLiteral.
It is a utility class allowing you to specify a (bean) type along with the type variable. It then allows to retrieve the raw type as well as the actual type parameter inside. Here is a code snippet:

// define the type you want
TypeLiteral<Foo<Bar>> typeLiteral = new TypeLiteral<Foo<Bar>>() {};

// now search for beans; note that getBeans allows to specify Annotations as well!
Set<Bean<?>> beans = beanManager.getBeans(typeLiteral.getType());

// and apply resolution - you should get the one you want here
Bean<?> bean = beanManager.resolve(beans);

ContentLicense: CC BY-SA 4.0


问:
Sinatra scope nomethoderror
I am trying to making Sinatra application.

But now I have a bug I can't solved. So I want help.

When I entered /tasks?status=done, the application alerts

NoMethodError at /tasks undefined method `status_is_done'

How can I fix the bug? Please show me any tips if you can.

Here is the Model code.

```<code>module Todo
class Task < ActiveRecord::Base
scope :status_is, ->(status){where(status: status)}

scope :status_is_not_yet, ->{status_is(NOT_YET)}
scope :status_is_done, ->{status_is(DONE)}
scope :status_is_pending, ->{status_is(PENDING)}

NOT_YET = 0
DONE = 1
PENDING = 2

STATUS = {
    'NOT_YET' => NOT_YET,
    'DONE' => DONE,
    'PENDING' => PENDING
}.freeze

validates :name, presence: true, length: {maximum: 140}
validates :content, presence: true
validates :status, numericality: true, inclusion: {in: STATUS.values}

def status_name
  STATUS.key(self.status)
end
</code>```

end
end

And Here is the Controller code.

```<code>require 'sinatra/base'
require 'haml'

require 'todo/db'
require 'todo/task'

module Todo
class Application < Sinatra::Base

set :haml, escape_html: true

configure do
  DB.prepare
end

configure :development do
  require 'sinatra/reloader'
  register Sinatra::Reloader
end

get '/' do
  redirect :tasks
end

get '/tasks' do
  @tasks = Task.order('created_at DESC')
  #statusによって@statusの値を変更
  if (@status = params[:status])
    case @status
    when 'not_yet'
      @tasks = @tasks.status_is_not_yet
    when 'done'
      @tasks = @tasks.status_is_done
    when 'pending'
      @tasks = @tasks.status_is_pending
    else
      @status = nil
    end
  end

  haml :index
end

end
end
</code>```

答:
Try replacing

```<code>@tasks = @tasks.status_is_done
</code>```

with

```<code>@tasks = Task.order('created_at DESC').status_is_done
</code>```

Title: Sinatra scope nomethoderror

Body:
I am trying to making Sinatra application.

But now I have a bug I can't solved. So I want help.

When I entered /tasks?status=done, the application alerts

NoMethodError at /tasks undefined method `status_is_done'

How can I fix the bug? Please show me any tips if you can.

Here is the Model code.

module Todo
class Task < ActiveRecord::Base
scope :status_is, ->(status){where(status: status)}

scope :status_is_not_yet, ->{status_is(NOT_YET)}
scope :status_is_done, ->{status_is(DONE)}
scope :status_is_pending, ->{status_is(PENDING)}

NOT_YET = 0
DONE = 1
PENDING = 2

STATUS = {
    'NOT_YET' => NOT_YET,
    'DONE' => DONE,
    'PENDING' => PENDING
}.freeze

validates :name, presence: true, length: {maximum: 140}
validates :content, presence: true
validates :status, numericality: true, inclusion: {in: STATUS.values}

def status_name
  STATUS.key(self.status)
end

end
end

And Here is the Controller code.

require 'sinatra/base'
require 'haml'

require 'todo/db'
require 'todo/task'

module Todo
class Application < Sinatra::Base

set :haml, escape_html: true

configure do
  DB.prepare
end

configure :development do
  require 'sinatra/reloader'
  register Sinatra::Reloader
end

get '/' do
  redirect :tasks
end

get '/tasks' do
  @tasks = Task.order('created_at DESC')
  #statusによって@statusの値を変更
  if (@status = params[:status])
    case @status
    when 'not_yet'
      @tasks = @tasks.status_is_not_yet
    when 'done'
      @tasks = @tasks.status_is_done
    when 'pending'
      @tasks = @tasks.status_is_pending
    else
      @status = nil
    end
  end

  haml :index
end

end
end

Body:
Try replacing

@tasks = @tasks.status_is_done

with

@tasks = Task.order('created_at DESC').status_is_done


问:
Tell `string::operator==` to start comparing at the back of the string
Is it possible/(relatively) easy/std™ to start comparing at the back of a string or should I write my own function for that? It would be relatively straightforward of course, but still, I would trust a standard library implementation over mine any day.

The end of the string is almost unique, and the front is quite common, that's the only reason I need this "optimization".

Thanks!

答: Best I can think of so far is str1.size() == str2.size() && std::equal(str1.rbegin(), str1.rend(), str2.rbegin())

ContentLicense: CC BY-SA 2.5


问:
Dynamic Inputs not getting serialized / submitted
i have the following form in  a modal (beside other modals on the page) (shortened for reading).

```<code><div class="modal fade" id="edit-project" tabindex="-1" role="dialog" aria-labelledby="edit-project">
  <form method="POST" action="update" id="edit-project-form">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4 class="modal-title">Edit Project Metadata</h4>
        </div>
        <div class="modal-body">
          <label>People:</label>
        <div class="form-group row" data-rel="0">
        <div class="col-md-4">
          <input class="form-control" name="member[0][firstname]" type="text" value="John">
        </div>
        <div class="col-md-5">
          <input class="form-control" name="member[0][lastname]" type="text" value="Smith">
        </div>
        <div class="col-md-6">
          <input class="form-control" name="member[0][email]" type="text" value="john@example.com">
        </div>
        <div class="col-md-7">
          <input class="form-control" name="member[0][uri]" type="text" value="http://www.example.com">
        </div>
      </div>

      ...

      <div class="form-group row" data-rel="2">
        <div class="col-md-4">
          <input class="form-control" name="member[2][firstname]" type="text" value="Peter">
        </div>
        <div class="col-md-5">
          <input class="form-control" name="member[2][lastname]" type="text" value="Doe">
        </div>
        <div class="col-md-6">
          <input class="form-control" name="member[2][email]" type="text" value="peter@example.com@gmail.com">
        </div>
        <div class="col-md-7">
          <input class="form-control" name="member[2][uri]" type="text" value="">
        </div>
        <div class="col-md-2">
          <button class="add-form-group btn btn-default" type="button">
            <i class="fa fa-plus"></i><span class="hidden-sm hidden-xs"></span>
          </button>
        </div>
      </div>
    </div>
  </form>
</div>
</code>```

Works great except for the last button from which I call some JQuery to dynamically add inputs. My plan was to make it the most general possible and prevent any HTML in the JS by cloning the form-group the button sits in and including it after the current form-group:

```<code>$('div.modal-body').on('click', '.add-form-group', function(){
    var current_form_group = $(this).closest('.form-group');
    var next_form_group = current_form_group.clone();
    var current_index = current_form_group.data('rel');
    var next_index = current_index + 1;

    next_form_group.attr('data-rel', next_index);

    next_form_group.children().find('input').each(function(index, element) {
        $(element).attr('name').replace(current_index, next_index);
        $(element).val = '';
    });
    $(this).parent().remove();
    next_form_group.appendTo('#edit-project-form').insertAfter(current_form_group);
})
</code>```

The form group is generated well. But the newly created inputs never get posted (not even serialized) although the elements are visible via DevTools:

```<code><div class="form-group row" data-rel="3">
    <div class="col-md-4">
        <input class="form-control" name="member[3][firstname]" type="text" value="New Firstname">
    </div>
    <div class="col-md-5">
        <input class="form-control" name="member[3][lastname]" type="text" value="New Lastname">
    </div>
    <div class="col-md-6">
        <input class="form-control" name="member[3][email]" type="text" value="New Email">
    </div>
    <div class="col-md-7">
        <input class="form-control" name="member[3][uri]" type="text" value="New URI">
    </div>
</div>
</code>```

Trying to find the form to append the new form-group to is not successful:

```<code>// Does not work:
var form = current_form_group.closest('form');
// Neither does this:
var for = $(this).closest('form');
</code>```

How can I get the parent form? But am I doing wrong? I queried for it and most of the time it was a problem with a wrongly wrappend form element (which is not the case here).

Serialization happens client-side so far and works well with the original inputs:

```<code>$('#edit-project-form').bind('submit', function (e) {
    e.preventDefault();
    var form    = $(this);
    var div     = $(this).parent();

    console.log(form.serialize());
});
</code>```

UPDATE: I gave more information on where the code actually sits (a modal). I left out any server-side code since the serialization already fails client-side

UPDATE 2: I got it working now:

```<code>form.append(next_form_group);
</code>```

The only thing that puzzles me now is the following: It gets injected at the top of the form now. How can I move the created form-group right underneath the "current_form_group". An easy "insertAfter" (like in the original post) does the trick visually but doesn't append the new form-group to the form.

Thanks in advance.

答:
I think the issue is here:

```<code>next_form_group.appendTo('#form').insertAfter(current_form_group);
</code>```

you are using insertAfter which add the data after the div having id #form and the form tag ends inside the div having id #form.

So to handle this use append() to add dynamic html inside form tag

Body:
i have the following form in  a modal (beside other modals on the page) (shortened for reading).

  <form method="POST" action="update" id="edit-project-form">

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Edit Project Metadata

          People:

          <input class="form-control" name="member[0][firstname]" type="text" value="John">

          <input class="form-control" name="member[0][lastname]" type="text" value="Smith">

          <input class="form-control" name="member[0][email]" type="text" value="john@example.com">

          <input class="form-control" name="member[0][uri]" type="text" value="http://www.example.com">

      ...

          <input class="form-control" name="member[2][firstname]" type="text" value="Peter">

          <input class="form-control" name="member[2][lastname]" type="text" value="Doe">

          <input class="form-control" name="member[2][email]" type="text" value="peter@example.com@gmail.com">

          <input class="form-control" name="member[2][uri]" type="text" value="">

          <button class="add-form-group btn btn-default" type="button">

          </button>

  </form>

Works great except for the last button from which I call some JQuery to dynamically add inputs. My plan was to make it the most general possible and prevent any HTML in the JS by cloning the form-group the button sits in and including it after the current form-group:

$('div.modal-body').on('click', '.add-form-group', function(){
    var current_form_group = $(this).closest('.form-group');
    var next_form_group = current_form_group.clone();
    var current_index = current_form_group.data('rel');
    var next_index = current_index + 1;

    next_form_group.attr('data-rel', next_index);

    next_form_group.children().find('input').each(function(index, element) {
        $(element).attr('name').replace(current_index, next_index);
        $(element).val = '';
    });
    $(this).parent().remove();
    next_form_group.appendTo('#edit-project-form').insertAfter(current_form_group);
})

The form group is generated well. But the newly created inputs never get posted (not even serialized) although the elements are visible via DevTools:

        <input class="form-control" name="member[3][firstname]" type="text" value="New Firstname">

        <input class="form-control" name="member[3][lastname]" type="text" value="New Lastname">

        <input class="form-control" name="member[3][email]" type="text" value="New Email">

        <input class="form-control" name="member[3][uri]" type="text" value="New URI">

Trying to find the form to append the new form-group to is not successful:

// Does not work:
var form = current_form_group.closest('form');
// Neither does this:
var for = $(this).closest('form');

How can I get the parent form? But am I doing wrong? I queried for it and most of the time it was a problem with a wrongly wrappend form element (which is not the case here).

Serialization happens client-side so far and works well with the original inputs:

$('#edit-project-form').bind('submit', function (e) {
    e.preventDefault();
    var form    = $(this);
    var div     = $(this).parent();

    console.log(form.serialize());
});

UPDATE: I gave more information on where the code actually sits (a modal). I left out any server-side code since the serialization already fails client-side

UPDATE 2: I got it working now:

form.append(next_form_group);

The only thing that puzzles me now is the following: It gets injected at the top of the form now. How can I move the created form-group right underneath the "current_form_group". An easy "insertAfter" (like in the original post) does the trick visually but doesn't append the new form-group to the form.

Thanks in advance.

Body:
I think the issue is here:

next_form_group.appendTo('#form').insertAfter(current_form_group);

you are using insertAfter which add the data after the div having id #form and the form tag ends inside the div having id #form.

So to handle this use append() to add dynamic html inside form tag


问:
IdentityServer4 along with Asp.Net 4.5 MVC Client
I am trying to authenticate an existing MVC application built with old Asp.Net (not the core version) with MVC framework.

By following IdentityServer4 and IdentityServer3 examples I have managed to get to a point where my user information is stored in LocalDB using EntityFramework and when I try to access to a restricted page in my client application I get redirected to the Login page provided by the IdentityServer4. However after successful login (based on what I see on the log) It does not redirect to the appropriate page. Address bar stays with something like http://localhost:5000/.... followed by lots of parameters and hashed values. Port 5000 is where I run my identity server and my application is hosted at port 44300 yet I couldn't manage to get back to there.

Has someone faced this kind of issue before or can someone please point me to an example which consists of IdentityServer4 along with a none Core version of Asp.Net.

Edit 1: Implementation Details

Server: IdentityServer4 implementation is almost clone of IdentityServer4 Quickstarts 6-AspNetIdentity.

Config File:

```<code>public class Config
{
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
        };
    }

    // clients want to access resources (aka scopes)
    public static IEnumerable<Client> GetClients()
    {
        // client credentials client
        return new List<Client>
        {
            new Client
            {
                ClientId = "webapp",
                ClientName = "Client WebApp",
                AllowedGrantTypes = GrantTypes.Hybrid,
                RedirectUris = { "http://localhost:44300/signin-oidc" },
                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile
                },
                AllowOfflineAccess = true
            }
        };
    }
}
</code>```

Client: Client implementation I am using is a dummy and It originates from IdentityServer3 Client examples "MVC OWIN Client (Hybrid)".

Startup.cs:

```<code>public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies"
        });
        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            AuthenticationType = "oidc",
            SignInAsAuthenticationType = "Cookies",
            ClientSecret = "secret",

            Authority = "http://localhost:5000", //ID Server
            RedirectUri = "http://localhost:44300/signin-oidc",
            ClientId = "webapp",

            ResponseType = "id_token code",
            Scope = "openid profile",
        });
    }
}
</code>```

Log Output: Log output after clicking secured page -> IS Login Page -> Clicking Login.

```<code>...
...
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
      HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Identity.Application.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
      AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /connect/authorize/login matched to endpoint type Authorize
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Mapping found for endpoint: Authorize, creating handler: IdentityServer4.Endpoints.AuthorizeEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize/login
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Start authorize request (after login)
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
      AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      User in authorize request: df21b123-d4b6-40ef-beed-e918bdfd56e9
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Start authorize request protocol validation
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
      AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator
info: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      ValidatedAuthorizeRequest
      {
        "ClientId": "webapp",
        "ClientName": "Client WebApp",
        "RedirectUri": "http://localhost:44300/signin-oidc",
        "AllowedRedirectUris": [
          "http://localhost:44300/signin-oidc"
        ],
        "SubjectId": "df21b123-d4b6-40ef-beed-e918bdfd56e9",
        "ResponseType": "code id_token",
        "ResponseMode": "form_post",
        "GrantType": "hybrid",
        "RequestedScopes": "openid profile",
        "State": "OpenIdConnect.AuthenticationProperties=m1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk",
        "Nonce": "636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl",
        "SessionId": "61d148313b2a7485dd27e3110ea61fff",
        "Raw": {
          "client_id": "webapp",
          "redirect_uri": "http://localhost:44300/signin-oidc",
          "response_mode": "form_post",
          "response_type": "id_token code",
          "scope": "openid profile",
          "state": "OpenIdConnect.AuthenticationProperties=m1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk",
          "nonce": "636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl",
          "x-client-SKU": "ID_NET",
          "x-client-ver": "1.0.40306.1554"
        }
      }
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
      Executed DbCommand (0ms) [Parameters=[@__get_Item_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
      SELECT TOP(1) [e].[Id], [e].[AccessFailedCount], [e].[ConcurrencyStamp], [e].[DefaultDatabaseName], [e].[DefaultDatabaseServer], [e].[Email], [e].[EmailConfirmed], [e].[HierarchyIds], [e].[LockoutEnabled], [e].[LockoutEnd], [e].[NormalizedEmail], [e].[NormalizedUserName], [e].[PasswordHash], [e].[PhoneNumber], [e].[PhoneNumberConfirmed], [e].[SecurityStamp], [e].[TwoFactorEnabled], [e].[UserName]
      FROM [AspNetUsers] AS [e]
      WHERE [e].[Id] = @__get_Item_0
info: IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator[0]
      Showing consent: User has not yet consented
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 138.8585ms 302
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/consent?returnUrl=%2Fconnect%2Fauthorize%2Fconsent%3Fclient_id%3Dwebapp%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A44300%252Fsignin-oidc%26response_mode%3Dform_post%26response_type%3Did_token%2520code%26scope%3Dopenid%2520profile%26state%3DOpenIdConnect.AuthenticationProperties%253Dm1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk%26nonce%3D636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl%26x-client-SKU%3DID_NET%26x-client-ver%3D1.0.40306.1554
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
      HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Identity.Application.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
      AuthenticationScheme: Identity.Application was successfully authenticated.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 32.5652ms 404
</code>```

答:
Your application running an older version of .NET isn't relevant.

In this video, one of the authors of IdentityServer demonstrates how he was able to connect a WinForm application with IDS4.

The communication to the IDS4 is made through HTTP requests, your client could be anything really as long as it can handle the communication with the IDS4.

I suggest that you open fiddler and monitor the requests to view the parameters passing.

You could also use one of the quickstarts as a base to your IDS, or compare it to your setup to check what's wrong.

Body:
I am trying to authenticate an existing MVC application built with old Asp.Net (not the core version) with MVC framework.

By following IdentityServer4 and IdentityServer3 examples I have managed to get to a point where my user information is stored in LocalDB using EntityFramework and when I try to access to a restricted page in my client application I get redirected to the Login page provided by the IdentityServer4. However after successful login (based on what I see on the log) It does not redirect to the appropriate page. Address bar stays with something like http://localhost:5000/.... followed by lots of parameters and hashed values. Port 5000 is where I run my identity server and my application is hosted at port 44300 yet I couldn't manage to get back to there.

Has someone faced this kind of issue before or can someone please point me to an example which consists of IdentityServer4 along with a none Core version of Asp.Net.

Edit 1: Implementation Details

Server: IdentityServer4 implementation is almost clone of IdentityServer4 Quickstarts 6-AspNetIdentity.

Config File:

public class Config
{
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
        };
    }

    // clients want to access resources (aka scopes)
    public static IEnumerable<Client> GetClients()
    {
        // client credentials client
        return new List<Client>
        {
            new Client
            {
                ClientId = "webapp",
                ClientName = "Client WebApp",
                AllowedGrantTypes = GrantTypes.Hybrid,
                RedirectUris = { "http://localhost:44300/signin-oidc" },
                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile
                },
                AllowOfflineAccess = true
            }
        };
    }
}

Client: Client implementation I am using is a dummy and It originates from IdentityServer3 Client examples "MVC OWIN Client (Hybrid)".

Startup.cs:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies"
        });
        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            AuthenticationType = "oidc",
            SignInAsAuthenticationType = "Cookies",
            ClientSecret = "secret",

            Authority = "http://localhost:5000", //ID Server
            RedirectUri = "http://localhost:44300/signin-oidc",
            ClientId = "webapp",

            ResponseType = "id_token code",
            Scope = "openid profile",
        });
    }
}

Log Output: Log output after clicking secured page -> IS Login Page -> Clicking Login.

...
...
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
      HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Identity.Application.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
      AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /connect/authorize/login matched to endpoint type Authorize
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Mapping found for endpoint: Authorize, creating handler: IdentityServer4.Endpoints.AuthorizeEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize/login
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Start authorize request (after login)
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
      AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      User in authorize request: df21b123-d4b6-40ef-beed-e918bdfd56e9
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Start authorize request protocol validation
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
      AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator
info: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      ValidatedAuthorizeRequest
      {
        "ClientId": "webapp",
        "ClientName": "Client WebApp",
        "RedirectUri": "http://localhost:44300/signin-oidc",
        "AllowedRedirectUris": [
          "http://localhost:44300/signin-oidc"
        ],
        "SubjectId": "df21b123-d4b6-40ef-beed-e918bdfd56e9",
        "ResponseType": "code id_token",
        "ResponseMode": "form_post",
        "GrantType": "hybrid",
        "RequestedScopes": "openid profile",
        "State": "OpenIdConnect.AuthenticationProperties=m1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk",
        "Nonce": "636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl",
        "SessionId": "61d148313b2a7485dd27e3110ea61fff",
        "Raw": {
          "client_id": "webapp",
          "redirect_uri": "http://localhost:44300/signin-oidc",
          "response_mode": "form_post",
          "response_type": "id_token code",
          "scope": "openid profile",
          "state": "OpenIdConnect.AuthenticationProperties=m1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk",
          "nonce": "636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl",
          "x-client-SKU": "ID_NET",
          "x-client-ver": "1.0.40306.1554"
        }
      }
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
      Executed DbCommand (0ms) [Parameters=[@__get_Item_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
      SELECT TOP(1) [e].[Id], [e].[AccessFailedCount], [e].[ConcurrencyStamp], [e].[DefaultDatabaseName], [e].[DefaultDatabaseServer], [e].[Email], [e].[EmailConfirmed], [e].[HierarchyIds], [e].[LockoutEnabled], [e].[LockoutEnd], [e].[NormalizedEmail], [e].[NormalizedUserName], [e].[PasswordHash], [e].[PhoneNumber], [e].[PhoneNumberConfirmed], [e].[SecurityStamp], [e].[TwoFactorEnabled], [e].[UserName]
      FROM [AspNetUsers] AS [e]
      WHERE [e].[Id] = @__get_Item_0
info: IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator[0]
      Showing consent: User has not yet consented
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 138.8585ms 302
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/consent?returnUrl=%2Fconnect%2Fauthorize%2Fconsent%3Fclient_id%3Dwebapp%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A44300%252Fsignin-oidc%26response_mode%3Dform_post%26response_type%3Did_token%2520code%26scope%3Dopenid%2520profile%26state%3DOpenIdConnect.AuthenticationProperties%253Dm1ybV84KFOLgklhcmtb8iR6VFuDBxWSzJKpTy83w7RF3zRTwd9zHBbdSyiAHbuea2D6FM1MjCJvMbql9qjcTntyu95POoCAWGwDML0nkiaYnKPKtJxgZ7FagyvYvz87C6pYlJWmL2zbrTFkYh7IPmX-Qv9rPOfyp4uwhhbZZ731vfL1mSxuhh_p1dPVNFJJav4E8bZXyadg94EXJbqb3ecc_jQHWn1F_eiJsoVMSRdk%26nonce%3D636268234716844341.OTFhNGE1ZTEtNTMyYy00Y2MyLWFjOGMtMDE1NjBmNDY3ZGM1NWFmNzIxMjItYTgzZC00NjJhLTk4YWMtNDExOTA0N2I4MjNl%26x-client-SKU%3DID_NET%26x-client-ver%3D1.0.40306.1554
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
      HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Identity.Application.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
      AuthenticationScheme: Identity.Application was successfully authenticated.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 32.5652ms 404


问:
Android 7 nougat, how to get the file path from uri of incoming intent?
FileProvider:- Setting up file sharing

I know that change the file policy in android nougat.
The wanted app that file share to other apps generate the uri by FileProvider.
The uri format is content://com.example.myapp.fileprovider/myimages/default_image.jpg.

I want know that how can I get filepath from the uri that generate by FileProvider.getUriForFile().
because the my app is need to know the physical filepath in order to save, load, readinfo, etc.
is it possible

[In short]

My app received the intent uri by other apps on andorid 7 nougat.

The uri format is content://com.example.myapp.fileprovider/myimages/default_image.jpg

Maybe it was generate by FileProvider.getUriForFile.

I want to know way that get the file path from uri.

I can just get the mime type, display name, file size and read binay from getContentResolver().openFileDescriptor().
but  I wnat to know the filepath.

答:
You cannot get a "file path" for a Uri, for the simple reason that there is no requirement that a Uri point to a file. Use ContentResolver and methods like openInputStream() to access the content represented by the Uri.

To share a file with another app using a content URI, your app has to
  generate the content URI. To generate the content URI, create a new
  File for the file, then pass the File to getUriForFile(). You can send
  the content URI returned by getUriForFile() to another app in an
  Intent. The client app that receives the content URI can open the file
  and access its contents by calling ContentResolver.openFileDescriptor
  to get a ParcelFileDescriptor.
  Source: Android developers


答: You should write your own function for that.  You could reverse as Lost says, but that wouldn't be an optimization unless you kept that reversed string around and where comparing multiple times.  Even then, it wouldn't be an improvement over writing your own that simply iterates the strings in reverse.</p>

Title: Tell `string::operator==` to start comparing at the back of the string

Body:
Is it possible/(relatively) easy/std™ to start comparing at the back of a string or should I write my own function for that? It would be relatively straightforward of course, but still, I would trust a standard library implementation over mine any day.

The end of the string is almost unique, and the front is quite common, that's the only reason I need this "optimization".

Thanks!


问:
How to remove call back when application goes to background?
I use runnable method they work properly when application goes background and app goes foreground they work but first time without background they cant work. work.
My code is below.

```<code> runnable = new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(context, "Login Successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(), WSSD.class);
                            toEdit.putString("LoginFlag", "true");
                            toEdit.commit();
                            intent.putExtra("AppMode", "online");
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                            startActivity(intent);
                            overridePendingTransition(R.anim.pull_in_right, R.anim.pull_out_left);

                            handler.postDelayed(this, 3000);
                        }
                    };
</code>```

/////////////////////////

```<code>@Override
    protected void onResume() {
        handler.postDelayed(runnable, 5000);
        MyApplication.activityResumed();
        super.onResume();
    }

    @Override
    protected void onPause() {
        handler.removeCallbacks(runnable);
        MyApplication.activityPaused();
        super.onPause();
    }
</code>```

答:
```<code>@Override
protected void onStop() {
    if(handler != null){
        handler.removeCallbacks(runnable);
    }
    super.onStop();
}
</code>```

void removeCallbacks (Runnable r)

Remove any pending posts of Runnable r that are in the message queue.

Body:
I use runnable method they work properly when application goes background and app goes foreground they work but first time without background they cant work. work.
My code is below.

 runnable = new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(context, "Login Successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(), WSSD.class);
                            toEdit.putString("LoginFlag", "true");
                            toEdit.commit();
                            intent.putExtra("AppMode", "online");
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                            startActivity(intent);
                            overridePendingTransition(R.anim.pull_in_right, R.anim.pull_out_left);

                            handler.postDelayed(this, 3000);
                        }
                    };

/////////////////////////

@Override
    protected void onResume() {
        handler.postDelayed(runnable, 5000);
        MyApplication.activityResumed();
        super.onResume();
    }

    @Override
    protected void onPause() {
        handler.removeCallbacks(runnable);
        MyApplication.activityPaused();
        super.onPause();
    }

Body:
@Override
protected void onStop() {
    if(handler != null){
        handler.removeCallbacks(runnable);
    }
    super.onStop();
}

void removeCallbacks (Runnable r)

Remove any pending posts of Runnable r that are in the message queue.


问:
Fixed header hides the content starting section
I've created one page website, Once the page is scrolled the header is fixed to top. The problem here I'm facing is once we click the "Service" section from the menu some portion of the page is hidden below the menu.

I have tried adding padding to the section it still results the same.

URL : here

Sorry as the website is hosted, Please check the code in hosted link. This is just a static website.

答:
First of all, I agree with the comments; please post a Minimal, Complete, and Verifiable example so we can help you better. Linking to another website is not the way this platform works.

In your JavaScript you have the following code:

```<code>$('.page-scroll').bind('click', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top
    }, 1500, 'easeInOutExpo');
    event.preventDefault();
});
</code>```

if you play with that value (the offset().top) you can change the behaviour of the scrollTo.

Change it to something like this:

```<code>scrollTop: ($($anchor.attr('href')).offset().top - 77)
</code>```

77 is the height in pixels of the menu. If you want some more spacing between the menu and the content, make the 77 something like 90.

Body:
First of all, I agree with the comments; please post a Minimal, Complete, and Verifiable example so we can help you better. Linking to another website is not the way this platform works.

In your JavaScript you have the following code:

$('.page-scroll').bind('click', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top
    }, 1500, 'easeInOutExpo');
    event.preventDefault();
});

if you play with that value (the offset().top) you can change the behaviour of the scrollTo.

Change it to something like this:

scrollTop: ($($anchor.attr('href')).offset().top - 77)

77 is the height in pixels of the menu. If you want some more spacing between the menu and the content, make the 77 something like 90.


问:
Is it possible to embed a PDF doc at the end of XSL FO?
I have used the below  tag

```<code><fox:external-document src="Resources/test.pdf" />
</code>```

But Its throwing the below error.

Apr 03, 2017 10:15:31 AM org.apache.fop.events.LoggingEventListener
  processEvent SEVERE: Image not available. URI: Resources/test.pdf.
  Reason: org.apache.xmlgraphics.image.loader.ImageException: The file
  format is not supported. No ImagePreloader found for
  Resources/test.pdf (No context info available)
  org.apache.xmlgraphics.image.loader.ImageException: The file format is
  not supported. No ImagePreloader found for Resources/test.pdf     at
  org.apache.xmlgraphics.image.loader.ImageManager.preloadImage(ImageManager.java:180)

I have kept the namespace properly.

答:
I'm using fop 2.1 and include pdf as external-graphics successfully using the FOP PDF Images Plugin

"The four jar files should be placed in the lib directory of your fop
  installation"

I'm think my download was from here.

Body:
I have used the below  tag

<fox:external-document src="Resources/test.pdf" />

But Its throwing the below error.

Apr 03, 2017 10:15:31 AM org.apache.fop.events.LoggingEventListener
  processEvent SEVERE: Image not available. URI: Resources/test.pdf.
  Reason: org.apache.xmlgraphics.image.loader.ImageException: The file
  format is not supported. No ImagePreloader found for
  Resources/test.pdf (No context info available)
  org.apache.xmlgraphics.image.loader.ImageException: The file format is
  not supported. No ImagePreloader found for Resources/test.pdf     at
  org.apache.xmlgraphics.image.loader.ImageManager.preloadImage(ImageManager.java:180)

I have kept the namespace properly.


问:
Fluent NHibernate with ManyToMany and Custom Link Table
I have the following schema, and when I delete one of the objects on one many side, it seems to be trying to delete the objects on the other many side.  Am somewhat confused about the proper Cascade options to use, and I don't find Oren's brief description of them to be useful, so please don't quote those back.

```<code>public class Store {
public virtual IList<StoreProduct> StoreProducts { get; set; }
}

public class Product {
public virtual IList<StoreProduct> StoreProducts { get; set; }
}

public class StoreProduct {
public virtual Store Store { get; set; }
public virtual Product Product { get; set; }
public virtual Decimal Cost { get; set; } //this is why I have a custom linking class
}
</code>```

In my mapping overrides, I have:

For Store:

```<code>mapping.HasMany(x => x.StoreProducts).Cascade.AllDeleteOrphan().Inverse;
</code>```

For Product:

```<code>mapping.HasMany(x => x.StoreProducts).Cascade.AllDeleteOrphan().Inverse;
</code>```

When I try to delete a Store that has associated StoreProducts, it seems that NHIbernate tries to delete not only the StoreProducts, but the Products.

Here are my conventions:

```<code> return c =>
                       {
                           c.Add<ForeignKeyConvention>();
                           c.Add<HasManyConvention>();
                           c.Add<HasManyToManyConvention>();
                           c.Add<ManyToManyTableNameConvention>();
                           c.Add<PrimaryKeyConvention>();
                           c.Add<ReferenceConvention>();
                           c.Add<EnumConvention>();
                           c.Add<TableNameConvention>();
                           c.Add<CascadeAll>();
                           c.Add(DefaultCascade.All());
                       };
</code>```

HasManyConvention:

```<code>public void Apply(IOneToManyCollectionInstance instance)
{
    instance.Key.Column(instance.EntityType.Name + "Fk");
    instance.Cascade.AllDeleteOrphan();
    instance.Inverse();
}
</code>```

What am I doing wrong?

Thanks!

p.s.:  I don't want to overwhelm people w/code, but can post more if needed.

答: You need to turn off the cascading on StoreProduct is my guess.  Its hard to test without setting it up.  I see the cascade on Store and Product, but turn it off on StoreProduct.</p>

Body:
I have the following schema, and when I delete one of the objects on one many side, it seems to be trying to delete the objects on the other many side.  Am somewhat confused about the proper Cascade options to use, and I don't find Oren's brief description of them to be useful, so please don't quote those back.

public class Store {
public virtual IList<StoreProduct> StoreProducts { get; set; }
}

public class Product {
public virtual IList<StoreProduct> StoreProducts { get; set; }
}

public class StoreProduct {
public virtual Store Store { get; set; }
public virtual Product Product { get; set; }
public virtual Decimal Cost { get; set; } //this is why I have a custom linking class
}

In my mapping overrides, I have:

For Store:

mapping.HasMany(x => x.StoreProducts).Cascade.AllDeleteOrphan().Inverse;

For Product:

mapping.HasMany(x => x.StoreProducts).Cascade.AllDeleteOrphan().Inverse;

When I try to delete a Store that has associated StoreProducts, it seems that NHIbernate tries to delete not only the StoreProducts, but the Products.

Here are my conventions:

 return c =>
                       {
                           c.Add<ForeignKeyConvention>();
                           c.Add<HasManyConvention>();
                           c.Add<HasManyToManyConvention>();
                           c.Add<ManyToManyTableNameConvention>();
                           c.Add<PrimaryKeyConvention>();
                           c.Add<ReferenceConvention>();
                           c.Add<EnumConvention>();
                           c.Add<TableNameConvention>();
                           c.Add<CascadeAll>();
                           c.Add(DefaultCascade.All());
                       };

HasManyConvention:

public void Apply(IOneToManyCollectionInstance instance)
{
    instance.Key.Column(instance.EntityType.Name + "Fk");
    instance.Cascade.AllDeleteOrphan();
    instance.Inverse();
}

What am I doing wrong?

Thanks!

p.s.:  I don't want to overwhelm people w/code, but can post more if needed.


问:
How to use get_posts() and form select
Hi everyone I'm new to wp plugin development. So far, I'm doing well except for this form select piece that seems to be kicking my head. I'm trying to show list of recent post in a select field for admin to select and do some stuff but the title will not show. I tried this in radio button and even text field and got no result. Please, what am I missing in this form?</p>

```<code><form method="post"><select name="Article">
$args = array( 'numberposts' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );     foreach ($postslist as $post) : setup_postdata($post);

echo'<option value='".the_ID()."'>'".the_title()."'</option>';
endforeach;
echo"</select></form>";
</code>```

答:
it won't work as you'd like in the middle of a concatenation. You need get_the_ID($post) instead.

```<code>  <?php
        $args = array( 'numberposts=>-1&order=>ASC&orderby=>title' );
        $postslist = get_posts( $args );     foreach ($postslist as $post) : setup_postdata($post);
        echo '<option value="'.get_the_id($post).'">'.get_the_title($post).'</option>';
        endforeach;
?>
</code>```

your echo should be

```<code>echo '<option value="' . get_the_ID($post) . '">' . get_the_title($post) . '</option>';
</code>```

Title: How to use get_posts() and form select

Body:
Hi everyone I'm new to wp plugin development. So far, I'm doing well except for this form select piece that seems to be kicking my head. I'm trying to show list of recent post in a select field for admin to select and do some stuff but the title will not show. I tried this in radio button and even text field and got no result. Please, what am I missing in this form?

<form method="post"><select name="Article">
$args = array( 'numberposts' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );     foreach ($postslist as $post) : setup_postdata($post);

echo'<option value='".the_ID()."'>'".the_title()."'</option>';
endforeach;
echo"</select></form>";

Body:
it won't work as you'd like in the middle of a concatenation. You need get_the_ID($post) instead.

  <?php
        $args = array( 'numberposts=>-1&order=>ASC&orderby=>title' );
        $postslist = get_posts( $args );     foreach ($postslist as $post) : setup_postdata($post);
        echo '<option value="'.get_the_id($post).'">'.get_the_title($post).'</option>';
        endforeach;
?>

your echo should be

echo '<option value="' . get_the_ID($post) . '">' . get_the_title($post) . '</option>';


问:
NodeJS Express Async issue
I have this function which gets some data from my database but i'm having a trouble calling the function and getting the proper response

```<code>  function getEvents()
  {
    var x = [];
    var l = dbCollection['e'].find({}).forEach(function(y) {
    x.push(y);
  });

 return x;
});
</code>```

and another function which calls this function but it always returns undefined.
How can i make the function wait till mongoose has finished filling up the array?

Thanks for the help! My life

答:
The solution proposed by @orhankutlu should work fine.

I will give another solution using promise. You can choose one between these two solutions depending on your style of programming.

Solution using promise:

```<code>function getEvents() {
    return new Promise(function(resolve, reject){
        dbCollection['e'].find({}, function(error, results) {
           if (error) return reject(error);

           var x = [];
           results.forEach(function(y){
              x.push(y);
           });
           // forEach() is a blocking call,
           // so the promise will be resolved only
           // after the forEach completes
           return resolve(x);
        });
    });
};
</code>```

Calling getEvents():

```<code>getEvents().then(function(result){
    console.log(result);   //should print 'x'
}).catch(function(err){
    // Handle error here in case the promise is rejected
});
</code>```

I will encourage you to try both the approaches, ie, using callbacks and using promises. Hope you find it useful!

Title: NodeJS Express Async issue

Body:
I have this function which gets some data from my database but i'm having a trouble calling the function and getting the proper response

  function getEvents()
  {
    var x = [];
    var l = dbCollection['e'].find({}).forEach(function(y) {
    x.push(y);
  });

 return x;
});

and another function which calls this function but it always returns undefined.
How can i make the function wait till mongoose has finished filling up the array?

Thanks for the help! My life

Body:
The solution proposed by @orhankutlu should work fine.

I will give another solution using promise. You can choose one between these two solutions depending on your style of programming.

Solution using promise:

function getEvents() {
    return new Promise(function(resolve, reject){
        dbCollection['e'].find({}, function(error, results) {
           if (error) return reject(error);

           var x = [];
           results.forEach(function(y){
              x.push(y);
           });
           // forEach() is a blocking call,
           // so the promise will be resolved only
           // after the forEach completes
           return resolve(x);
        });
    });
};

Calling getEvents():

getEvents().then(function(result){
    console.log(result);   //should print 'x'
}).catch(function(err){
    // Handle error here in case the promise is rejected
});

I will encourage you to try both the approaches, ie, using callbacks and using promises. Hope you find it useful!


问:
Hide/Show jcf Select (dropdown) from jquery
My select dropdown

```<code><select class="model" id="model" name="model" style="display:none;">
    <option value="model1">Model1</option>
    <option value="model2">Model2</option>
    <option value="model3">Model3</option>
    <option value="model4">Model4</option>
</select>
</code>```

I am using jcf plugin for select. Refrence https://www.psd2html.com/js-custom-forms/

Now i want to display my dropdown from jquery.
jQuery("select[name='model']").show();

But this is not working anymore.How can i change display:none to display:block ?

答:
It is not working because jcf plugin hides native element and create equivalent custom element as next sibling to it. In this case, the select element is hidden by default and hence jcf do not create equivalent element out of it.

Hence you need to show the select element first and then initialize jcf plugin:

```<code>$("#model").css('display','block');
jcf.replaceAll();
</code>```

Body:
My select dropdown

<select class="model" id="model" name="model" style="display:none;">
    <option value="model1">Model1</option>
    <option value="model2">Model2</option>
    <option value="model3">Model3</option>
    <option value="model4">Model4</option>
</select>

I am using jcf plugin for select. Refrence https://www.psd2html.com/js-custom-forms/

Now i want to display my dropdown from jquery.
jQuery("select[name='model']").show();

But this is not working anymore.How can i change display:none to display:block ?

Body:
It is not working because jcf plugin hides native element and create equivalent custom element as next sibling to it. In this case, the select element is hidden by default and hence jcf do not create equivalent element out of it.

Hence you need to show the select element first and then initialize jcf plugin:

$("#model").css('display','block');
jcf.replaceAll();


答:
Use this regex to get the link between "yourlink"

```<code>(?<=")(.*)(?=")
</code>```

Note: It works in PHP but not in Javascript. Lookbehind is not supported in Javascript!

Note 2: This answer is only specified for your SHORT information. I would suggest you to update your Question with more Details to get an better Code Sample!

Title: Regex Image url

Body:
I'm trying to pre replace to get dynamic url,

Code is:

I need to extract: only /List/Detail/c0954c57-57ca-4f32-841d-de2b61a5087c/5358455

Ive tried: \/Listing\/AdDetail\/

Body:
Use this regex to get the link between "yourlink"

(?<=")(.*)(?=")

Note: It works in PHP but not in Javascript. Lookbehind is not supported in Javascript!

Note 2: This answer is only specified for your SHORT information. I would suggest you to update your Question with more Details to get an better Code Sample!


问:
javax.mail.MessagingException: Unknown SMTP host
I am developing the application which sent mail using JAVA email API.
I use the office SMTP server
Mail is sent properly in the office network but outside the office network or another data connection mail can not be sent.

It Show the error could not connect to the SMTP host
it says unknown SMTP host.

答:
As you are using office mail id. Most of the time due to security reason Technical team/Network team disable the outside network. So, you are able to post your main inside the office. Please contact your network team, they will give some sort of solution for host configuration.
Most likely you have a firewall on your machine or on your network
that is preventing you from connecting.

If also not resolving, please post the screen shot of your error.

Thanks,
Rakesh


问:
TS Observable & ng: proper templating syntax
I have an observable "applicationDetail" (private applicationDetail: Observable<ApplicationDetail>;). I bind the values like this:

```<code><h2 class="detailViewH2">{{ (applicationDetail | async)?.AttendeeName }}</h2>
<p>{{ (applicationDetail | async)?.AttendeeFunction }} </p>
</code>```

This doesn't seem like proper templating syntax to me, isn't there a way to generally say "applicationDetail" will be async and all it's props should use the safe navigation operator?

答:
In Angular4 you can work around this using *ngIf

```<code><ng-container *ngIf="(applicationDetail | async) as foo">
  <h2 class="detailViewH2">{{foo.AttendeeName }}</h2>
  <p>{{foo.AttendeeFunction }} </p>
</ng-container>
</code>```

You can also create your own structural directive that doesn't remove the content when the expression is false but otherwise provides this functionality.

Body:
I have an observable "applicationDetail" (private applicationDetail: Observable<ApplicationDetail>;). I bind the values like this:

{{ (applicationDetail | async)?.AttendeeName }}

{{ (applicationDetail | async)?.AttendeeFunction }}

This doesn't seem like proper templating syntax to me, isn't there a way to generally say "applicationDetail" will be async and all it's props should use the safe navigation operator?

Body:
In Angular4 you can work around this using *ngIf

<ng-container *ngIf="(applicationDetail | async) as foo">
  <h2 class="detailViewH2">{{foo.AttendeeName }}</h2>
  <p>{{foo.AttendeeFunction }} </p>
</ng-container>

You can also create your own structural directive that doesn't remove the content when the expression is false but otherwise provides this functionality.


问:
Using GMail as an interface to my database
What if I choose to use GMail's awesome mail archive search capabilities on my database? What if, for every transaction that my database is responsible, I emailed details of that transaction to a GMail address that exists for the sole purpose of searching and retrieving transactions.

Anyone logged into that account could search according to labels, invoice numbers, customer names - whatever using Google's search engine. The results are presented as 'email messages'.

Imagine a user working from the standard (web-based) GMail account searches for an invoice number via GMail's search box - he's returned all instances where the db did anything that included that unique number. Opening any of these 'email messages' would have the static text text included at the time of the transactions (historical and tracking gold) but could also carry a Gadget that could transform the 'message' into an editor so as to execute a new transaction on that invoice.

Imagine further that I wasn't the first one to think of this - cuz surely i'm not - and even if i were, i'm not smart enough to execute the idea alone.

Are you aware of efforts similar to this?

thx

[?belongs on superuser instead?]

答: An interesting idea, however given your search parameters it might be unreliable. Although gmail's search is great, I have found issues when searching for partial terms. Case in point, I had an email whose subject line was "stuffas". When I searched for "stuffa" I got no results, when I searched for "stuffas" I got the email in the search result. Additionally, I had an email with an 8 digit number inside the body. When I searched for 7 digits out of 8, I got no results, but when I put all 8 digits, the email appeared in the results. So, search in gmail may not be as powerful of a solution as you think. Again this is my experience, I'd love to hear if someone is able to partial search numbers in gmail.</p>


问:
Indesign Script to Apply "Object Style" to Specific XML Structure Tags
Is there a way to come up with a javascript within InDesign that after importing images via XML into InDesign, I can run a script that will map a specific object style to a particular tag? Just like the Tags allow when it comes with Paragraph styles and Character styles. Do not know why Adobe did not allow object styles to work the same way.</p>

答:
I found somewhat same question posted on Adobe forums ..
Following is the link for it..

https://forums.adobe.com/thread/740264

Hope this Helps..


问:
Calling DAL that uses Entity Framework
I have a Web API application that is calling a DAL library. The DAL library interacts with a SQL database using Entity Framework. Now, I need to set the connection string to the database in the Web API project. This requires me to install EF in the Web API project as well. Is there any way I can set the connection string in the Web API project without having to install EF?</p>

答:
You can wrap the DbContext, this way, the DAL project is not exposing any EF related components. By doing this you don't have to install EF into every project you reference the DAL project in.

```<code>public class DataContextWrapper : IDisposable {
    public DataContextWrapper() {
        DataContext = new DataContext();
    }

    internal DataContext DataContext { get; private set; }

    public void Dispose() {
        DataContext.Dispose();
    }
}
</code>```

As long as your repositories etc are also in the DAL project and they do not return database entities but models, you will be fine.

Title: Calling DAL that uses Entity Framework

Body:
You can wrap the DbContext, this way, the DAL project is not exposing any EF related components. By doing this you don't have to install EF into every project you reference the DAL project in.

public class DataContextWrapper : IDisposable {
    public DataContextWrapper() {
        DataContext = new DataContext();
    }

    internal DataContext DataContext { get; private set; }

    public void Dispose() {
        DataContext.Dispose();
    }
}

As long as your repositories etc are also in the DAL project and they do not return database entities but models, you will be fine.