问:
ECDSA get public key in C#
I can't figure this out it should be super simple.

I have both the C# and BouncyCastle (also C#) crypto libraries.

I just need to give a byte array as private key, specify the curve used and get the public key.

My curve is SEC-P-256-K1/secp256k1, but really if you can just help me navigate the sea of options and classes I don't need or care about I can set that myself.

答:
Using Vasiliy's answer I was struggling to get the same results as this tutorial but finally got the correct results after changing his code by adding .Normalize():

```<code>public Tuple<byte[],byte[]> GetPublicKey(byte[] privateKey){
    BigInteger privKeyInt = new BigInteger(+1, privateKey);

    var parameters = SecNamedCurves.GetByName("secp256k1");
    ECPoint qa = parameters.G.Multiply(privKeyInt).Normalize();

    byte[] pubKeyX = qa.XCoord.ToBigInteger().ToByteArrayUnsigned();
    byte[] pubKeyY = qa.YCoord.ToBigInteger().ToByteArrayUnsigned();

    return Tuple.Create(pubKeyX, pubKeyY);
}
</code>```

I'd add this as a comment but alas not enough reputation.

Title: ECDSA get public key in C#

Body:
Using Vasiliy's answer I was struggling to get the same results as this tutorial but finally got the correct results after changing his code by adding .Normalize():

public Tuple<byte[],byte[]> GetPublicKey(byte[] privateKey){
    BigInteger privKeyInt = new BigInteger(+1, privateKey);

    var parameters = SecNamedCurves.GetByName("secp256k1");
    ECPoint qa = parameters.G.Multiply(privKeyInt).Normalize();

    byte[] pubKeyX = qa.XCoord.ToBigInteger().ToByteArrayUnsigned();
    byte[] pubKeyY = qa.YCoord.ToBigInteger().ToByteArrayUnsigned();

    return Tuple.Create(pubKeyX, pubKeyY);
}

I'd add this as a comment but alas not enough reputation.


来源: stackexchange

问:
Insert statement with subquery which has inner join statement
I have 3 tables in my SQL Server database named College, University, OldSyllabus.

Table College has 1000 rows with columns such as DateOfJoining, studentName

Table University has 50 rows with columns such as DateOfCourseRevision, courseName

I need to write an insert statement to push records in table OldSyllabus by comparing University table DateOfCourseRevision column with College table DateOfJoining column

All records from College table to be inserted into OldSyllabus by comparing the DateOfCourseRevision <= DateOfJoining

Query:

```<code>INSERT INTO [OS].[OldSyllabus] (StudenName, Address)
VALUES
    ((SELECT C.Name
      FROM [COL].[College] AS c
      INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                         AND c.Date <= u.Date),
     (SELECT C.Address
      FROM [COL].[College] AS c
      INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                         AND c.Date <= u.Date))
</code>```

I get an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

答:
Assuming the table oldsyllabus table has been created and has columns same as that of college, Use the query below to fetch the data from the college table and store:

```<code>INSERT INTO `oldsyllabus`(`DateofJoining`, `studentName`) SELECT college.DateofJoining, college.studentName FROM college JOIN university WHERE university.dateOfCourseRevision <= college.DateofJoining;
</code>```

In case the table or columns haven't been created go to:
Create table (structure) from existing table
Here it explains how to create tables from existing ones

ContentLicense: CC BY-SA 4.0

Body:
I have 3 tables in my SQL Server database named College, University, OldSyllabus.

Table College has 1000 rows with columns such as DateOfJoining, studentName

Table University has 50 rows with columns such as DateOfCourseRevision, courseName

I need to write an insert statement to push records in table OldSyllabus by comparing University table DateOfCourseRevision column with College table DateOfJoining column

All records from College table to be inserted into OldSyllabus by comparing the DateOfCourseRevision <= DateOfJoining

Query:

INSERT INTO [OS].[OldSyllabus] (StudenName, Address)
VALUES
    ((SELECT C.Name
      FROM [COL].[College] AS c
      INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                         AND c.Date <= u.Date),
     (SELECT C.Address
      FROM [COL].[College] AS c
      INNER JOIN [UNI].[University] AS u ON c.CourseName = u.CourseName
                                         AND c.Date <= u.Date))

I get an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Body:
Assuming the table oldsyllabus table has been created and has columns same as that of college, Use the query below to fetch the data from the college table and store:

INSERT INTO `oldsyllabus`(`DateofJoining`, `studentName`) SELECT college.DateofJoining, college.studentName FROM college JOIN university WHERE university.dateOfCourseRevision <= college.DateofJoining;

In case the table or columns haven't been created go to:
Create table (structure) from existing table
Here it explains how to create tables from existing ones


问:
How can i do a multi-gradient background with 3 colors and a lot of curves?
I need to realize a background like this in CSS:

For now I've done something similar, but of course is totally not the same thing:

body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

div.divbg {
  position: absolute;
  width: 100%;
  height: 100%;
}

#layer1 {
  background: #4F598A;
  z-index: 100;
}

#layer2 {
  z-index: 110;
  /*background-image: linear-gradient(90deg, rgba(186,52,41,0) 40%, rgba(186,52,41,1) 100%);*/
  background-image: linear-gradient(90deg, rgba(186, 52, 41, 0) 43%, rgba(186, 52, 41, 1) 51%);
  /*-webkit-clip-path: polygon(100% 0, 54% 1%, 48% 12%, 45% 24%, 45% 36%, 46% 52%, 48% 71%, 53% 93%, 75% 97%, 100% 81%, 100% 53%);*/
  /*clip-path: polygon(100% 0, 54% 1%, 48% 12%, 45% 24%, 45% 36%, 46% 52%, 48% 71%, 53% 93%, 75% 97%, 100% 81%, 100% 53%);*/
  /*-webkit-clip-path: polygon(51% 0, 50% 5%, 49% 12%, 49% 21%, 50% 35%, 52% 58%, 55% 82%, 59% 100%, 80% 100%, 100% 100%, 100% 0);*/
  /*clip-path: polygon(51% 0, 50% 5%, 49% 12%, 49% 21%, 50% 35%, 52% 58%, 55% 82%, 59% 100%, 80% 100%, 100% 100%, 100% 0);*/
  /*filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#BA3429', endColorstr='#BA3429',GradientType=1 );*/
  /*box-shadow: inset 943px -164px 69px 100px #4F598A;*/
  /*background: red;*/
  opacity: 0.8;
}

#layer3 {
  z-index: 120;
  width: 100%;
  height: 50%;
  /*background: #000 !important;*/
  bottom: 0;
  content: '';
  z-index: 99999 !important;
  position: absolute;
  background-image: -webkit-linear-gradient(270deg, rgba(0, 255, 255, 0) 0%, rgba(94, 151, 73, 1) 100%);
  /*clip-path: polygon(65% 7%, 49% 76%, 2% 66%, 8% 9%, 33% 3%);*/
  /*filter: blur(20px);*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divbg" id="layer1"> </div>
<div class="divbg" id="layer2"> </div>
<div class="divbg" id="layer3"> </div></code>```

codepen

Then, I tried to "cut" my gradient elements with clip-path, but of course this is totally worse:

body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

div.divbg {
  position: absolute;
  width: 100%;
  height: 100%;
}

#layer1 {
  background: #4F598A;
  z-index: 100;
}

#layer2 {
  z-index: 110;
  /*background-image: linear-gradient(90deg, rgba(186,52,41,0) 40%, rgba(186,52,41,1) 100%);*/
  background-image: linear-gradient(90deg, rgba(186, 52, 41, 0) 43%, rgba(186, 52, 41, 1) 51%);
  /*-webkit-clip-path: polygon(100% 0, 54% 1%, 48% 12%, 45% 24%, 45% 36%, 46% 52%, 48% 71%, 53% 93%, 75% 97%, 100% 81%, 100% 53%);*/
  /*clip-path: polygon(100% 0, 54% 1%, 48% 12%, 45% 24%, 45% 36%, 46% 52%, 48% 71%, 53% 93%, 75% 97%, 100% 81%, 100% 53%);*/
  /*-webkit-clip-path: polygon(51% 0, 50% 5%, 49% 12%, 49% 21%, 50% 35%, 52% 58%, 55% 82%, 59% 100%, 80% 100%, 100% 100%, 100% 0);*/
  clip-path: polygon(51% 0, 50% 5%, 49% 12%, 49% 21%, 50% 35%, 52% 58%, 55% 82%, 59% 100%, 80% 100%, 100% 100%, 100% 0);
  /*filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#BA3429', endColorstr='#BA3429',GradientType=1 );*/
  box-shadow: inset 943px -164px 69px 100px #4F598A;
  /*background: red;*/
  opacity: 0.8;
}

#layer3 {
  z-index: 120;
  width: 100%;
  height: 50%;
  /*background: #000 !important;*/
  bottom: 0;
  content: '';
  z-index: 99999 !important;
  position: absolute;
  background-image: -webkit-linear-gradient(270deg, rgba(0, 255, 255, 0) 0%, rgba(94, 151, 73, 1) 100%);
  /*clip-path: polygon(65% 7%, 49% 76%, 2% 66%, 8% 9%, 33% 3%);*/
  /*filter: blur(20px);*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divbg" id="layer1"> </div>
<div class="divbg" id="layer2"> </div>
<div class="divbg" id="layer3"> </div></code>```

codepen

I don't have any other idea to doing this.

Is there anything else that can I try?

答:
I will consider this previous answer where I will add an extra layer above. You will have a bottom linear-gradient then above it an SVG shape where I also applied a gradient and above a radial-gradient that start from the bottom:

.container {
  width: 400px;
  height: 400px;
  background:
    radial-gradient(100% 100% at bottom, #689140 20%, rgba(104, 145, 64, 0.55) 50%, transparent),
    url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" ><defs><linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="%234c5585" /><stop offset="100%" stop-color="%23894955" /></linearGradient></defs><path d="M32 64 C46 54 24 24 36 0 L0 0 L0 64 Z" fill="url(%23grad)" /></svg>') center/100% 100%,
    linear-gradient(to right, #b33529 40%, #91454b);

  display:flex;
  justify-content:space-around;
  align-items:center;
  flex-direction:column;
  color:#fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
</div></code>```

You can keep adding more layer either using linear-gradient, radial-gradient or the SVG by adjusting the shape and the gradient inside.

Body:
I need to realize a background like this in CSS:

For now I've done something similar, but of course is totally not the same thing:

body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

div.divbg {
  position: absolute;
  width: 100%;
  height: 100%;
}

#layer1 {
  background: #4F598A;
  z-index: 100;
}

#layer2 {
  z-index: 110;
  /*background-image: linear-gradient(90deg, rgba(186,52,41,0) 40%, rgba(186,52,41,1) 100%);*/
  background-image: linear-gradient(90deg, rgba(186, 52, 41, 0) 43%, rgba(186, 52, 41, 1) 51%);
  /*-webkit-clip-path: polygon(100% 0, 54% 1%, 48% 12%, 45% 24%, 45% 36%, 46% 52%, 48% 71%, 53% 93%, 75% 97%, 100% 81%, 100% 53%);*/
  /*clip-path: polygon(100% 0, 54% 1%, 48% 12%, 45% 24%, 45% 36%, 46% 52%, 48% 71%, 53% 93%, 75% 97%, 100% 81%, 100% 53%);*/
  /*-webkit-clip-path: polygon(51% 0, 50% 5%, 49% 12%, 49% 21%, 50% 35%, 52% 58%, 55% 82%, 59% 100%, 80% 100%, 100% 100%, 100% 0);*/
  /*clip-path: polygon(51% 0, 50% 5%, 49% 12%, 49% 21%, 50% 35%, 52% 58%, 55% 82%, 59% 100%, 80% 100%, 100% 100%, 100% 0);*/
  /*filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#BA3429', endColorstr='#BA3429',GradientType=1 );*/
  /*box-shadow: inset 943px -164px 69px 100px #4F598A;*/
  /*background: red;*/
  opacity: 0.8;
}

#layer3 {
  z-index: 120;
  width: 100%;
  height: 50%;
  /*background: #000 !important;*/
  bottom: 0;
  content: '';
  z-index: 99999 !important;
  position: absolute;
  background-image: -webkit-linear-gradient(270deg, rgba(0, 255, 255, 0) 0%, rgba(94, 151, 73, 1) 100%);
  /*clip-path: polygon(65% 7%, 49% 76%, 2% 66%, 8% 9%, 33% 3%);*/
  /*filter: blur(20px);*/
}

codepen

Then, I tried to "cut" my gradient elements with clip-path, but of course this is totally worse:

body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

div.divbg {
  position: absolute;
  width: 100%;
  height: 100%;
}

#layer1 {
  background: #4F598A;
  z-index: 100;
}

#layer2 {
  z-index: 110;
  /*background-image: linear-gradient(90deg, rgba(186,52,41,0) 40%, rgba(186,52,41,1) 100%);*/
  background-image: linear-gradient(90deg, rgba(186, 52, 41, 0) 43%, rgba(186, 52, 41, 1) 51%);
  /*-webkit-clip-path: polygon(100% 0, 54% 1%, 48% 12%, 45% 24%, 45% 36%, 46% 52%, 48% 71%, 53% 93%, 75% 97%, 100% 81%, 100% 53%);*/
  /*clip-path: polygon(100% 0, 54% 1%, 48% 12%, 45% 24%, 45% 36%, 46% 52%, 48% 71%, 53% 93%, 75% 97%, 100% 81%, 100% 53%);*/
  /*-webkit-clip-path: polygon(51% 0, 50% 5%, 49% 12%, 49% 21%, 50% 35%, 52% 58%, 55% 82%, 59% 100%, 80% 100%, 100% 100%, 100% 0);*/
  clip-path: polygon(51% 0, 50% 5%, 49% 12%, 49% 21%, 50% 35%, 52% 58%, 55% 82%, 59% 100%, 80% 100%, 100% 100%, 100% 0);
  /*filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#BA3429', endColorstr='#BA3429',GradientType=1 );*/
  box-shadow: inset 943px -164px 69px 100px #4F598A;
  /*background: red;*/
  opacity: 0.8;
}

#layer3 {
  z-index: 120;
  width: 100%;
  height: 50%;
  /*background: #000 !important;*/
  bottom: 0;
  content: '';
  z-index: 99999 !important;
  position: absolute;
  background-image: -webkit-linear-gradient(270deg, rgba(0, 255, 255, 0) 0%, rgba(94, 151, 73, 1) 100%);
  /*clip-path: polygon(65% 7%, 49% 76%, 2% 66%, 8% 9%, 33% 3%);*/
  /*filter: blur(20px);*/
}

codepen

I don't have any other idea to doing this.

Is there anything else that can I try?

Body:
I will consider this previous answer where I will add an extra layer above. You will have a bottom linear-gradient then above it an SVG shape where I also applied a gradient and above a radial-gradient that start from the bottom:

.container {
  width: 400px;
  height: 400px;
  background:
    radial-gradient(100% 100% at bottom, #689140 20%, rgba(104, 145, 64, 0.55) 50%, transparent),
    url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" ><defs><linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="%234c5585" /><stop offset="100%" stop-color="%23894955" /></linearGradient></defs><path d="M32 64 C46 54 24 24 36 0 L0 0 L0 64 Z" fill="url(%23grad)" /></svg>') center/100% 100%,
    linear-gradient(to right, #b33529 40%, #91454b);

  display:flex;
  justify-content:space-around;
  align-items:center;
  flex-direction:column;
  color:#fff;
}

<div class="container">
</div>

You can keep adding more layer either using linear-gradient, radial-gradient or the SVG by adjusting the shape and the gradient inside.


问:
How can I remove certain characters from a string only if it comes before a specific character
I have a string that has parenthesis in it. I want to write a function to remove the parenthesis if they exist and what's inside only if it comes before a comma. Sometimes in my string, there may be more than 1 set of parenthesis in the string; but I would only like to remove the set before the parenthesis. </p>

```<code>var string1 = "Dog (big), 0"
var string2 = "Dog (medium) (black), 1"
var string3 = "Dog (small) (brown), 1"

What I want:

string1 = "Dog, 0"
string1 = "Dog (medium), 0"
string1 = "Dog (small), 0"
</code>```

答:
If you dont want to use regex:   </p>

```<code>var string2 = "Dog (medium) (black), 1";
    string2 = string2.Replace(string2.Substring(string2.LastIndexOf('(') - 1, string2.LastIndexOf(')') - string2.LastIndexOf('(') + 2), "");
</code>```

Body:
I have a string that has parenthesis in it. I want to write a function to remove the parenthesis if they exist and what's inside only if it comes before a comma. Sometimes in my string, there may be more than 1 set of parenthesis in the string; but I would only like to remove the set before the parenthesis.

var string1 = "Dog (big), 0"
var string2 = "Dog (medium) (black), 1"
var string3 = "Dog (small) (brown), 1"

What I want:

string1 = "Dog, 0"
string1 = "Dog (medium), 0"
string1 = "Dog (small), 0"

Body:
If you dont want to use regex:

var string2 = "Dog (medium) (black), 1";
    string2 = string2.Replace(string2.Substring(string2.LastIndexOf('(') - 1, string2.LastIndexOf(')') - string2.LastIndexOf('(') + 2), "");


问:
Scala Swing skips repaint of the Frame
I am currently working on an implementation of the game Othello in Scala and so far it's working pretty nicely. When implementing the GUI though (using Scala Swing) I've stumbled across an issue that I can't seem to fix.

When playing against the computer opponent the Frame seems to be repainted only when the bot is done making its move.

The game is also playable through the terminal and doing so updates the Frame properly every time regardless of the player configuration (Player vs Player or Player vs Computer). Also playing player vs player using the GUI exclusively presents no issues at all.

It might be an oversight on my behalf, but so far I am unable to find a solution and would greatly appreciate any help.

So far I have tried various combinations of revalidating and repainting the individual panels, adding and removing listeners, changing my implementation of the reactor pattern to the one provided by Scala Swing, adding Thread.sleep to see if there could be a scheduling conflict of sorts.

import java.awt.Color

import othello.controller.Controller
import javax.swing.ImageIcon
import javax.swing.border.LineBorder

import scala.swing.event.MouseClicked
import scala.swing.{BorderPanel, BoxPanel, Dimension, FlowPanel, GridPanel, Label, Orientation}

class TablePanel(controller: Controller) extends FlowPanel {

  val sides = 32
  val sidesColor: Color = Color.lightGray
  val squareSize = 52

  def tableSize: Int = controller.board.size

  def edgeLength: Int = tableSize * squareSize

  def rows: BoxPanel = new BoxPanel(Orientation.Vertical) {
    background = sidesColor
    preferredSize = new Dimension(sides, edgeLength)
    contents += new Label {
      preferredSize = new Dimension(sides, sides)
    }
    contents += new GridPanel(tableSize, 1) {
      background = sidesColor
      for { i <- 1 to rows } contents += new Label(s"$i")
    }
  }

  def columns: GridPanel = new GridPanel(1, tableSize) {
    background = sidesColor
    preferredSize = new Dimension(edgeLength, sides)
    for { i <- 0 until columns } contents += new Label(s"${(i + 65).toChar}")
  }

  def table: GridPanel = new GridPanel(tableSize, tableSize) {
    background = new Color(10, 90, 10)
    for {
      col <- 0 until columns
      row <- 0 until rows
    } contents += square(col, row)
  }

  def square(row: Int, col: Int): Label = new Label {
    border = new LineBorder(new Color(30, 30, 30, 140), 1)
    preferredSize = new Dimension(squareSize, squareSize)
    icon = controller.board.valueOf(col, row) match {
      case -1 => new ImageIcon("resources/big_dot.png")
      case 0  => new ImageIcon("resources/empty.png")
      case 1  => new ImageIcon("resources/black_shadow.png")
      case 2  => new ImageIcon("resources/white_shadow.png")
    }
    listenTo(mouse.clicks)
    reactions += {
      case _: MouseClicked =>
        if (controller.options.contains((col, row))) controller.set(col, row)
        else if (controller.board.gameOver) controller.newGame()
        else controller.highlight()
    }
  }

  def redraw(): Unit = {
    contents.clear
    contents += new BorderPanel {
      add(rows, BorderPanel.Position.West)
      add(new BoxPanel(Orientation.Vertical) {
        contents += columns
        contents += table
      }, BorderPanel.Position.East)
    }
    repaint
  }
}
```

<pre class="lang-scala prettyprint-override"><code>import scala.swing._
import othello.controller._
import othello.util.Observer

import scala.swing.event.Key

class SwingGui(controller: Controller) extends Frame with Observer {

  controller.add(this)

  lazy val tablePanel = new TablePanel(controller)

  lazy val mainFrame: MainFrame = new MainFrame {
    title = "Othello"
    menuBar = menus
    contents = tablePanel
    centerOnScreen
    // peer.setAlwaysOnTop(true)
    resizable = false
    visible = true
  }

  def menus: MenuBar = new MenuBar {
    contents += new Menu("File") {
      mnemonic = Key.F
      contents += new MenuItem(Action("New Game") {
        controller.newGame()
      })
      contents += new MenuItem(Action("Quit") {
        controller.exit()
      })
    }
    contents += new Menu("Edit") {
      mnemonic = Key.E
      contents += new MenuItem(Action("Undo") {
        controller.undo()
      })
      contents += new MenuItem(Action("Redo") {
        controller.redo()
      })
    }
    contents += new Menu("Options") {
      mnemonic = Key.O
      contents += new MenuItem(Action("Highlight possible moves") {
        controller.highlight()
      })
      contents += new MenuItem(Action("Reduce board size") {
        controller.resizeBoard("-")
      })
      contents += new MenuItem(Action("Increase board size") {
        controller.resizeBoard("+")
      })
      contents += new MenuItem(Action("Reset board size") {
        controller.resizeBoard(".")
      })
      contents += new Menu("Game mode") {
        contents += new MenuItem(Action("Player vs. Computer") {
          controller.setupPlayers("1")
        })
        contents += new MenuItem(Action("Player vs. Player") {
          controller.setupPlayers("2")
        })
      }
    }
  }

  def update: Boolean = {
    tablePanel.redraw()
    mainFrame.pack
    mainFrame.centerOnScreen
    mainFrame.repaint
    true
  }
}

</code>```

The expected behavior is a repainted Frame on every turn. The actual result is the Frame only being repainted after the opponent made a move. It only happens when playing player vs bot exclusively through clicking the UI.

答:
As Rich suggested, the solution was concurrency. Making the search algorithm a Future-type solved the issue for now. It might not be the cleanest implementation as it is the first time I'm using Future, but this is what it looks like now:

  def selectAndSet(): Future[_] = Future(if (!board.gameOver && player.isBot) {
    new MoveSelector(this).select() match {
      case Success(square) => set(square)
      case _ => omitPlayer()
    }
    selectAndSet()
  })(ExecutionContext.global)
```

Title: Scala Swing skips repaint of the Frame

Body:
I am currently working on an implementation of the game Othello in Scala and so far it's working pretty nicely. When implementing the GUI though (using Scala Swing) I've stumbled across an issue that I can't seem to fix.

When playing against the computer opponent the Frame seems to be repainted only when the bot is done making its move.

The game is also playable through the terminal and doing so updates the Frame properly every time regardless of the player configuration (Player vs Player or Player vs Computer). Also playing player vs player using the GUI exclusively presents no issues at all.

It might be an oversight on my behalf, but so far I am unable to find a solution and would greatly appreciate any help.

So far I have tried various combinations of revalidating and repainting the individual panels, adding and removing listeners, changing my implementation of the reactor pattern to the one provided by Scala Swing, adding Thread.sleep to see if there could be a scheduling conflict of sorts.

import java.awt.Color

import othello.controller.Controller
import javax.swing.ImageIcon
import javax.swing.border.LineBorder

import scala.swing.event.MouseClicked
import scala.swing.{BorderPanel, BoxPanel, Dimension, FlowPanel, GridPanel, Label, Orientation}

class TablePanel(controller: Controller) extends FlowPanel {

  val sides = 32
  val sidesColor: Color = Color.lightGray
  val squareSize = 52

  def tableSize: Int = controller.board.size

  def edgeLength: Int = tableSize * squareSize

  def rows: BoxPanel = new BoxPanel(Orientation.Vertical) {
    background = sidesColor
    preferredSize = new Dimension(sides, edgeLength)
    contents += new Label {
      preferredSize = new Dimension(sides, sides)
    }
    contents += new GridPanel(tableSize, 1) {
      background = sidesColor
      for { i <- 1 to rows } contents += new Label(s"$i")
    }
  }

  def columns: GridPanel = new GridPanel(1, tableSize) {
    background = sidesColor
    preferredSize = new Dimension(edgeLength, sides)
    for { i <- 0 until columns } contents += new Label(s"${(i + 65).toChar}")
  }

  def table: GridPanel = new GridPanel(tableSize, tableSize) {
    background = new Color(10, 90, 10)
    for {
      col <- 0 until columns
      row <- 0 until rows
    } contents += square(col, row)
  }

  def square(row: Int, col: Int): Label = new Label {
    border = new LineBorder(new Color(30, 30, 30, 140), 1)
    preferredSize = new Dimension(squareSize, squareSize)
    icon = controller.board.valueOf(col, row) match {
      case -1 => new ImageIcon("resources/big_dot.png")
      case 0  => new ImageIcon("resources/empty.png")
      case 1  => new ImageIcon("resources/black_shadow.png")
      case 2  => new ImageIcon("resources/white_shadow.png")
    }
    listenTo(mouse.clicks)
    reactions += {
      case _: MouseClicked =>
        if (controller.options.contains((col, row))) controller.set(col, row)
        else if (controller.board.gameOver) controller.newGame()
        else controller.highlight()
    }
  }

  def redraw(): Unit = {
    contents.clear
    contents += new BorderPanel {
      add(rows, BorderPanel.Position.West)
      add(new BoxPanel(Orientation.Vertical) {
        contents += columns
        contents += table
      }, BorderPanel.Position.East)
    }
    repaint
  }
}

import scala.swing._
import othello.controller._
import othello.util.Observer

import scala.swing.event.Key

class SwingGui(controller: Controller) extends Frame with Observer {

  controller.add(this)

  lazy val tablePanel = new TablePanel(controller)

  lazy val mainFrame: MainFrame = new MainFrame {
    title = "Othello"
    menuBar = menus
    contents = tablePanel
    centerOnScreen
    // peer.setAlwaysOnTop(true)
    resizable = false
    visible = true
  }

  def menus: MenuBar = new MenuBar {
    contents += new Menu("File") {
      mnemonic = Key.F
      contents += new MenuItem(Action("New Game") {
        controller.newGame()
      })
      contents += new MenuItem(Action("Quit") {
        controller.exit()
      })
    }
    contents += new Menu("Edit") {
      mnemonic = Key.E
      contents += new MenuItem(Action("Undo") {
        controller.undo()
      })
      contents += new MenuItem(Action("Redo") {
        controller.redo()
      })
    }
    contents += new Menu("Options") {
      mnemonic = Key.O
      contents += new MenuItem(Action("Highlight possible moves") {
        controller.highlight()
      })
      contents += new MenuItem(Action("Reduce board size") {
        controller.resizeBoard("-")
      })
      contents += new MenuItem(Action("Increase board size") {
        controller.resizeBoard("+")
      })
      contents += new MenuItem(Action("Reset board size") {
        controller.resizeBoard(".")
      })
      contents += new Menu("Game mode") {
        contents += new MenuItem(Action("Player vs. Computer") {
          controller.setupPlayers("1")
        })
        contents += new MenuItem(Action("Player vs. Player") {
          controller.setupPlayers("2")
        })
      }
    }
  }

  def update: Boolean = {
    tablePanel.redraw()
    mainFrame.pack
    mainFrame.centerOnScreen
    mainFrame.repaint
    true
  }
}

The expected behavior is a repainted Frame on every turn. The actual result is the Frame only being repainted after the opponent made a move. It only happens when playing player vs bot exclusively through clicking the UI.


问:
From a LightBDD Decorator, how to retrieve the scenario's current ChromeDriver from the DependencyResolver?
I'm using LightBDD to run Selenium tests and I'm trying to automatically take a screenshot whenever a scenario fails. I wrote a class-level LightBDD Decorator to do this but I retrieve a new instance of the ChromeDriver from the ResourcePool instead of retrieving the current ChromeDriver.

How can retrieve the scenario's current ChromeDriver instead of a new instance?

More Details

I'm registering the ChromeDriver as in the provided example, i.e.:

private void ConfigureContainer(ContainerConfigurator config)
{
    config.RegisterInstance(
        new ResourcePool<ChromeDriver>(CreateDriver),
        new RegistrationOptions());
}

private ChromeDriver CreateDriver()
{
    var driver = new ChromeDriver();
    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(0);
    return driver;
}
```

<p>My Decorator:</p>

<pre class="lang-cs prettyprint-override"><code>[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class TakeScreenshotOnErrorAttribute : Attribute, IScenarioDecoratorAttribute
{
    public async Task ExecuteAsync(IScenario scenario, Func<Task> scenarioInvocation)
    {
        try {
            await scenarioInvocation();
        }
        catch (Exception ex) {
            await TakeScreenshot(scenario);
        }
    }

    public int Order { get; set; }

    private static async Task TakeScreenshot(IScenario scenario)
    {
        try {
            var driverHandle = scenario.DependencyResolver.Resolve(typeof(ResourceHandle<ChromeDriver>));
            var driver = await ((ResourceHandle<ChromeDriver>) driverHandle).ObtainAsync();
            var screenshot = driver.GetScreenshot();
            screenshot.SaveAsFile(@"c:\temp\error.png");
        }
        catch {
            /* Ignore */
        }
    }
}
</code>```

The debugger clearly shows that a second instance is created:

Version: LightBDD 3.0.1 with NUnit3

答:
The default behavior of LightBDD DI container is to provide a new instance of the requested dependency every time Resolve() method is called.

To make it working as expected a more advanced DI has to be used (like LightBDD.Autofac package) and ResourceHandle<ChromeDriver> has to be registered with a scope lifetime:

public class ConfiguredLightBddScopeAttribute : LightBddScopeAttribute
{
    protected override void OnConfigure(LightBddConfiguration configuration)
    {
        configuration.DependencyContainerConfiguration()
            .UseAutofac(ConfigureContainer());
    }

    private ContainerBuilder ConfigureContainer()
    {
        var builder = new ContainerBuilder();
        builder.RegisterInstance(new ResourcePool<ChromeDriver>(CreateDriver));
        builder.RegisterType<ResourceHandle<ChromeDriver>>().InstancePerLifetimeScope();
        // ^-- this makes the difference
        return builder;
    }

    private ChromeDriver CreateDriver()
    {
        var driver = new ChromeDriver();
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(0);
        return driver;
    }
}
```

It would mean that while each scenario will get own copy of the handle, the scenario code and the decorator code will get the same instance.

I have provided the working example in a response on the LightBDD issues page: https://github.com/LightBDD/LightBDD/issues/186

Body:
I'm using LightBDD to run Selenium tests and I'm trying to automatically take a screenshot whenever a scenario fails. I wrote a class-level LightBDD Decorator to do this but I retrieve a new instance of the ChromeDriver from the ResourcePool instead of retrieving the current ChromeDriver.

How can retrieve the scenario's current ChromeDriver instead of a new instance?

More Details

I'm registering the ChromeDriver as in the provided example, i.e.:

private void ConfigureContainer(ContainerConfigurator config)
{
    config.RegisterInstance(
        new ResourcePool<ChromeDriver>(CreateDriver),
        new RegistrationOptions());
}

private ChromeDriver CreateDriver()
{
    var driver = new ChromeDriver();
    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(0);
    return driver;
}

My Decorator:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class TakeScreenshotOnErrorAttribute : Attribute, IScenarioDecoratorAttribute
{
    public async Task ExecuteAsync(IScenario scenario, Func<Task> scenarioInvocation)
    {
        try {
            await scenarioInvocation();
        }
        catch (Exception ex) {
            await TakeScreenshot(scenario);
        }
    }

    public int Order { get; set; }

    private static async Task TakeScreenshot(IScenario scenario)
    {
        try {
            var driverHandle = scenario.DependencyResolver.Resolve(typeof(ResourceHandle<ChromeDriver>));
            var driver = await ((ResourceHandle<ChromeDriver>) driverHandle).ObtainAsync();
            var screenshot = driver.GetScreenshot();
            screenshot.SaveAsFile(@"c:\temp\error.png");
        }
        catch {
            /* Ignore */
        }
    }
}

The debugger clearly shows that a second instance is created:

Version: LightBDD 3.0.1 with NUnit3

Body:
The default behavior of LightBDD DI container is to provide a new instance of the requested dependency every time Resolve() method is called.

To make it working as expected a more advanced DI has to be used (like LightBDD.Autofac package) and ResourceHandle<ChromeDriver> has to be registered with a scope lifetime:

public class ConfiguredLightBddScopeAttribute : LightBddScopeAttribute
{
    protected override void OnConfigure(LightBddConfiguration configuration)
    {
        configuration.DependencyContainerConfiguration()
            .UseAutofac(ConfigureContainer());
    }

    private ContainerBuilder ConfigureContainer()
    {
        var builder = new ContainerBuilder();
        builder.RegisterInstance(new ResourcePool<ChromeDriver>(CreateDriver));
        builder.RegisterType<ResourceHandle<ChromeDriver>>().InstancePerLifetimeScope();
        // ^-- this makes the difference
        return builder;
    }

    private ChromeDriver CreateDriver()
    {
        var driver = new ChromeDriver();
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(0);
        return driver;
    }
}

It would mean that while each scenario will get own copy of the handle, the scenario code and the decorator code will get the same instance.

I have provided the working example in a response on the LightBDD issues page: https://github.com/LightBDD/LightBDD/issues/186


问:
Request format is unrecognized for URL unexpectedly ending in
When consuming a WebService, I got the following error:

Request format is unrecognized for URL unexpectedly ending in /myMethodName

How can this be solved?

答:
I was getting this error until I added (as shown in the code below) $.holdReady(true) at the beginning of my web service call and $.holdReady(false) after it ends. This is jQuery thing to suspend the ready state of the page so any script within document.ready function would be waiting for this (among other possible but unknown to me things).

```<code><span class="AjaxPlaceHolder"></span>
<script type="text/javascript">
$.holdReady(true);
function GetHTML(source, section){
    var divToBeWorkedOn = ".AjaxPlaceHolder";
    var webMethod = "../MyService.asmx/MyMethod";
    var parameters = "{'source':'" + source + "','section':'" + section + "'}";

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        xhrFields: {
            withCredentials: false
        },
        crossDomain: true,
        success: function(data) {
            $.holdReady(false);
            var myData = data.d;
            if (myData != null) {
                $(divToBeWorkedOn).prepend(myData.html);
            }
        },
        error: function(e){
            $.holdReady(false);
            $(divToBeWorkedOn).html("Unavailable");
        }
    });
}
GetHTML("external", "Staff Directory");
</script>
</code>```

OwnerDisplayName: rm

Body:
I was getting this error until I added (as shown in the code below) $.holdReady(true) at the beginning of my web service call and $.holdReady(false) after it ends. This is jQuery thing to suspend the ready state of the page so any script within document.ready function would be waiting for this (among other possible but unknown to me things).

<span class="AjaxPlaceHolder"></span>
<script type="text/javascript">
$.holdReady(true);
function GetHTML(source, section){
    var divToBeWorkedOn = ".AjaxPlaceHolder";
    var webMethod = "../MyService.asmx/MyMethod";
    var parameters = "{'source':'" + source + "','section':'" + section + "'}";

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        xhrFields: {
            withCredentials: false
        },
        crossDomain: true,
        success: function(data) {
            $.holdReady(false);
            var myData = data.d;
            if (myData != null) {
                $(divToBeWorkedOn).prepend(myData.html);
            }
        },
        error: function(e){
            $.holdReady(false);
            $(divToBeWorkedOn).html("Unavailable");
        }
    });
}
GetHTML("external", "Staff Directory");
</script>


问:
Finite difference in Haskell, or how to disable potential optimizations
I'd like to implement the following naive (first order) finite differencing function:

```<code>finite_difference :: Fractional a => a -> (a -> a) -> a -> a
finite_difference h f x = ((f $ x + h) - (f x)) / h
</code>```

As you may know, there is a subtle problem: one has to make sure that (x + h) and x differ by an exactly representable number. Otherwise, the result has a huge error, leveraged by the fact that (f $ x + h) - (f x) involves catastrophic cancellation (and one has to carefully choose h, but that is not my problem here).

In C or C++, the problem can be solved like this:

```<code>volatile double temp = x + h;
h = temp - x;
</code>```

and the volatile modifier disables any optimization pertaining to the variable temp, so we are assured that a "clever" compiler will not optimize away those two lines.

I don't know enough Haskell yet to know how to solve this. I'm afraid that

```<code>let temp = x + h
    hh = temp - x
in ((f $ x + hh) - (f x)) / h
</code>```

will get optimized away by Haskell (or the backend it uses). How do I get the equivalent of volatile here (if possible without sacrificing laziness)? I don't mind GHC specific answers.

答:
I don't think that

```<code>temp = unsafePerformIO $ return $ x + h
</code>```

would get optimised out. Just a guess.

Body:
I'd like to implement the following naive (first order) finite differencing function:

finite_difference :: Fractional a => a -> (a -> a) -> a -> a
finite_difference h f x = ((f $ x + h) - (f x)) / h

As you may know, there is a subtle problem: one has to make sure that (x + h) and x differ by an exactly representable number. Otherwise, the result has a huge error, leveraged by the fact that (f $ x + h) - (f x) involves catastrophic cancellation (and one has to carefully choose h, but that is not my problem here).

In C or C++, the problem can be solved like this:

volatile double temp = x + h;
h = temp - x;

and the volatile modifier disables any optimization pertaining to the variable temp, so we are assured that a "clever" compiler will not optimize away those two lines.

I don't know enough Haskell yet to know how to solve this. I'm afraid that

let temp = x + h
    hh = temp - x
in ((f $ x + hh) - (f x)) / h

will get optimized away by Haskell (or the backend it uses). How do I get the equivalent of volatile here (if possible without sacrificing laziness)? I don't mind GHC specific answers.

Body:
I don't think that

temp = unsafePerformIO $ return $ x + h

would get optimised out. Just a guess.

ContentLicense: CC BY-SA 3.0


问:
Can't get table function to work with if statement
trying to create a table function that returns a two column table that must be conditioned with an if statement.

I have two other functions that do this separate but cant get it to work when combined.

```<code>create  function dbo.PDM_GetCategorytable (@Mystring varchar(200) ,@appid int)
returns table
as -- begin

--return
begin
-- declare @MyString varchar(200);
--set @MyString= 'Fred mtf is dead'--'RE: [Encrypt]]FW: MTF Military ---
--UPDATE URGENT'
--declare @AppId int =5

declare @Dubb Table (Col varchar(200));
insert into @dubb
(Col )
values ( @Mystring);

if ((select top 1 categoryid from @dubb a
left join
(SELECT        (pass.Recordid) as categoryid , pass.appid,
pass.Priority_Identifier, pass.PrioritySortorder, pass.Category,
ps.Search_String AS SrchVar
FROM            dbo.PDM_PriorityAssignments AS pass INNER JOIN
                     dbo.PDM_Priority_Search AS ps ON pass.Recordid =
ps.PriorityAssignmentid where pass.appid=@AppId )  b on a.col like '%' +
b.SrchVar + '%'
                     order by PrioritySortorder)  is not null)--'where
appid=@AppId
begin
select top 1 categoryid,Category from @dubb a
left join
(SELECT        (pass.Recordid) as categoryid , pass.appid,
pass.Priority_Identifier, pass.PrioritySortorder, pass.Category,
ps.Search_String AS SrchVar
FROM            dbo.PDM_PriorityAssignments AS pass INNER JOIN
                         dbo.PDM_Priority_Search AS ps ON pass.Recordid =
ps.PriorityAssignmentid where pass.appid=@AppId )  b on a.col like '%' +
b.SrchVar + '%'
                         order by PrioritySortorder;
                    end
else
begin
select recordid as categoryid,Category  FROM dbo.PDM_PriorityAssignments
AS pass  where appid=@AppId and Priority_Identifier like 'Routine'
end
return
end;
</code>```

expected results will be the returning of two columns , category id, and category.

答:
The problem is exactly because of the algorithm you need to use.
That requirement prevents you from returning just a table. On this scenarios you need to do something a bit different.
First define the resulting table and then, insert the values as you need.

I can´t run it  without your data but it should work.

```<code>CREATE FUNCTION dbo.PDM_GetCategorytable (
    @Mystring VARCHAR(200)
    ,@appid INT
    )
RETURNS @GetCategorytable TABLE
(
    [CategoryId] INT,
    [Category] VARCHAR(200))
AS -- begin
--return
BEGIN
    -- declare @MyString varchar(200);
    --set @MyString= 'Fred mtf is dead'--'RE: [Encrypt]]FW: MTF Military ---
    --UPDATE URGENT'
    --declare @AppId int =5
    DECLARE @Dubb TABLE (Col VARCHAR(200));

    INSERT INTO @dubb (Col)
    VALUES (@Mystring);

    IF (
            (
                SELECT TOP 1 categoryid
                FROM @dubb a
                LEFT JOIN (
                    SELECT (pass.Recordid) AS categoryid
                        ,pass.appid
                        ,pass.Priority_Identifier
                        ,pass.PrioritySortorder
                        ,pass.Category
                        ,ps.Search_String AS SrchVar
                    FROM dbo.PDM_PriorityAssignments AS pass
                    INNER JOIN dbo.PDM_Priority_Search AS ps ON pass.Recordid = ps.PriorityAssignmentid
                    WHERE pass.appid = @AppId
                    ) b ON a.col LIKE '%' + b.SrchVar + '%'
                ORDER BY PrioritySortorder
                ) IS NOT NULL
            ) --'where
        -- NOT SURE WHAT YOU ARE TRYING TO DO WITH THIS -- appid = @AppId
    BEGIN
        insert into @GetCategorytable(Categoryid, Category)
        SELECT TOP 1 categoryid
            ,Category
        FROM @dubb a
        LEFT JOIN (
            SELECT (pass.Recordid) AS categoryid
                ,pass.appid
                ,pass.Priority_Identifier
                ,pass.PrioritySortorder
                ,pass.Category
                ,ps.Search_String AS SrchVar
            FROM dbo.PDM_PriorityAssignments AS pass
            INNER JOIN dbo.PDM_Priority_Search AS ps ON pass.Recordid = ps.PriorityAssignmentid
            WHERE pass.appid = @AppId
            ) b ON a.col LIKE '%' + b.SrchVar + '%'
        ORDER BY PrioritySortorder;
    END
    ELSE
    BEGIN
        insert into @GetCategorytable(Categoryid, Category)
        SELECT recordid AS categoryid ,Category FROM dbo.PDM_PriorityAssignments AS pass
        WHERE appid = @AppId
            AND Priority_Identifier LIKE 'Routine'
    END

RETURN
END;
</code>```

Body:
trying to create a table function that returns a two column table that must be conditioned with an if statement.

I have two other functions that do this separate but cant get it to work when combined.

create  function dbo.PDM_GetCategorytable (@Mystring varchar(200) ,@appid int)
returns table
as -- begin

--return
begin
-- declare @MyString varchar(200);
--set @MyString= 'Fred mtf is dead'--'RE: [Encrypt]]FW: MTF Military ---
--UPDATE URGENT'
--declare @AppId int =5

declare @Dubb Table (Col varchar(200));
insert into @dubb
(Col )
values ( @Mystring);

if ((select top 1 categoryid from @dubb a
left join
(SELECT        (pass.Recordid) as categoryid , pass.appid,
pass.Priority_Identifier, pass.PrioritySortorder, pass.Category,
ps.Search_String AS SrchVar
FROM            dbo.PDM_PriorityAssignments AS pass INNER JOIN
                     dbo.PDM_Priority_Search AS ps ON pass.Recordid =
ps.PriorityAssignmentid where pass.appid=@AppId )  b on a.col like '%' +
b.SrchVar + '%'
                     order by PrioritySortorder)  is not null)--'where
appid=@AppId
begin
select top 1 categoryid,Category from @dubb a
left join
(SELECT        (pass.Recordid) as categoryid , pass.appid,
pass.Priority_Identifier, pass.PrioritySortorder, pass.Category,
ps.Search_String AS SrchVar
FROM            dbo.PDM_PriorityAssignments AS pass INNER JOIN
                         dbo.PDM_Priority_Search AS ps ON pass.Recordid =
ps.PriorityAssignmentid where pass.appid=@AppId )  b on a.col like '%' +
b.SrchVar + '%'
                         order by PrioritySortorder;
                    end
else
begin
select recordid as categoryid,Category  FROM dbo.PDM_PriorityAssignments
AS pass  where appid=@AppId and Priority_Identifier like 'Routine'
end
return
end;

expected results will be the returning of two columns , category id, and category.

Body:
The problem is exactly because of the algorithm you need to use.
That requirement prevents you from returning just a table. On this scenarios you need to do something a bit different.
First define the resulting table and then, insert the values as you need.

I can´t run it  without your data but it should work.

CREATE FUNCTION dbo.PDM_GetCategorytable (
    @Mystring VARCHAR(200)
    ,@appid INT
    )
RETURNS @GetCategorytable TABLE
(
    [CategoryId] INT,
    [Category] VARCHAR(200))
AS -- begin
--return
BEGIN
    -- declare @MyString varchar(200);
    --set @MyString= 'Fred mtf is dead'--'RE: [Encrypt]]FW: MTF Military ---
    --UPDATE URGENT'
    --declare @AppId int =5
    DECLARE @Dubb TABLE (Col VARCHAR(200));

    INSERT INTO @dubb (Col)
    VALUES (@Mystring);

    IF (
            (
                SELECT TOP 1 categoryid
                FROM @dubb a
                LEFT JOIN (
                    SELECT (pass.Recordid) AS categoryid
                        ,pass.appid
                        ,pass.Priority_Identifier
                        ,pass.PrioritySortorder
                        ,pass.Category
                        ,ps.Search_String AS SrchVar
                    FROM dbo.PDM_PriorityAssignments AS pass
                    INNER JOIN dbo.PDM_Priority_Search AS ps ON pass.Recordid = ps.PriorityAssignmentid
                    WHERE pass.appid = @AppId
                    ) b ON a.col LIKE '%' + b.SrchVar + '%'
                ORDER BY PrioritySortorder
                ) IS NOT NULL
            ) --'where
        -- NOT SURE WHAT YOU ARE TRYING TO DO WITH THIS -- appid = @AppId
    BEGIN
        insert into @GetCategorytable(Categoryid, Category)
        SELECT TOP 1 categoryid
            ,Category
        FROM @dubb a
        LEFT JOIN (
            SELECT (pass.Recordid) AS categoryid
                ,pass.appid
                ,pass.Priority_Identifier
                ,pass.PrioritySortorder
                ,pass.Category
                ,ps.Search_String AS SrchVar
            FROM dbo.PDM_PriorityAssignments AS pass
            INNER JOIN dbo.PDM_Priority_Search AS ps ON pass.Recordid = ps.PriorityAssignmentid
            WHERE pass.appid = @AppId
            ) b ON a.col LIKE '%' + b.SrchVar + '%'
        ORDER BY PrioritySortorder;
    END
    ELSE
    BEGIN
        insert into @GetCategorytable(Categoryid, Category)
        SELECT recordid AS categoryid ,Category FROM dbo.PDM_PriorityAssignments AS pass
        WHERE appid = @AppId
            AND Priority_Identifier LIKE 'Routine'
    END

RETURN
END;


问:
Unity NavMeshAgent not reaching target - moving around
I've created a simple scene and I'm now trying to make a rabbit move to the mouse-click position on a Plane.

So I've added a Rigidbody, a Nav Mesh Agent and a simple "Pathfinding" script to the rabbit.

The planes Mesh Renderer is set to "Navigation Static", "Generate OffMeshLinks" and "Walkable"

Now as soon as the rabbit gets close to the given destination, it will not stop but rather is "running around" in a very small circle around the destination.

Here is my script

```<code>using UnityEngine;
using UnityEngine.AI;

public class Pathfinding : MonoBehaviour {

private NavMeshAgent agent;
private Animator animator;

// Use this for initialization
void Start() {
    agent = GetComponent<NavMeshAgent>();
    animator = GetComponent<Animator>();
}

// Update is called once per frame
void Update() {
    RaycastHit hit;

    if(Input.GetMouseButtonDown(0)) {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit)) {
            agent.SetDestination(hit.point);
            animator.SetInteger("AnimIndex", 1);
            animator.SetBool("Next", true);
        }
    }
}
}
</code>```

and a picture of my rabbit object ;)

答:
Actually I was wrong, updating Unity didn't fix the problem, but I recognized that the problem was that the animations "Root Transformation Position (XZ)"/ Bake Into Pose was deactivated. </p>

<p>I also changed my script to </p>

```<code>using UnityEngine;
using UnityEngine.AI;

public class Pathfinding : MonoBehaviour {

private NavMeshAgent agent;
private Animator animator;

private bool run = false;

// Use this for initialization
void Start() {
    agent = GetComponent<NavMeshAgent>();
    animator = GetComponent<Animator>();
}

// Update is called once per frame
void Update() {
    RaycastHit hit;

    if(Input.GetMouseButtonDown(0)) {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit)) {
            Debug.Log("start");
            agent.SetDestination(hit.point);
            animator.SetInteger("AnimIndex", 1);
            animator.SetBool("Next", true);
            run = true;
        }
    }else if(agent.remainingDistance <= agent.stoppingDistance && run) {
        Debug.Log("stop");
        animator.SetInteger("AnimIndex", 0);
        animator.SetBool("Next", true);
        run = false;
    }

}
}
</code>```

Body:
I've created a simple scene and I'm now trying to make a rabbit move to the mouse-click position on a Plane.

So I've added a Rigidbody, a Nav Mesh Agent and a simple "Pathfinding" script to the rabbit.

The planes Mesh Renderer is set to "Navigation Static", "Generate OffMeshLinks" and "Walkable"

Now as soon as the rabbit gets close to the given destination, it will not stop but rather is "running around" in a very small circle around the destination.

Here is my script

using UnityEngine;
using UnityEngine.AI;

public class Pathfinding : MonoBehaviour {

private NavMeshAgent agent;
private Animator animator;

// Use this for initialization
void Start() {
    agent = GetComponent<NavMeshAgent>();
    animator = GetComponent<Animator>();
}

// Update is called once per frame
void Update() {
    RaycastHit hit;

    if(Input.GetMouseButtonDown(0)) {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit)) {
            agent.SetDestination(hit.point);
            animator.SetInteger("AnimIndex", 1);
            animator.SetBool("Next", true);
        }
    }
}
}

and a picture of my rabbit object ;)

Body:
Actually I was wrong, updating Unity didn't fix the problem, but I recognized that the problem was that the animations "Root Transformation Position (XZ)"/ Bake Into Pose was deactivated.

I also changed my script to

using UnityEngine;
using UnityEngine.AI;

public class Pathfinding : MonoBehaviour {

private NavMeshAgent agent;
private Animator animator;

private bool run = false;

// Use this for initialization
void Start() {
    agent = GetComponent<NavMeshAgent>();
    animator = GetComponent<Animator>();
}

// Update is called once per frame
void Update() {
    RaycastHit hit;

    if(Input.GetMouseButtonDown(0)) {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit)) {
            Debug.Log("start");
            agent.SetDestination(hit.point);
            animator.SetInteger("AnimIndex", 1);
            animator.SetBool("Next", true);
            run = true;
        }
    }else if(agent.remainingDistance <= agent.stoppingDistance && run) {
        Debug.Log("stop");
        animator.SetInteger("AnimIndex", 0);
        animator.SetBool("Next", true);
        run = false;
    }

}
}


问:
Accesing an array item for a class binding in a v-for loop
When using Vue's dynamic class binding to use a ternary operator to bind a class based on the currentValue and the id of the items in my looped array, Vue seems to ignore the class completely.

Both the 'first' and 'last' class bindings work, but when using the item.id, the class is never assigned. However the function is fired because the event is successfully emitted and the currentValue var updated.

ContentSwitcher.vue

```<code><template>
  <div class="content-switcher-wrapper">
    <section class="content-items">
      <a v-for="(item, index) in options"
         class="content-item"
         :class="[ index === 0 ? 'first' : '',
                   index === options.length -1 ? 'last' : '',
                   item.id === currentValue ? 'selected' : '',]"
         @click="updateSelected(item.id)">
        {{ item.text }}
      </a>
    </section>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class ContentSwitcher extends Vue {
  @Prop()
  public options!: any;

  public currentValue!: string;

  public created(): void {
    this.currentValue = this.options[0].id;
  }

  public updateSelected(value: string): void {
    this.currentValue = value;
    this.$emit('contentSwitcherUpdated', value);
  }
}
</script>
</code>```

Usage

```<code><content-switcher :options="tabSwitcherOptions"></content-switcher>
</code>```

Options passed

```<code>  private tabSwitcherOptions: any = [
    {
      id: 'week',
      text: 'Week',
    },
    {
      id: 'month',
      text: 'Maand',
    },
  ];
</code>```

When clicking on "Month", the event is emmited, however the classed 'selected' is never added to the tag.

答:
I think what you have is actually a reactivity issue seen here public currentValue!: string. currentValue is not assigned until the created hook. The created hook is NOT a constructor and gets executed after the instantiation which means when the component is initially created currentValue is actually undefined. Instance properties must have an initial value for change detection to happen. Change it to public currentValue: string = ''; and you should see the results you are looking for.

See Declaring-Reactive-Properties for more info.

Body:
When using Vue's dynamic class binding to use a ternary operator to bind a class based on the currentValue and the id of the items in my looped array, Vue seems to ignore the class completely.

Both the 'first' and 'last' class bindings work, but when using the item.id, the class is never assigned. However the function is fired because the event is successfully emitted and the currentValue var updated.

ContentSwitcher.vue

<template>

        {{ item.text }}

</template>

Usage

<content-switcher :options="tabSwitcherOptions"></content-switcher>

Options passed

  private tabSwitcherOptions: any = [
    {
      id: 'week',
      text: 'Week',
    },
    {
      id: 'month',
      text: 'Maand',
    },
  ];

When clicking on "Month", the event is emmited, however the classed 'selected' is never added to the tag.


问:
How to Resize google reCAPTCHA?
The image of the problem:

The code:

```<code><div class="text-xs-center" id="DIVCATCHA" runat="server">
  <asp:HiddenField runat="server" ID="hdnImageSelected" />
  <div class="g-recaptcha" data-sitekey="" style="transform:scale(0.81);-webkit-transform:scale(0.81);transform-origin:0 0;-webkit-transform-origin:0 0;" >
  </div>
</div>
</code>```

答:
By using the CSS transform property you can achieve changing the width by changing the entire scale of the reCAPTCHA.

By adding in just two inline styles, you can make the reCAPTCHA fit nicely:

```<code><div class="g-recaptcha"
     data-theme="light"
     data-sitekey="XXXXXXXXXXXXX"
     style="transform:scale(0.77);transform-origin:0 0">
</div>
</code>```

More details can be found here: https://www.geekgoddess.com/how-to-resize-the-google-nocaptcha-recaptcha/

Title: How to Resize google reCAPTCHA?

Body:
The image of the problem:

The code:

  <asp:HiddenField runat="server" ID="hdnImageSelected" />

Body:
By using the CSS transform property you can achieve changing the width by changing the entire scale of the reCAPTCHA.

By adding in just two inline styles, you can make the reCAPTCHA fit nicely:

<div class="g-recaptcha"
     data-theme="light"
     data-sitekey="XXXXXXXXXXXXX"
     style="transform:scale(0.77);transform-origin:0 0">
</div>

More details can be found here: https://www.geekgoddess.com/how-to-resize-the-google-nocaptcha-recaptcha/


问:
ADB: missing port in specification
I've recently upgraded to Android SDK Platform-Tools version 28.0.2. Version information:

```<code>$ adb version
Android Debug Bridge version 1.0.40
Version 28.0.2-5303910
</code>```

When using the adb connect command I now get the following error:

```<code>$ adb connect 192.168.1.20
missing port in specification: tcp:192.168.1.20
</code>```

ADB previously connected to devices using TCP port 5555 by default. I am still able to connect to my device by specifying this port number:

```<code>$ adb connect 192.168.1.20:5555
connected to 192.168.1.20:5555
</code>```

However, this is a minor inconvenience to me as I'm used to typing in just the IP address. Is there any way of telling this version of ADB to use TCP port 5555 by default?

答:
There's another workaround, with credit to this unknown person in the Google issue thread. Create a custom alias that automatically adds the default port number to the IP address.

For Linux & MacOS, in ~/.bashrc or ~/.bash_aliases:

```<code>function adbc() {
   adb connect $1:5555
}
</code>```

Then connect using command

```<code>$ adbc 192.168.1.20
</code>```

For Windows users:

Put this in adbc.bat anywhere in your PATH

```<code>@echo off
adb connect %1:5555
</code>```

Then connect using command

```<code>> adbc 192.168.1.20
</code>```

Title: ADB: missing port in specification

Body:
I've recently upgraded to Android SDK Platform-Tools version 28.0.2. Version information:

$ adb version
Android Debug Bridge version 1.0.40
Version 28.0.2-5303910

When using the adb connect command I now get the following error:

$ adb connect 192.168.1.20
missing port in specification: tcp:192.168.1.20

ADB previously connected to devices using TCP port 5555 by default. I am still able to connect to my device by specifying this port number:

$ adb connect 192.168.1.20:5555
connected to 192.168.1.20:5555

However, this is a minor inconvenience to me as I'm used to typing in just the IP address. Is there any way of telling this version of ADB to use TCP port 5555 by default?

Body:
There's another workaround, with credit to this unknown person in the Google issue thread. Create a custom alias that automatically adds the default port number to the IP address.

For Linux & MacOS, in ~/.bashrc or ~/.bash_aliases:

function adbc() {
   adb connect $1:5555
}

Then connect using command

$ adbc 192.168.1.20

For Windows users:

Put this in adbc.bat anywhere in your PATH

@echo off
adb connect %1:5555

Then connect using command

> adbc 192.168.1.20


问:
Creating function to get means based on column levels
I'm trying to create a function that gives me the means based on another column's levels. I know that R has plenty of functions that do this same thing, but since I'm planning to use the boot package, as I could see I need to provide a function to be used (this package appears not to have pre defined functions such as "FUN=mean"). Sorry for such a basic question!

I searched on pages about the basics of function creation in R but couldn't find what I want. Here an example what I want using iris dataset and tapply:

```<code>data(iris)
with(iris, tapply(Sepal.Length, Species, mean))
</code>```

So, I want a function that gives me the means (Sepal.Length) of each level (Species) of a X data.table (in this case, iris).

```<code>setosa versicolor  virginica
 5.006    5.936      6.588
</code>```

答:
If you want to bootstrap means by groups, you can do something following the lines below.

This is your code, the means by group of Species, full dataset.

```<code>res1 <- with(iris, tapply(Sepal.Length, Species, mean))
</code>```

Now a bootstrap function and its application.

```<code>library(boot)

bootMeans <- function(data, indices, val, catg, na.rm = FALSE){
  val <- deparse(substitute(val))
  catg <- deparse(substitute(catg))
  d <- data[indices, ]
  tapply(d[[val]], d[[catg]], mean, na.rm = na.rm)
}

set.seed(1234)
b <- boot(iris, bootMeans, R = 1000,
          val = Sepal.Length, catg = Species, na.rm = TRUE)

identical(b$t0, res1)
#[1] TRUE

colMeans(b$t)
#[1] 5.006788 5.940504 6.588357
</code>```

Body:
I'm trying to create a function that gives me the means based on another column's levels. I know that R has plenty of functions that do this same thing, but since I'm planning to use the boot package, as I could see I need to provide a function to be used (this package appears not to have pre defined functions such as "FUN=mean"). Sorry for such a basic question!

I searched on pages about the basics of function creation in R but couldn't find what I want. Here an example what I want using iris dataset and tapply:

data(iris)
with(iris, tapply(Sepal.Length, Species, mean))

So, I want a function that gives me the means (Sepal.Length) of each level (Species) of a X data.table (in this case, iris).

setosa versicolor  virginica
 5.006    5.936      6.588

Body:
If you want to bootstrap means by groups, you can do something following the lines below.

This is your code, the means by group of Species, full dataset.

res1 <- with(iris, tapply(Sepal.Length, Species, mean))

Now a bootstrap function and its application.

library(boot)

bootMeans <- function(data, indices, val, catg, na.rm = FALSE){
  val <- deparse(substitute(val))
  catg <- deparse(substitute(catg))
  d <- data[indices, ]
  tapply(d[[val]], d[[catg]], mean, na.rm = na.rm)
}

set.seed(1234)
b <- boot(iris, bootMeans, R = 1000,
          val = Sepal.Length, catg = Species, na.rm = TRUE)

identical(b$t0, res1)
#[1] TRUE

colMeans(b$t)
#[1] 5.006788 5.940504 6.588357


问:
How to install Tex live in a different directory than default one?
As I dont have sudo or root access, I want to install Tex live at a different location but install-tl doesn't have any option for this. Is there any other workaround?

Default Path is: /usr/local/texlive/2014

答:
I did the following 3 steps

./install-tl > Enter command: P

sed -i 's|/usr/local/|~/|g' texlive.profile
Modifies generated texlive.profile to replace all occurances of /usr/local/ with ~/

Run ./install-tl -profile texlive.profile


问:
~0 vs. !0 vs. 1 in C
I was reading some code today by someone I consider to be a reasonable programmer, and I noticed they used a =~0 to set a loop quit variable.

Is there any compelling reason to do this rather than simply quit = 1;?

I'm mostly just curious, before I go ahead and change it. Thanks!

Example:

```<code>while(!quit){
    ...;

    if(!strcmp(s, "q"))
        quit=~0;
}
</code>```

答: In C, ~ is the unary operator for ones compliment which flips bits to their opposite state. So technically the code works because the if() clause is only evaluating for the presence of 0 (false) or anything not 0 (true). Frankly I think this is a bit overkill for evaluating true or false. I'd only consider using it if I was truly doing evaluations on a bitwise basis. Maybe there could be an argument made for performance but I somehow doubt it.</p>

Title: ~0 vs. !0 vs. 1 in C

Body:
I was reading some code today by someone I consider to be a reasonable programmer, and I noticed they used a =~0 to set a loop quit variable.

Is there any compelling reason to do this rather than simply quit = 1;?

I'm mostly just curious, before I go ahead and change it. Thanks!

Example:

while(!quit){
    ...;

    if(!strcmp(s, "q"))
        quit=~0;
}


问:
How to configure classDumpDir in jacoco?
I'm able to generate jacoco reports by configuring the javaagent using tcpserver option. But dev classes are not getting dumped to my test project.

I have tried adding classDumpDir in pom.xml

```<code>                        <classDumpDir>${project.build.directory}/classes</classDumpDir>
</code>```

Not sure under which execution and goal classDumpDir needs to be specified and what is the maven command to execute.

My goal is to fetch the dynamically generated dev classes from remote server to my local machine using classDumpDir or any other option.  It would be great if someone can shed some light on pom.xml  part

答:
Not sure under which execution and goal classDumpDir needs to be specified

classdumpdir is an option of JaCoCo Java Agent (see https://www.jacoco.org/jacoco/trunk/doc/agent.html), from there one can logically assume that it can be specified for prepare-agent goal. Even without this knowledge and assumption, there is documentation for jacoco-maven-plugin at https://www.jacoco.org/jacoco/trunk/doc/maven.html , which lists all available goals and their parameters, including classDumpDir in prepare-agent at page https://www.jacoco.org/jacoco/trunk/doc/prepare-agent-mojo.html#classDumpDir

Body:
I'm able to generate jacoco reports by configuring the javaagent using tcpserver option. But dev classes are not getting dumped to my test project.

I have tried adding classDumpDir in pom.xml

                        <classDumpDir>${project.build.directory}/classes</classDumpDir>

Not sure under which execution and goal classDumpDir needs to be specified and what is the maven command to execute.

My goal is to fetch the dynamically generated dev classes from remote server to my local machine using classDumpDir or any other option.  It would be great if someone can shed some light on pom.xml  part


问:
How to plot top5 features_importances using RandomForestRegressor
I am trying to plot the feature_importance of a RandomForestRegressor model. However, I have 307 features (after OneHotEncoding) in my dataset, so plotting all of them is not really helpful aesthetically.

How could I plot just the top5 (or top10) ones?

Here is my actual code:

```<code># Help function to plot feature_importances
def plot_feature_importances(model_to_plot, features_list, x_train_set):
    # Wichtigkeit der eizelnen Features plotten!

    plt_x = np.linspace(0,len(features_list)-1,len(features_list))

    print("Features sorted by their score:")

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 12}

    plt.rc('font', **font)

    plt.figure(figsize=(15,7))

    plt.bar(plt_x, model_to_plot.feature_importances_, width=0.5, color="blue",align='center')
    plt.gca().set_xticklabels(plt_x, rotation=60 )
    plt.title('Features importance in decision making', position=(.5,1.05), fontsize=20)
    plt.xticks(plt_x, features_list, fontsize=12)
    plt.yticks(fontsize=12)
    plt.ylabel('Relative Information %', fontsize=15)
    plt.xlabel('Features', fontsize=15)
    plt.show()

    print("Feature ranking:")

    importances = model_to_plot.feature_importances_
    std = np.std([tree.feature_importances_ for tree in model_to_plot.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1]

    for f in range(x_train.shape[1]):
        print("%d. Feature %s (%.2f)" % (f + 1, x_train_set.columns[indices[f]], importances[indices[f]]))
</code>```

and plotting using the following code gives me something like this:

```<code>plot_feature_importances(model, features, x_train)
</code>```

答:
You failed to provide a Minimal, Complete, and Verifiable example, so I cannot provide a final working answer. Nevertheless, you can try the following modified code. I have removed the lines for setting x-ticks. But that part is trivial</p>

```<code>def plot_feature_importances(model_to_plot, features_list, x_train_set):
    to_plot = 5 # <---- Define the number to plot
    importances = model_to_plot.feature_importances_
    std = np.std([tree.feature_importances_ for tree in model_to_plot.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1][0:to_plot] # <--- Take the top 5

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 12}

    plt.rc('font', **font)

    plt.figure(figsize=(15,7))

    plt.bar(range(to_plot), importances[indices], width=0.5, color="blue",align='center') # <--- Plot the top 5
    plt.xticks(range(to_plot), features_list[indices], fontsize=12) # <--- add ticks
    plt.title('Features importance in decision making', position=(.5,1.05), fontsize=20)
    plt.yticks(fontsize=12)
    plt.ylabel('Relative Information %', fontsize=15)
    plt.xlabel('Features', fontsize=15)
    plt.show()

    for f in range(x_train.shape[1]):
        print("%d. Feature %s (%.2f)" % (f + 1, x_train_set.columns[indices[f]], importances[indices[f]]))

plot_feature_importances(model, features, x_train)
</code>```

Body:
I am trying to plot the feature_importance of a RandomForestRegressor model. However, I have 307 features (after OneHotEncoding) in my dataset, so plotting all of them is not really helpful aesthetically.

How could I plot just the top5 (or top10) ones?

Here is my actual code:

# Help function to plot feature_importances
def plot_feature_importances(model_to_plot, features_list, x_train_set):
    # Wichtigkeit der eizelnen Features plotten!

    plt_x = np.linspace(0,len(features_list)-1,len(features_list))

    print("Features sorted by their score:")

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 12}

    plt.rc('font', **font)

    plt.figure(figsize=(15,7))

    plt.bar(plt_x, model_to_plot.feature_importances_, width=0.5, color="blue",align='center')
    plt.gca().set_xticklabels(plt_x, rotation=60 )
    plt.title('Features importance in decision making', position=(.5,1.05), fontsize=20)
    plt.xticks(plt_x, features_list, fontsize=12)
    plt.yticks(fontsize=12)
    plt.ylabel('Relative Information %', fontsize=15)
    plt.xlabel('Features', fontsize=15)
    plt.show()

    print("Feature ranking:")

    importances = model_to_plot.feature_importances_
    std = np.std([tree.feature_importances_ for tree in model_to_plot.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1]

    for f in range(x_train.shape[1]):
        print("%d. Feature %s (%.2f)" % (f + 1, x_train_set.columns[indices[f]], importances[indices[f]]))

and plotting using the following code gives me something like this:

plot_feature_importances(model, features, x_train)

Body:
You failed to provide a Minimal, Complete, and Verifiable example, so I cannot provide a final working answer. Nevertheless, you can try the following modified code. I have removed the lines for setting x-ticks. But that part is trivial

def plot_feature_importances(model_to_plot, features_list, x_train_set):
    to_plot = 5 # <---- Define the number to plot
    importances = model_to_plot.feature_importances_
    std = np.std([tree.feature_importances_ for tree in model_to_plot.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1][0:to_plot] # <--- Take the top 5

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 12}

    plt.rc('font', **font)

    plt.figure(figsize=(15,7))

    plt.bar(range(to_plot), importances[indices], width=0.5, color="blue",align='center') # <--- Plot the top 5
    plt.xticks(range(to_plot), features_list[indices], fontsize=12) # <--- add ticks
    plt.title('Features importance in decision making', position=(.5,1.05), fontsize=20)
    plt.yticks(fontsize=12)
    plt.ylabel('Relative Information %', fontsize=15)
    plt.xlabel('Features', fontsize=15)
    plt.show()

    for f in range(x_train.shape[1]):
        print("%d. Feature %s (%.2f)" % (f + 1, x_train_set.columns[indices[f]], importances[indices[f]]))

plot_feature_importances(model, features, x_train)


问:
How to remove ordinal indicators of the Portuguese language string
In portuguese several names have the following characters:

```<code>feminine ª
and
masculine º
</code>```

I need to remove them from my string, but I can't find the right regex. Anyone able to help me out?

答:
It seems that it works, very strange, but works.</p>

```<code>stringr::str_replace_all(string = inep$NO_ENTIDADE, pattern = "�", replacement = "")
</code>```

Body:
In portuguese several names have the following characters:

feminine ª
and
masculine º

I need to remove them from my string, but I can't find the right regex. Anyone able to help me out?

Body:
It seems that it works, very strange, but works.

stringr::str_replace_all(string = inep$NO_ENTIDADE, pattern = "�", replacement = "")


问:
Profiling shell commands in Emacs
Is there a way to profile the amount of time blocking on shell commands in emacs? Consider the following program:

(profiler-start 'cpu)
(shell-command "sleep 3")
(profiler-report)
(profiler-stop)
```

<p>The profiler report will look something like this:</p>

<pre class="lang-none prettyprint-override"><code>- command-execute                                                 371  95%
 - call-interactively                                             371  95%
  - funcall-interactively                                         329  84%
   - execute-extended-command                                     175  44%
    - execute-extended-command--shorter                           157  40%
     - completion-try-completion                                  149  38%
      - completion--nth-completion                                149  38%
       - completion--some                                         143  36%
        - #<compiled 0x438307f1>                                  143  36%
         - completion-pcm-try-completion                          102  26%
          - completion-pcm--find-all-completions                   98  25%
             completion-pcm--all-completions                       98  25%
          + completion-pcm--merge-try                               4   1%
           completion-basic-try-completion                         41  10%
    + sit-for                                                      16   4%
   - eval-expression                                              154  39%
    - eval                                                        154  39%
     - profiler-start                                             154  39%
      - debug                                                     154  39%
       - recursive-edit                                           141  36%
        - command-execute                                         114  29%
         - call-interactively                                     114  29%
          - byte-code                                             107  27%
           + read--expression                                      64  16%
           + read-extended-command                                 43  11%
          + funcall-interactively                                   7   1%
  + byte-code                                                      42  10%
+ ...                                                              19   4%
</code>```

As you can see the time spent is more or less evenly distributed. I'm interested in seeing output that tells me that I'm spending the significant part of the program blocking on the shell-command sleep 3, is this possible somehow? I am aware that sleep 3 is not heavy on my CPU - but I'm trying to figure out which shell commands are called from magit that is taking such a long time - so I'll also be interested in stuff that's IO-bound.

答:
Note that profiler.el is a sampling profiler. You might want to try an instrumenting profiler such as elp.el if you are interested in the wall time.

In your case you may want to instrument magit by using M-x elp-instrument-package RET magit RET. After running your magit commands you can then take a look at the results using M-x elp-results RET.

For magit you would probably find that the function magit-process-file is taking up a lot of time. To further investigate the specific function calls you could then simply instrument that or any other function by adding an advice function logging the runtime together with the function's arguments to the messages buffer for each individual function call as follows.

(defun log-function-time (f &rest args)
  (let ((time-start (current-time)))
    (prog1
        (apply f args)
      (message "%s seconds used in (magit-process-file %s)"
               (time-to-seconds (time-subtract (current-time) time-start))
               args))))

(advice-add 'magit-process-file :around 'log-function-time)
```

Title: Profiling shell commands in Emacs

Body:
Is there a way to profile the amount of time blocking on shell commands in emacs? Consider the following program:

(profiler-start 'cpu)
(shell-command "sleep 3")
(profiler-report)
(profiler-stop)

The profiler report will look something like this:

- command-execute                                                 371  95%
 - call-interactively                                             371  95%
  - funcall-interactively                                         329  84%
   - execute-extended-command                                     175  44%
    - execute-extended-command--shorter                           157  40%
     - completion-try-completion                                  149  38%
      - completion--nth-completion                                149  38%
       - completion--some                                         143  36%
        - #<compiled 0x438307f1>                                  143  36%
         - completion-pcm-try-completion                          102  26%
          - completion-pcm--find-all-completions                   98  25%
             completion-pcm--all-completions                       98  25%
          + completion-pcm--merge-try                               4   1%
           completion-basic-try-completion                         41  10%
    + sit-for                                                      16   4%
   - eval-expression                                              154  39%
    - eval                                                        154  39%
     - profiler-start                                             154  39%
      - debug                                                     154  39%
       - recursive-edit                                           141  36%
        - command-execute                                         114  29%
         - call-interactively                                     114  29%
          - byte-code                                             107  27%
           + read--expression                                      64  16%
           + read-extended-command                                 43  11%
          + funcall-interactively                                   7   1%
  + byte-code                                                      42  10%
+ ...                                                              19   4%

As you can see the time spent is more or less evenly distributed. I'm interested in seeing output that tells me that I'm spending the significant part of the program blocking on the shell-command sleep 3, is this possible somehow? I am aware that sleep 3 is not heavy on my CPU - but I'm trying to figure out which shell commands are called from magit that is taking such a long time - so I'll also be interested in stuff that's IO-bound.


问:
Unzip a LARGE zip file in Azure File Storage w/o "Out of Memory" exception"
Here's what I'm dealing with...

Some process (out of our control) will occasionally drop a zip file into a directory in Azure File Storage.  That directory name is InBound. So let's say a file called bigbook.zip is dropped into the InBound folder.

I need to create an Azure Function App that runs every 5 minutes and looks for zip files in the InBound directory. If any exists, then one-by-one, we create a new directory by the same name as the zip file in another directory (called InProcess). So in our example, I would create InProcess/bigbook.

Now inside InProcess/bigbook, I need to unzip bigbook.zip. So by the time the process is done running InProcess/bigbook will contain all the contents of bigbook.zip.

Please note: This function I am creating is a Console App that will run as an Azure Function App. So there will be no file system access (at least, as far as I'm aware, anyway.)  There is no option to download the zip file, unzip it, and then move the contents.

I am having a devil of a time figuring out how to do this in memory only. No matter what I try, I keep running into an Out Of Memory exception. For now, I am just doing this on my localhost running in debug in Visual Studio 2017, .NET 4.7.  In that setting, I am not able to convert the test zip file, which is 515,069KB.

This was my first attempt:

```<code>    private async Task<MemoryStream> GetMemoryStreamAsync(CloudFile inBoundfile)
    {
        MemoryStream memstream = new MemoryStream();
        await inBoundfile.DownloadToStreamAsync(memstream).ConfigureAwait(false);
        return memstream;
    }
</code>```

And this (with high hopes) was my second attempt, thinking that DownloadRangeToStream would work better than just DownloadToStream.

```<code>    private MemoryStream GetMemoryStreamByRange(CloudFile inBoundfile)
    {
        MemoryStream outPutStream = new MemoryStream();
        inBoundfile.FetchAttributes();
        int bufferLength = 1 * 1024 * 1024;//1 MB chunk
        long blobRemainingLength = inBoundfile.Properties.Length;
        long offset = 0;
        while (blobRemainingLength > 0)
        {
            long chunkLength = (long)Math.Min(bufferLength, blobRemainingLength);

            using (var ms = new MemoryStream())
            {
                inBoundfile.DownloadRangeToStream(ms, offset, chunkLength);
                lock (outPutStream)
                {
                    outPutStream.Position = offset;
                    var bytes = ms.ToArray();
                    outPutStream.Write(bytes, 0, bytes.Length);
                }
            }

            offset += chunkLength;
            blobRemainingLength -= chunkLength;
        }
        return outPutStream;
    }
</code>```

But either way, I am running into memory issues. I presume it's because the MemoryStream I am trying to create gets too large?

How else can I tackle this?  And again, downloading the zip file is not an option, as the app will ultimately be an Azure Function App. I'm also pretty sure that using a FileStream isn't an option either, as that requires a local file path, which I don't have. (I only have a remote Azure URL)

Could I somehow create a temp file in the same Azure Storage account that the zip file is in, and stream the zip file to that temp file instead of to a memory stream? (Thinking out loud.)

The goal is to get the stream into a ZipArchive using:

```<code>ZipArchive archive = new ZipArchive(stream)
</code>```

And from there I can extract all the contents.  But getting to that point w/o memory errors is proving a real bugger.

Any ideas?

答:
Using Azure Storage File Share this is the only way it worked for me without loading the entire ZIP into Memory. I tested with a 3GB ZIP File (with thousands of files or with a big file inside) and Memory/CPU was low and stable. I hope it helps!</p>

```<code>var zipFiles = _directory.ListFilesAndDirectories()
    .OfType<CloudFile>()
    .Where(x => x.Name.ToLower().Contains(".zip"))
    .ToList();

foreach (var zipFile in zipFiles)
{
    using (var zipArchive = new ZipArchive(zipFile.OpenRead()))
    {
        foreach (var entry in zipArchive.Entries)
        {
            if (entry.Length > 0)
            {
                CloudFile extractedFile = _directory.GetFileReference(entry.Name);

                using (var entryStream = entry.Open())
                {
                    byte[] buffer = new byte[16 * 1024];
                    using (var ms = extractedFile.OpenWrite(entry.Length))
                    {
                        int read;
                        while ((read = entryStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                    }
                }
            }
        }
    }
}
</code>```

Body:
Here's what I'm dealing with...

Some process (out of our control) will occasionally drop a zip file into a directory in Azure File Storage.  That directory name is InBound. So let's say a file called bigbook.zip is dropped into the InBound folder.

I need to create an Azure Function App that runs every 5 minutes and looks for zip files in the InBound directory. If any exists, then one-by-one, we create a new directory by the same name as the zip file in another directory (called InProcess). So in our example, I would create InProcess/bigbook.

Now inside InProcess/bigbook, I need to unzip bigbook.zip. So by the time the process is done running InProcess/bigbook will contain all the contents of bigbook.zip.

Please note: This function I am creating is a Console App that will run as an Azure Function App. So there will be no file system access (at least, as far as I'm aware, anyway.)  There is no option to download the zip file, unzip it, and then move the contents.

I am having a devil of a time figuring out how to do this in memory only. No matter what I try, I keep running into an Out Of Memory exception. For now, I am just doing this on my localhost running in debug in Visual Studio 2017, .NET 4.7.  In that setting, I am not able to convert the test zip file, which is 515,069KB.

This was my first attempt:

    private async Task<MemoryStream> GetMemoryStreamAsync(CloudFile inBoundfile)
    {
        MemoryStream memstream = new MemoryStream();
        await inBoundfile.DownloadToStreamAsync(memstream).ConfigureAwait(false);
        return memstream;
    }

And this (with high hopes) was my second attempt, thinking that DownloadRangeToStream would work better than just DownloadToStream.

    private MemoryStream GetMemoryStreamByRange(CloudFile inBoundfile)
    {
        MemoryStream outPutStream = new MemoryStream();
        inBoundfile.FetchAttributes();
        int bufferLength = 1 * 1024 * 1024;//1 MB chunk
        long blobRemainingLength = inBoundfile.Properties.Length;
        long offset = 0;
        while (blobRemainingLength > 0)
        {
            long chunkLength = (long)Math.Min(bufferLength, blobRemainingLength);

            using (var ms = new MemoryStream())
            {
                inBoundfile.DownloadRangeToStream(ms, offset, chunkLength);
                lock (outPutStream)
                {
                    outPutStream.Position = offset;
                    var bytes = ms.ToArray();
                    outPutStream.Write(bytes, 0, bytes.Length);
                }
            }

            offset += chunkLength;
            blobRemainingLength -= chunkLength;
        }
        return outPutStream;
    }

But either way, I am running into memory issues. I presume it's because the MemoryStream I am trying to create gets too large?

How else can I tackle this?  And again, downloading the zip file is not an option, as the app will ultimately be an Azure Function App. I'm also pretty sure that using a FileStream isn't an option either, as that requires a local file path, which I don't have. (I only have a remote Azure URL)

Could I somehow create a temp file in the same Azure Storage account that the zip file is in, and stream the zip file to that temp file instead of to a memory stream? (Thinking out loud.)

The goal is to get the stream into a ZipArchive using:

ZipArchive archive = new ZipArchive(stream)

And from there I can extract all the contents.  But getting to that point w/o memory errors is proving a real bugger.

Any ideas?

Body:
Using Azure Storage File Share this is the only way it worked for me without loading the entire ZIP into Memory. I tested with a 3GB ZIP File (with thousands of files or with a big file inside) and Memory/CPU was low and stable. I hope it helps!

var zipFiles = _directory.ListFilesAndDirectories()
    .OfType<CloudFile>()
    .Where(x => x.Name.ToLower().Contains(".zip"))
    .ToList();

foreach (var zipFile in zipFiles)
{
    using (var zipArchive = new ZipArchive(zipFile.OpenRead()))
    {
        foreach (var entry in zipArchive.Entries)
        {
            if (entry.Length > 0)
            {
                CloudFile extractedFile = _directory.GetFileReference(entry.Name);

                using (var entryStream = entry.Open())
                {
                    byte[] buffer = new byte[16 * 1024];
                    using (var ms = extractedFile.OpenWrite(entry.Length))
                    {
                        int read;
                        while ((read = entryStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                    }
                }
            }
        }
    }
}


问:
Trailing 0 decimal after casting to string to float
In redshift I'm trying to convert a string to a float and round to 2 decimal places. But when I do that I get a lot of trailing 0's at at the end.

```<code>select
'1.99'
, '1.99'::float
, round('1.99'::float , 2)
</code>```

Seems like the round function doesn't do anything.
I want to just get 1.99 as a float and not 1.9900000000000

I'm using DBeaver btw

答:
In most languages, round() alters the value not the length of a number.

Looks to me like you need to use trunc() instead or possibly as well.

See: Redshift docs

Body:
In redshift I'm trying to convert a string to a float and round to 2 decimal places. But when I do that I get a lot of trailing 0's at at the end.

select
'1.99'
, '1.99'::float
, round('1.99'::float , 2)

Seems like the round function doesn't do anything.
I want to just get 1.99 as a float and not 1.9900000000000

I'm using DBeaver btw


问:
Change cursor style depending on sort or not
I'm using the jqGrid and have 3 columns that can NOT be sorted.  At this point the cursor changes to a hand when the user hovers over the headers regardless of sorting set to true or false.  I'd like that cursor to be something other than a hand (text or pointer) on those column heads.  It's confusing to the users this way. Is this something that can be set?

Thanks,
Mark

答:
```<code>$("jquery selector to pick only non-sorted columns").css("cursor", "default");
</code>```


问:
How to see keyboard modifiers when program launched from windows?
I have a Qt application and would like to determine if Shift (or Ctrl) key was held down when the application was launched.  My goal is to implement a "safe mode" for the application.

I have tried using QApplication::keyboardModifiers() but that function always returns 0 (no modifiers) no matter what keys I have held down when start the app, either by double-clicking it or starting from the command line.

```<code>int main(int argc, char *argv[]) {

    QString homeDocs = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+"/";
    QCoreApplication::setApplicationName(getAppName());
    QCoreApplication::setOrganizationName(getDeveloperName());
    QCoreApplication::setOrganizationDomain(getDeveloperDomain());

    QSettings settings;

    QApplication a(argc, argv);
    QStringList args = a.arguments();

    Qt::KeyboardModifiers test = QApplication::keyboardModifiers();

</code>```

Receiving a code of 0 but was expecting bit flags indicating which keys were held down.

答:
 I think you tend to implemente a function that will be run when Ctrl was pressed enough time.

 You can override mousePressEvent to confirm Ctrl is pressed and start a timer, then you should alse override mouseReleaseEvent to confirm how long time ctrl pressed by the timer.

Body:
I have a Qt application and would like to determine if Shift (or Ctrl) key was held down when the application was launched.  My goal is to implement a "safe mode" for the application.

I have tried using QApplication::keyboardModifiers() but that function always returns 0 (no modifiers) no matter what keys I have held down when start the app, either by double-clicking it or starting from the command line.

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

    QString homeDocs = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+"/";
    QCoreApplication::setApplicationName(getAppName());
    QCoreApplication::setOrganizationName(getDeveloperName());
    QCoreApplication::setOrganizationDomain(getDeveloperDomain());

    QSettings settings;

    QApplication a(argc, argv);
    QStringList args = a.arguments();

    Qt::KeyboardModifiers test = QApplication::keyboardModifiers();

Receiving a code of 0 but was expecting bit flags indicating which keys were held down.