问:
unsupported operand type(s) for |=: 'list' and 'list'
I am having trouble with some code for an AMT22 encoder. I am getting the following error:
TypeError: unsupported operand type(s) for |=: 'list' and 'list'.
I know I cant do an operation like this on two lists, but I don't know how to declare currentPosition as uint16 as I would like too.

I am using python on a Raspberry Pi 4 B through which the encoders communicate by SPI, so I am using spidev library.

Here is all the code with the error attached at the bottom.

```<code>import time
from time import sleep
import RPi.GPIO as GPIO
import spidev
import math
import array as arr

BAUDRATE = 115200
AMT22_NOP = 0x00
AMT22_RESET = 0x60
AMT22_ZERO = 0x70

NEWLINE = 0x0A
TAB = 0x09

RES12 = 12
ENC_1 = 8
SPI_MOSI = 10
SPI_MISO = 9
SPI_SCLK = 13

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

GPIO.setup(SPI_MOSI, GPIO.OUT)
GPIO.setup(SPI_MISO, GPIO.IN)
GPIO.setup(SPI_SCLK, GPIO.OUT)
GPIO.setup(ENC_1, GPIO.OUT)

GPIO.output(ENC_1, True)

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 500
binaryArray = arr.array('d', [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])

def spiWriteRead(sendByte, encoder, releaseLine):
    GPIO.output(encoder, False)
    sleep(0.000003)
     data = spi.xfer([sendByte])
#     spi.writebytes([sendByte])
#     data = spi.readbytes(16)
    sleep(0.000003)
    GPIO.output(encoder, releaseLine)
    return data

def getPositionSPI(encoder):
    currentPosition = spiWriteRead(AMT22_NOP, encoder, False)
    sleep(0.000003)
    currentPosition |= spiWriteRead(AMT22_NOP, encoder, True)
    for i in range(16):
        binaryArray[i] = (0x01) & (currentPosition >> i)
    if ((binaryArray[15] is math.factorial(binaryArray[13]**binaryArray[11]**binaryArray[9]**binaryArray[7]**binaryArray[5]**binaryArray[3]**binaryArray[1])) and (binaryArray[14] is math.factorial(binaryArray[12]**binaryArray[10]**binaryArray[8]**binaryArray[6]**binaryArray[4]**binaryArray[2]**binaryArray[0]))):
        currentPosition & 0x3FFF
    else:
        currentPosition & 0xFFFF

    if (currentPosition != 0xFFFF):
        currentPosition >> 2

    return currentPosition

try:
    while True:
        attempts = 0
        encoderPosition = getPositionSPI(ENC_1)

        while (encoderPosition == 0xFFFF and attempts < 3):
            attempts += 1
            encoderPosition = getPositionSPI(ENC_1)

            if (encoderPosition == 0xFFFF):
                print("Encoder 0 error. Attempts: ")
                print(attempts)
            else:
                print("Encoder 0: ")
                print(encoderPosition)

            sleep(0.5)

except KeyboardInterrupt:
    print("Ctl C pressed - ending program")

GPIO.cleanup()
close()
print("Done")

Traceback (most recent call last):
  File "/home/pi/Desktop/AMT22.py", line 66, in <module>
    encoderPosition = getPositionSPI(ENC_1)
  File "/home/pi/Desktop/AMT22.py", line 50, in getPositionSPI
    currentPosition |= spiWriteRead(AMT22_NOP, encoder, True)
TypeError: unsupported operand type(s) for |=: 'list' and 'list'
</code>```

Any help would be appreciated,
Thank you!

答:
From what I can see, the method xfer returns a list of bytes and so does your spiWriteRead function.

I am going to assume that for your calculation you want to take the first two bytes from that list and convert them to a 16 bit unsigned integer in little-endian format.

You can use the struct module to do that:

```<code>import struct

currentPosition |= struct.unpack('<H', bytearray(spiWriteRead(AMT22_NOP, encoder, True)))[0]
</code>```

What this line does is as follows:

convert the list spiWriteRead returns in to an array of bytes so unpack can process it.

Unpack the array in to a single unsigned short ('H' formatting letter) in little-endian ('<' format sign) byte order.

Because unpack always returns a tuple, take the first element ([0]) which will be an integer, thus you can do the | (or) operation on it.

For more information on working with binary data in Python read the struct documentation.

Edit:
Looking again at the code, and considering the OP comment to this answer, it may be that the spiReadWrite function returns one byte at a time, and the or operation is to combine the high and low byte of the uint16.

If this is the case, there is no need to use the struct module, only extract the single member of the list that contains the actual byte value.

Note however, the result must be bit shifted not simply or'ed to get the correct value.

Here is how the code would look in that case:

(this again assumes we are working in little-endian, so least significant byte is read first)

```<code>currentPosition = spiWriteRead(AMT22_NOP, encoder, False)[0]
sleep(0.000003)
currentPosition |= spiWriteRead(AMT22_NOP, encoder, True)[0] << 8
</code>```

Note the only difference from the original code is adding the list index [0] and in the second call shifting all the bits by 8 places to make them the higher byte of a 2 byte int.

Body:
I am having trouble with some code for an AMT22 encoder. I am getting the following error:
TypeError: unsupported operand type(s) for |=: 'list' and 'list'.
I know I cant do an operation like this on two lists, but I don't know how to declare currentPosition as uint16 as I would like too.

I am using python on a Raspberry Pi 4 B through which the encoders communicate by SPI, so I am using spidev library.

Here is all the code with the error attached at the bottom.

import time
from time import sleep
import RPi.GPIO as GPIO
import spidev
import math
import array as arr

BAUDRATE = 115200
AMT22_NOP = 0x00
AMT22_RESET = 0x60
AMT22_ZERO = 0x70

NEWLINE = 0x0A
TAB = 0x09

RES12 = 12
ENC_1 = 8
SPI_MOSI = 10
SPI_MISO = 9
SPI_SCLK = 13

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

GPIO.setup(SPI_MOSI, GPIO.OUT)
GPIO.setup(SPI_MISO, GPIO.IN)
GPIO.setup(SPI_SCLK, GPIO.OUT)
GPIO.setup(ENC_1, GPIO.OUT)

GPIO.output(ENC_1, True)

spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 500
binaryArray = arr.array('d', [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])

def spiWriteRead(sendByte, encoder, releaseLine):
    GPIO.output(encoder, False)
    sleep(0.000003)
     data = spi.xfer([sendByte])
#     spi.writebytes([sendByte])
#     data = spi.readbytes(16)
    sleep(0.000003)
    GPIO.output(encoder, releaseLine)
    return data

def getPositionSPI(encoder):
    currentPosition = spiWriteRead(AMT22_NOP, encoder, False)
    sleep(0.000003)
    currentPosition |= spiWriteRead(AMT22_NOP, encoder, True)
    for i in range(16):
        binaryArray[i] = (0x01) & (currentPosition >> i)
    if ((binaryArray[15] is math.factorial(binaryArray[13]**binaryArray[11]**binaryArray[9]**binaryArray[7]**binaryArray[5]**binaryArray[3]**binaryArray[1])) and (binaryArray[14] is math.factorial(binaryArray[12]**binaryArray[10]**binaryArray[8]**binaryArray[6]**binaryArray[4]**binaryArray[2]**binaryArray[0]))):
        currentPosition & 0x3FFF
    else:
        currentPosition & 0xFFFF

    if (currentPosition != 0xFFFF):
        currentPosition >> 2

    return currentPosition

try:
    while True:
        attempts = 0
        encoderPosition = getPositionSPI(ENC_1)

        while (encoderPosition == 0xFFFF and attempts < 3):
            attempts += 1
            encoderPosition = getPositionSPI(ENC_1)

            if (encoderPosition == 0xFFFF):
                print("Encoder 0 error. Attempts: ")
                print(attempts)
            else:
                print("Encoder 0: ")
                print(encoderPosition)

            sleep(0.5)

except KeyboardInterrupt:
    print("Ctl C pressed - ending program")

GPIO.cleanup()
close()
print("Done")

Traceback (most recent call last):
  File "/home/pi/Desktop/AMT22.py", line 66, in <module>
    encoderPosition = getPositionSPI(ENC_1)
  File "/home/pi/Desktop/AMT22.py", line 50, in getPositionSPI
    currentPosition |= spiWriteRead(AMT22_NOP, encoder, True)
TypeError: unsupported operand type(s) for |=: 'list' and 'list'

Any help would be appreciated,
Thank you!

Body:
From what I can see, the method xfer returns a list of bytes and so does your spiWriteRead function.

I am going to assume that for your calculation you want to take the first two bytes from that list and convert them to a 16 bit unsigned integer in little-endian format.

You can use the struct module to do that:

import struct

currentPosition |= struct.unpack('<H', bytearray(spiWriteRead(AMT22_NOP, encoder, True)))[0]

What this line does is as follows:

convert the list spiWriteRead returns in to an array of bytes so unpack can process it.

Unpack the array in to a single unsigned short ('H' formatting letter) in little-endian ('<' format sign) byte order.

Because unpack always returns a tuple, take the first element ([0]) which will be an integer, thus you can do the | (or) operation on it.

For more information on working with binary data in Python read the struct documentation.

Edit:
Looking again at the code, and considering the OP comment to this answer, it may be that the spiReadWrite function returns one byte at a time, and the or operation is to combine the high and low byte of the uint16.

If this is the case, there is no need to use the struct module, only extract the single member of the list that contains the actual byte value.

Note however, the result must be bit shifted not simply or'ed to get the correct value.

Here is how the code would look in that case:

(this again assumes we are working in little-endian, so least significant byte is read first)

currentPosition = spiWriteRead(AMT22_NOP, encoder, False)[0]
sleep(0.000003)
currentPosition |= spiWriteRead(AMT22_NOP, encoder, True)[0] << 8

Note the only difference from the original code is adding the list index [0] and in the second call shifting all the bits by 8 places to make them the higher byte of a 2 byte int.


来源: stackexchange

问:
Converting DATE to INT in Infopath
convert MM-DD-YYYY TO MMDDYYYY infopath

so for example date: 05-05-2011 would be 05052011 in Info path?

How do I do this?

答:
number(concat(substring(string(.), 1, 4), substring(string(.), 6, 2), substring(string(.), 9, 2)))

string(.) will convert the date field into a string on the format yyyy-mm-dd. I have written this rule in the text change of the date field, that's why . is used, you can replace the . with the XPath to your field.

ContentLicense: CC BY-SA 3.0

Title: Converting DATE to INT in Infopath


问:
Meaning of curly braces after the "is" operator
I found in some C# source code the following line:

```<code>if(!(context.Compilation.GetTypeByMetadataName("Xunit.FactAttribute")
         is { } factAttribute))
</code>```

and here is another one:

```<code>if(!(diagnostic.Location.SourceTree is { } tree))
</code>```

What is the meaning of the curly braces ({ }) after the is operator?

答:
This is a new pattern matching feature which was introduced in C# 8.0 and is called property pattern. In this particular case it is used to check that object is not null, example from the linked article:</p>
```<code>static string Display(object o) => o switch
{
    Point { X: 0, Y: 0 }         p => "origin",
    Point { X: var x, Y: var y } p => $"({x}, {y})",
    {}                           => o.ToString(),
    null                         => "null"
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I found in some C# source code the following line:

if(!(context.Compilation.GetTypeByMetadataName("Xunit.FactAttribute")
         is { } factAttribute))

and here is another one:

if(!(diagnostic.Location.SourceTree is { } tree))

What is the meaning of the curly braces ({ }) after the is operator?

Body:
This is a new pattern matching feature which was introduced in C# 8.0 and is called property pattern. In this particular case it is used to check that object is not null, example from the linked article:

static string Display(object o) => o switch
{
    Point { X: 0, Y: 0 }         p => "origin",
    Point { X: var x, Y: var y } p => $"({x}, {y})",
    {}                           => o.ToString(),
    null                         => "null"
};


问:
SQL Get current month
I have table1 with data

```<code>file  Startdate
A     2020-05-01
B     2020-06-01
</code>```

We have today is 2020-06-01 and I could use Select and where startdate ='2020-06-01'

But I try this query and not get 2020-06-01

```<code>select file from table1
where
 startdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
         and startdate < datefromparts(year(getdate()), month(getdate()), 1)
</code>```

Please correct me. Thank you

答:
datefromparts clutter it, it's much easier to write and understand it like this.
Mysql

```<code>SELECT DATE_FORMAT(getdate(), "%Y-%m-01");
</code>```

MSSql

```<code>SELECT CONVERT(NOW(), varchar(8),120) + '01'
</code>```

Title: SQL Get current month

Body:
I have table1 with data

file  Startdate
A     2020-05-01
B     2020-06-01

We have today is 2020-06-01 and I could use Select and where startdate ='2020-06-01'

But I try this query and not get 2020-06-01

select file from table1
where
 startdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
         and startdate < datefromparts(year(getdate()), month(getdate()), 1)

Please correct me. Thank you

Body:
datefromparts clutter it, it's much easier to write and understand it like this.
Mysql

SELECT DATE_FORMAT(getdate(), "%Y-%m-01");

MSSql

SELECT CONVERT(NOW(), varchar(8),120) + '01'


问:
In the Bot Framework, Is there a common location where I can set the speak property to true in ChannelData?
I am using the Bot Framework to build a speech enabled Bot which handles various events, and triggers a Dialog based on the event. The Bot is connected using WebChat as the interface. As this is mostly a proactive scenario, there is no prior input from the user. As a result, even though the dialog is triggered, there is no output speech, since the speech is activated only if the previous interaction was via Speech. To enable output speech, I right now have to explicitly set the ChannelData of every outgoing activity with 'speak' property as true using activity.ChannelData = new {speak = true};, which WebChat understands , and voices out the message associated with the Activity.

Is there a more efficient way to do this, by setting this property in a common location, so that all outgoing activities by default will be spoken out?

答:
To run any code at all whenever the turn context sends an activity, you can use TurnContext.OnSendActivities:

```<code>turnContext.OnSendActivities(async (tc, activities, next) =>
{
    activities.ForEach(activity => activity.ChannelData = new { speak = true });

    return await next().ConfigureAwait(false);
});
</code>```

This is often done with middleware, but you could possibly choose to do it at the start of your main bot logic.

Body:
To run any code at all whenever the turn context sends an activity, you can use TurnContext.OnSendActivities:

turnContext.OnSendActivities(async (tc, activities, next) =>
{
    activities.ForEach(activity => activity.ChannelData = new { speak = true });

    return await next().ConfigureAwait(false);
});

This is often done with middleware, but you could possibly choose to do it at the start of your main bot logic.


问:
How can I combine these HTML files in order to run them at the same time on a single webpage?
My knowledge of HTML/Javascript is extremely limited. I was working with this code I found online, and wanted to combine the two programs so that I had the brickbreaker game on top, and the live data updating beneath it. The two activities don't need to be linked, but want them to appear on the same webpage, both within view without having to scroll. I appreciate any help!

```<code><!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function () {

var dataPoints1 = [];
var dataPoints2 = [];
var dataPoints3 = [];

var chart = new CanvasJS.Chart("chartContainer", {
    zoomEnabled: true,
    title: {
        text: "Protein Activity"
    },
    axisX: {
        title: "chart updates every 1 secs"
    },
    axisY:{
        prefix: "",
        includeZero: false
    },
    toolTip: {
        shared: true
    },
    legend: {
        cursor:"pointer",
        verticalAlign: "top",
        fontSize: 22,
        fontColor: "dimGrey",
        itemclick : toggleDataSeries
    },
    data: [{
        type: "line",
        xValueType: "dateTime",
        yValueFormatString: "####.00",
        xValueFormatString: "hh:mm:ss",
        showInLegend: true,
        name: "Blue Protein",
        dataPoints: dataPoints1
        },
        {
            type: "line",
            xValueType: "dateTime",
            yValueFormatString: "####.00",
            xValueFormatString: "hh:mm:ss",
            showInLegend: true,
            name: "Red Protein" ,
            dataPoints: dataPoints2
    },
    {
        type: "line",
        xValueType: "dateTime",
        yValueFormatString: "####.00",
        xValueFormatString: "hh:mm:ss",
        showInLegend: true,
        name: "Green Protein" ,
        dataPoints: dataPoints3
}]
});

function toggleDataSeries(e) {
    if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
        e.dataSeries.visible = false;
    }
    else {
        e.dataSeries.visible = true;
    }
    chart.render();
}
//initial interval was 3000 (every 3 seconds)
var updateInterval = 1000; // 1 second interval 1000
// initial value originally 600 and 605
var yValue1 = 0;
var yValue2 = 0
var yValue3 = 0;

var time = new Date;
// starting at 9.30 am

time.setMinutes(00);
time.setSeconds(00);

function updateChart(count) {

    count = count || 1;
    var deltaY1, deltaY2, deltaY3;
    for (var i = 0; i < count; i++) {
        time.setTime(time.getTime() + updateInterval);
        // dropping the parenthetical manipulators
        // the change is between 0 and 1 ... place holder until we connect with the game
        deltaY1 =  Math.random() ;
        deltaY2 =  Math.random();
        deltaY3 =  Math.random();

    // adding random value and rounding it to two digits.
    yValue1 = Math.round((yValue1 + deltaY1)*100)/100;
    yValue2 = Math.round((yValue2 + deltaY2)*100)/100;
    yValue3 = Math.round((yValue3 + deltaY3)*100)/100;
    // pushing the new values
    dataPoints1.push({
        x: time.getTime(),
        y: yValue1
    });
    dataPoints2.push({
        x: time.getTime(),
        y: yValue2
    });
    dataPoints3.push({
        x: time.getTime(),
        y: yValue3
    });
    }

    // updating legend text with  updated with y Value
    chart.options.data[0].legendText = " Blue Protein:  " + yValue1;
    chart.options.data[1].legendText = " Red Protein:  " + yValue2;
    chart.options.data[2].legendText = " Green Protein:  " + yValue3;
    chart.render();

}
// generates first set of dataPoints
updateChart(0);
setInterval(function(){updateChart()}, updateInterval);

}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
</code>```

and

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Gamedev Canvas Workshop</title>
    <style>
        * { padding: 0; margin: 0; }
        canvas { background: #eee; display: block; margin: 0 auto; }
    </style>
</head>
<body>

<canvas id="myCanvas" width="480" height="320"></canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
var brickRowCount = 5;
var brickColumnCount = 3;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;

var bricks = [];
for(var c=0; c<brickColumnCount; c++) {
  bricks[c] = [];
  for(var r=0; r<brickRowCount; r++) {
    bricks[c][r] = { x: 0, y: 0, status: 1 };
  }
}

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
document.addEventListener("mousemove", mouseMoveHandler, false);

function keyDownHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = true;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = false;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = false;
    }
}

function mouseMoveHandler(e) {
  var relativeX = e.clientX - canvas.offsetLeft;
  if(relativeX > 0 && relativeX < canvas.width) {
    paddleX = relativeX - paddleWidth/2;
  }
}
function collisionDetection() {
  for(var c=0; c<brickColumnCount; c++) {
    for(var r=0; r<brickRowCount; r++) {
      var b = bricks[c][r];
      if(b.status == 1) {
        if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
          dy = -dy;
          b.status = 0;
          score++;
          if(score == brickRowCount*brickColumnCount) {
            alert("YOU WIN, CONGRATS!");
            document.location.reload();
          }
        }
      }
    }
  }
}

function drawBall() {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI*2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}
function drawPaddle() {
  ctx.beginPath();
  ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}
function drawBricks() {
  for(var c=0; c<brickColumnCount; c++) {
    for(var r=0; r<brickRowCount; r++) {
      if(bricks[c][r].status == 1) {
        var brickX = (r*(brickWidth+brickPadding))+brickOffsetLeft;
        var brickY = (c*(brickHeight+brickPadding))+brickOffsetTop;
        bricks[c][r].x = brickX;
        bricks[c][r].y = brickY;
        ctx.beginPath();
        ctx.rect(brickX, brickY, brickWidth, brickHeight);
        ctx.fillStyle = "#0095DD";
        ctx.fill();
        ctx.closePath();
      }
    }
  }
}
function drawScore() {
  ctx.font = "16px Arial";
  ctx.fillStyle = "#0095DD";
  ctx.fillText("Score: "+score, 8, 20);
}
function drawLives() {
  ctx.font = "16px Arial";
  ctx.fillStyle = "#0095DD";
  ctx.fillText("Lives: "+lives, canvas.width-65, 20);
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBricks();
  drawBall();
  drawPaddle();
  drawScore();
  drawLives();
  collisionDetection();

  if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
    dx = -dx;
  }
  if(y + dy < ballRadius) {
    dy = -dy;
  }
  else if(y + dy > canvas.height-ballRadius) {
    if(x > paddleX && x < paddleX + paddleWidth) {
      dy = -dy;
    }
    else {
      lives--;
      if(!lives) {
        alert("GAME OVER");
        document.location.reload();
      }
      else {
        x = canvas.width/2;
        y = canvas.height-30;
        dx = 3;
        dy = -3;
        paddleX = (canvas.width-paddleWidth)/2;
      }
    }
  }

  if(rightPressed && paddleX < canvas.width-paddleWidth) {
    paddleX += 7;
  }
  else if(leftPressed && paddleX > 0) {
    paddleX -= 7;
  }

  x += dx;
  y += dy;
  requestAnimationFrame(draw);
}

draw();
</script>

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

答: You could create different java script files separately and link them to the same HTML page. </p>

Body:
My knowledge of HTML/Javascript is extremely limited. I was working with this code I found online, and wanted to combine the two programs so that I had the brickbreaker game on top, and the live data updating beneath it. The two activities don't need to be linked, but want them to appear on the same webpage, both within view without having to scroll. I appreciate any help!

<!DOCTYPE HTML>

and

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Gamedev Canvas Workshop</title>

<canvas id="myCanvas" width="480" height="320"></canvas>


问:
Firing off event listeners and CSS classes in the same condition
In the following code block in JS, I would like to hide/show a button depending on the validity of input fields in a form. When the .confirm button is clicked and the form is valid, I would like to fire off an event listener on the latter button to add a checkmark.

However, only the first two lines of code are firing off but the event listener is not. Any suggestions on how I could add/remove buttons and upon the same condition make the checkmark appear on the body?

```<code>if (form.checkValidity()) {
 document.querySelector(".formSubmit").classList.add("formSubmitShow");
 document.querySelector(".confirm").classList.add("confirmHide");
 document.querySelector(".confirm").addEventListener("click", (e)=>{
         body.classList.add("checkmark");
        });
      } else {
        formElements.forEach((el) => {
          if (!el.checkValidity()) {
            el.classList.add("invalid");
          }
        });
      }
</code>```

```<code>.checkmark {
  content: url(static/gifs/check.gif);
}

</code>```

答:
You said

When the .confirm button is clicked and the form is valid

so maybe you just need to restructure your code

The idea of having an event listener is not firing it when it's executed in code, but when the user make the event(which is something not known as the time of writing code & that's why it's made as a listener)

document.querySelector(".confirm").addEventListener("click", (e) => {

  if (form.checkValidity()) {
    document.querySelector(".formSubmit").classList.add("formSubmitShow");
    document.querySelector(".confirm").classList.add("confirmHide");

    body.classList.add("checkmark");

  } else {
    formElements.forEach((el) => {
      if (!el.checkValidity()) {
        el.classList.add("invalid");
      }
    });
  }

});
```

I hope restructuring will help :D

Body:
In the following code block in JS, I would like to hide/show a button depending on the validity of input fields in a form. When the .confirm button is clicked and the form is valid, I would like to fire off an event listener on the latter button to add a checkmark.

However, only the first two lines of code are firing off but the event listener is not. Any suggestions on how I could add/remove buttons and upon the same condition make the checkmark appear on the body?

if (form.checkValidity()) {
 document.querySelector(".formSubmit").classList.add("formSubmitShow");
 document.querySelector(".confirm").classList.add("confirmHide");
 document.querySelector(".confirm").addEventListener("click", (e)=>{
         body.classList.add("checkmark");
        });
      } else {
        formElements.forEach((el) => {
          if (!el.checkValidity()) {
            el.classList.add("invalid");
          }
        });
      }

.checkmark {
  content: url(static/gifs/check.gif);
}

Body:
You said

When the .confirm button is clicked and the form is valid

so maybe you just need to restructure your code

The idea of having an event listener is not firing it when it's executed in code, but when the user make the event(which is something not known as the time of writing code & that's why it's made as a listener)

document.querySelector(".confirm").addEventListener("click", (e) => {

  if (form.checkValidity()) {
    document.querySelector(".formSubmit").classList.add("formSubmitShow");
    document.querySelector(".confirm").classList.add("confirmHide");

    body.classList.add("checkmark");

  } else {
    formElements.forEach((el) => {
      if (!el.checkValidity()) {
        el.classList.add("invalid");
      }
    });
  }

});

I hope restructuring will help :D


问:
Regex matching for optional strings
I am trying to come up with a smallest regex possible for extracting parts of a string with the last section being an optional one. The string will look something like:

```<code>jack:Bill(23):Space Force (23, Apple;Orange)
</code>```

or

```<code>jack:Bill(23):Space Force
</code>```

I need to extract as follows:

```<code>Jack
Bill(23)
Space Force
23
Apple;Orange
</code>```

The last 2 items may or may not appear based on the source string. I am trying with a regex like:

```<code>(.*?):(.*?):(.*?)(\\(([0-9]+),([^\\)]*)?\\))?
</code>```

But this does not seem to work.

Title: Regex matching for optional strings

Body:
I am trying to come up with a smallest regex possible for extracting parts of a string with the last section being an optional one. The string will look something like:

jack:Bill(23):Space Force (23, Apple;Orange)

or

jack:Bill(23):Space Force

I need to extract as follows:

Jack
Bill(23)
Space Force
23
Apple;Orange

The last 2 items may or may not appear based on the source string. I am trying with a regex like:

(.*?):(.*?):(.*?)(\\(([0-9]+),([^\\)]*)?\\))?

But this does not seem to work.

Body: I got it working with (.*?):(.*?):([^\\(]*)(\\(([0-9]+), ([^\\)]*)?\\))?


答:
You can simply join with condition as below

```<code>studentDF.join(markDF,
  studentDF("Marks").lt(markDF("Max_Mark")) && studentDF("Marks").gt(markDF("Min_Mark"))
).drop("Min_Mark", "Max_Mark")
</code>```

Output:

```<code>+---+--------+-----+-----+
|ID |Name    |Marks|Grade|
+---+--------+-----+-----+
|1  |Julia   |88   |9    |
|2  |Samantha|68   |7    |
|3  |Maria   |99   |10   |
|4  |Scarlet |78   |8    |
|5  |Ashley  |63   |7    |
|6  |Jane    |81   |9    |
+---+--------+-----+-----+
</code>```

Title: spark fast range lookup on 2 columns

Body:
I have 2 datasets, StudentMarks and Grades.
The Grades table has maximum and minimum marks for each grade.
Grades Dataset

+-----+--------+--------+
|Grade|Min_Mark|Max_Mark|
+-----+--------+--------+
|    1|       0|       9|
|    2|      10|      19|
|    3|      20|      29|
|    4|      30|      39|
|    5|      40|      49|
|    6|      50|      59|
|    7|      60|      69|
|    8|      70|      79|
|    9|      80|      89|
|   10|      90|     100|
+-----+--------+--------+

StudentMarks Dataset

+---+--------+-----+
| ID|    Name|Marks|
+---+--------+-----+
|  1|   Julia|   88|
|  2|Samantha|   68|
|  3|   Maria|   99|
|  4| Scarlet|   78|
|  5|  Ashley|   63|
|  6|    Jane|   81|
+---+--------+-----+

I need to find grade for each student. Expected Result-

+---+--------+-----+-----+
| ID|    Name|Marks|Grade|
+---+--------+-----+-----+
|  1|   Julia|   88| 9   |
|  2|Samantha|   68| 7   |
|  3|   Maria|   99| 10  |
|  4| Scarlet|   78| 8   |
|  5|  Ashley|   63| 7   |
|  6|    Jane|   81| 9   |
+---+--------+-----+-----+

Is there an efficient way of looking up for number in a range?

Body:
You can simply join with condition as below

studentDF.join(markDF,
  studentDF("Marks").lt(markDF("Max_Mark")) && studentDF("Marks").gt(markDF("Min_Mark"))
).drop("Min_Mark", "Max_Mark")

Output:

+---+--------+-----+-----+
|ID |Name    |Marks|Grade|
+---+--------+-----+-----+
|1  |Julia   |88   |9    |
|2  |Samantha|68   |7    |
|3  |Maria   |99   |10   |
|4  |Scarlet |78   |8    |
|5  |Ashley  |63   |7    |
|6  |Jane    |81   |9    |
+---+--------+-----+-----+


问:
Whats is systables in Guidewire?
I start PolicyCenter in Debug Mode and console show me following message:

```<code>***********************************************************************
INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\underwriting_companies.xml
c0059               2018-04-21 00:57:05,561  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\underwriting_companies.xml chunk #2
c0059               2018-04-21 00:57:05,564  INFO Configuration.ProductModel Loading C:\PolicyCenter\modules\configuration\config\resources\systables\uw_issue_types.xml
c0059               2018-04-21 00:57:52,029  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\uw_issue_types.xml
c0059               2018-04-21 00:58:16,916  INFO Configuration.ProductModel Loading C:\PolicyCenter\modules\configuration\config\resources\systables\vehicle_class_codes.xml
c0059               2018-04-21 01:00:30,555  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\vehicle_class_codes.xml
c0059               2018-04-21 01:00:30,558  INFO Configuration.ProductModel Loading C:\PolicyCenter\modules\configuration\config\resources\systables\vehicle_industry_codes.xml
c0059               2018-04-21 01:00:31,036  INFO Server.RunLevel Memory usage: 500.824 MB used (both active and stale objects), 269.674 MB free, 770.500 MB total, 1820.500 MB max. --  Please read 'Memory usage logging' in the System Administration Guide for information on how to interpret these numbers.
c0059               2018-04-21 01:00:41,732  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\vehicle_industry_codes.xml
c0059               2018-04-21 01:00:41,732  INFO Configuration.ProductModel Loading C:\PolicyCenter\modules\configuration\config\resources\systables\wc_class_codes.xml
c0059               2018-04-21 01:05:50,189  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\wc_class_codes.xml

***************************************************************************
</code>```

This is very slow, I would like to know whats are systables in Guidewire

答:
First of all, this is only loaded again after you drop your PC database. So if you move to file based h2 database, it will only load once and won't consume time until your next PC db drop.

System tables is basically a way to design "static" database tables, such as company divisions list, or taxation zones data etc. that would become invariant over subsequent database drops. 'Dictionary data' is kept in system tables and Product Designer supports editing those (because you need to create them from .xml file anyway) in some meanigful way by eg. hinting typelist values in the columns.

Title: Whats is systables in Guidewire?

Body:
I start PolicyCenter in Debug Mode and console show me following message:

***********************************************************************
INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\underwriting_companies.xml
c0059               2018-04-21 00:57:05,561  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\underwriting_companies.xml chunk #2
c0059               2018-04-21 00:57:05,564  INFO Configuration.ProductModel Loading C:\PolicyCenter\modules\configuration\config\resources\systables\uw_issue_types.xml
c0059               2018-04-21 00:57:52,029  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\uw_issue_types.xml
c0059               2018-04-21 00:58:16,916  INFO Configuration.ProductModel Loading C:\PolicyCenter\modules\configuration\config\resources\systables\vehicle_class_codes.xml
c0059               2018-04-21 01:00:30,555  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\vehicle_class_codes.xml
c0059               2018-04-21 01:00:30,558  INFO Configuration.ProductModel Loading C:\PolicyCenter\modules\configuration\config\resources\systables\vehicle_industry_codes.xml
c0059               2018-04-21 01:00:31,036  INFO Server.RunLevel Memory usage: 500.824 MB used (both active and stale objects), 269.674 MB free, 770.500 MB total, 1820.500 MB max. --  Please read 'Memory usage logging' in the System Administration Guide for information on how to interpret these numbers.
c0059               2018-04-21 01:00:41,732  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\vehicle_industry_codes.xml
c0059               2018-04-21 01:00:41,732  INFO Configuration.ProductModel Loading C:\PolicyCenter\modules\configuration\config\resources\systables\wc_class_codes.xml
c0059               2018-04-21 01:05:50,189  INFO Configuration.ProductModel Committing system tables file C:\PolicyCenter\modules\configuration\config\resources\systables\wc_class_codes.xml

***************************************************************************

This is very slow, I would like to know whats are systables in Guidewire


问:
Can I use Backblaze B2 to host user image uploads? Their TOS is difficult to understand
I want to build a simple dummy app like OfferUp where users can upload 5 images per listing.

I would normally use AWS S3 with Cloudfront to serve these images.

Can I do the same with Backblaze B2? Is this an intended usecase for the product?

答: Yev from Backblaze here -> Yes, you can absolutely use Backblaze B2 to host images, and we have a bandwidth partnership with Cloudflare (https://help.backblaze.com/hc/en-us/articles/217666928-Using-Backblaze-B2-with-the-Cloudflare-CDN) if you also need a CDN solution. </p>


问:
Do exec() calls fork for each command if passed a shell script?
For each command in a shell script passed to exec(), is it forked and ran in a child process?
Say I have a shell script called test.sh with the following contents;

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

echo Hello
echo There
</code>```

What I want to know is how the series of commands is treated if I were to call execvp() on test.sh in a C program.

For each command within the script, is there a fork followed by another exec call on that command, before a return to the parent and a repeat for the next command?

So far I have used strace on this exact example. My findings are that if I put two echos into the script, there are no calls to clone() (which I believe equates to forking?), but if I put two separate cats as such:

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

cat file1
cat file2
</code>```

Then I find two calls to clone in the strace. At the same time, stracing a singular cat call on its own, without running it from an execvp call on a shell script, does not yield any clones in the strace.

I would really appreciate a clarification on the way which exec calls handle shell scripts.

答:
The bash shell has a number of built-in commands that are executed in the same process as the shell.  The echo command is one of those built in commands.

cat on the other hand is at external program, so the shell must fork and exec to create a process and run the program.

Body:
For each command in a shell script passed to exec(), is it forked and ran in a child process?
Say I have a shell script called test.sh with the following contents;

#!/bin/bash

echo Hello
echo There

What I want to know is how the series of commands is treated if I were to call execvp() on test.sh in a C program.

For each command within the script, is there a fork followed by another exec call on that command, before a return to the parent and a repeat for the next command?

So far I have used strace on this exact example. My findings are that if I put two echos into the script, there are no calls to clone() (which I believe equates to forking?), but if I put two separate cats as such:

#!/bin/bash

cat file1
cat file2

Then I find two calls to clone in the strace. At the same time, stracing a singular cat call on its own, without running it from an execvp call on a shell script, does not yield any clones in the strace.

I would really appreciate a clarification on the way which exec calls handle shell scripts.


问:
Do unbuffered queries for one request
I'm looking to do unbuffered queries only on some requests.

In MySQL I was doing this:

```<code>$req = mysql_unbuffered_query('SELECT * FROM forum_topics
ORDER BY (topic_id/topic_stick) DESC, topic_last_post DESC');
while($data = mysql_fetch_assoc($req)) {
   // display results...
}
</code>```

I looked at PHP doc, and according to it in pdo we must proceed this way to do queries unbuffered:

```<code>$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$uresult = $pdo->query("SELECT Name FROM City");

if ($uresult) {
   while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
       echo $row['Name'] . PHP_EOL;
   }
}
</code>```

But is it possible to do it unbuffered only for the "forum_topics" table results without setting all pdo instance to unbuffered?

答:
MySQL does not implement statement-level attribute setting.

Source:

Here is your error message:

https://github.com/php/php-src/blob/master/ext/pdo/pdo_stmt.c#L1630

```<code>pdo_raise_impl_error(stmt->dbh, stmt, "IM001", "This driver doesn't support setting attributes");
</code>```

And the condition above is checked on the stmt->methods->set_attribute above.

The stmt->methods is defined above and the type is declared at:

https://github.com/php/php-src/blob/5d6e923d46a89fe9cd8fb6c3a6da675aa67197b4/ext/pdo/php_pdo_driver.h#L417

```<code>struct pdo_stmt_methods
</code>```

The set_attribute parameter is the 10th struct entry.

Here is the MySQL PDO implementation. And the statements methods are defined here:

https://github.com/php/php-src/blob/2ba4fb126391c578d20d859c841c4d31cd14adef/ext/pdo_mysql/mysql_statement.c#L935

```<code>NULL, /* set_attr */
</code>```

This shows that the MySQL PDO module does implement that feature.

Discussion:

I have reviewed other extensions. And only the Firebird PDO database module supports that feature.

Title: Do unbuffered queries for one request

Body:
I'm looking to do unbuffered queries only on some requests.

In MySQL I was doing this:

$req = mysql_unbuffered_query('SELECT * FROM forum_topics
ORDER BY (topic_id/topic_stick) DESC, topic_last_post DESC');
while($data = mysql_fetch_assoc($req)) {
   // display results...
}

I looked at PHP doc, and according to it in pdo we must proceed this way to do queries unbuffered:

$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$uresult = $pdo->query("SELECT Name FROM City");

if ($uresult) {
   while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
       echo $row['Name'] . PHP_EOL;
   }
}

But is it possible to do it unbuffered only for the "forum_topics" table results without setting all pdo instance to unbuffered?

Body:
MySQL does not implement statement-level attribute setting.

Source:

Here is your error message:

https://github.com/php/php-src/blob/master/ext/pdo/pdo_stmt.c#L1630

pdo_raise_impl_error(stmt->dbh, stmt, "IM001", "This driver doesn't support setting attributes");

And the condition above is checked on the stmt->methods->set_attribute above.

The stmt->methods is defined above and the type is declared at:

https://github.com/php/php-src/blob/5d6e923d46a89fe9cd8fb6c3a6da675aa67197b4/ext/pdo/php_pdo_driver.h#L417

struct pdo_stmt_methods

The set_attribute parameter is the 10th struct entry.

Here is the MySQL PDO implementation. And the statements methods are defined here:

https://github.com/php/php-src/blob/2ba4fb126391c578d20d859c841c4d31cd14adef/ext/pdo_mysql/mysql_statement.c#L935

NULL, /* set_attr */

This shows that the MySQL PDO module does implement that feature.

Discussion:

I have reviewed other extensions. And only the Firebird PDO database module supports that feature.


问:
Understanding the decompilation of an object to source code
First of all, I am a student, I do not yet have extensive knowledge about C, C ++ and assembler, so I am making a extreme effort to understand it.

I have this piece of assembly code from an Intel x86-32 bit processor.

My goal is to transform it to source code.

```<code>0x80483dc <main>:    push       ebp
0x80483dd <main+1>:  mov        ebp,esp
0x80483df <main+3>:  sub        esp,0x10
0x80483e2 <main+6>:  mov        DWORD PTR [ebp-0x8],0x80484d0
0x80483e9 <main+13>: lea        eax,[ebp-0x8]
0x80483ec <main+16>: mov        DWORD PTR [ebp-0x4],eax
0x80483ef <main+19>: mov        eax,DWORD PTR [ebp-0x4]
0x80483f2 <main+22>: mov        edx,DWORD PTR [eax+0xc]
0x80483f5 <main+25>: mov        eax,DWORD PTR [ebp-0x4]
0x80483f8 <main+28>: movzx      eax,WORD PTR [eax+0x10]
0x80483fc <main+32>: cwde
0x80483fd <main+33>: add        edx, eax
0x80483ff <main+35>: mov        eax,DWORD PTR [ebp-0x4]
0x8048402 <main+38>: mov        DWORD PTR [eax+0xc],edx
0x8048405 <main+41>: mov        eax,DWORD PTR [ebp-0x4]
0x8048408 <main+44>: movzx      eax,BYTE PTR [eax]
0x804840b <main+47>: cmp        al,0x4f
0x804840d <main+49>: jne        0x8048419 <main+61>
0x804840f <main+51>: mov        eax,DWORD PTR [ebp-0x4]
0x8048412 <main+54>: movzx      eax,BYTE PTR [eax]
0x8048415 <main+57>: cmp        al,0x4b
0x8048417 <main+59>: je         0x804842d <main+81>
0x8048419 <main+61>: mov        eax,DWORD PTR [ebp-0x4]
0x804841c <main+64>: mov        eax,DWORD PTR [eax+0xc]
0x804841f <main+67>: mov        edx, eax
0x8048421 <main+69>: and        edx,0xf0f0f0f
0x8048427 <main+75>: mov        eax,DWORD PTR [ebp-0x4]
0x804842a <main+78>: mov        DWORD PTR [eax+0x4],edx
0x804842d <main+81>: mov        eax,0x0
0x8048432 <main+86>: leave
0x8048433 <main+87>: ret
</code>```

This is what I understand from the code:

There are 4 variables:

```<code>a = [ebp-0x8] ebp
b = [ebp-0x4] eax
c = [eax + 0xc] edx
d = [eax + 0x10] eax
</code>```

Values:

```<code>0x4 = 4
0x8 = 8
0xc = 12
0x10 = 16
0x4b = 75
0x4f = 79
</code>```

Types:

```<code>char (8 bits) = 1 BYTE
short (16 bits) = WORD
int (32 bit) = DWORD
long (32 bits) = DWORD
long long (32 bit) = DWORD
</code>```

This is what I was able to create:

```<code>#include <stdio.h>
int main (void)
{
   int a = 0x80484d0;
   int b
   short c;
   int d;

   c + b?
if (79 <= al) {
instructions
} else {
instructions
}

   return 0
}
</code>```

But I'm stuck. Nor can I understand what the sentence "cmp al .." compares to, what is "al"?

How do these instructions work?

EDIT1:

That said, as you comment the assembly seems to be wrong or as someone comments say, it is insane!

The code and the exercise are from the following book called: "Reversing, Reverse Engineering" on page 140 (3.8 Proposed Exercises). It would never have occurred to me that it was wrong, if so, this clearly makes it difficult for me to learn ...

So it is not possible to do a reversing to get the source code because it is not a good assembly? Maybe I am not oppressed? Is it possible to optimize it?

EDIT2:

Hi!

I did ask and finally she says this should be the c code:

```<code>inf foo(void){
    char *string;//ebp-0x8
    unsigned int *pointerstring//[ebp-0x4]
    unsigned int *position;
    *position = *(pointerstring+0xc);
    unsigned char character;
    character=(unsigned char) string[*position];
    if ((character != 0x4)||(character != 0x4b))
    {
     *(position+0x4)=(unsigned int)(*position & 0x0f0f0f0f);
    }
    return(0);
}
</code>```

Does it have any sense at all for you?, could someone please explain this to me?
Does anyone really program like this?

Thanks very much!

答:
The x86 assembly language follows a long legacy and has mostly kept compatibility. We need to go back to the 8086/8088 chip where that story starts. These were 16 bit processors, which means that their register had a word size of 16 bits. The general purpose registers were named AX, BX, CX and DX. The 8086 had instructions to manipulate the upper and lower 8-bit parts of these registers that were then named AH, AL, BH, BL, CH, CL, DH and DL. This Wikipedia page describes this, please take a look.

The 32 bit versions of these registers have an E in front: EAX, EBX, ECX, etc.

The particular instruction you mention, e.g, cmp al,0x4f is comparing the lower byte of the AX register with 0x4f. The comparison is effectively the same as a subtraction, but does not save the result, only sets the flags.

For the 8086 instruction set, there is a nice reference here. Your program is 32 bit code, so you will need at least a 80386 instruction reference.

Body:
First of all, I am a student, I do not yet have extensive knowledge about C, C ++ and assembler, so I am making a extreme effort to understand it.

I have this piece of assembly code from an Intel x86-32 bit processor.

My goal is to transform it to source code.

0x80483dc :    push       ebp
0x80483dd :  mov        ebp,esp
0x80483df :  sub        esp,0x10
0x80483e2 :  mov        DWORD PTR [ebp-0x8],0x80484d0
0x80483e9 : lea        eax,[ebp-0x8]
0x80483ec : mov        DWORD PTR [ebp-0x4],eax
0x80483ef : mov        eax,DWORD PTR [ebp-0x4]
0x80483f2 : mov        edx,DWORD PTR [eax+0xc]
0x80483f5 : mov        eax,DWORD PTR [ebp-0x4]
0x80483f8 : movzx      eax,WORD PTR [eax+0x10]
0x80483fc : cwde
0x80483fd : add        edx, eax
0x80483ff : mov        eax,DWORD PTR [ebp-0x4]
0x8048402 : mov        DWORD PTR [eax+0xc],edx
0x8048405 : mov        eax,DWORD PTR [ebp-0x4]
0x8048408 : movzx      eax,BYTE PTR [eax]
0x804840b : cmp        al,0x4f
0x804840d : jne        0x8048419
0x804840f : mov        eax,DWORD PTR [ebp-0x4]
0x8048412 : movzx      eax,BYTE PTR [eax]
0x8048415 : cmp        al,0x4b
0x8048417 : je         0x804842d
0x8048419 : mov        eax,DWORD PTR [ebp-0x4]
0x804841c : mov        eax,DWORD PTR [eax+0xc]
0x804841f : mov        edx, eax
0x8048421 : and        edx,0xf0f0f0f
0x8048427 : mov        eax,DWORD PTR [ebp-0x4]
0x804842a : mov        DWORD PTR [eax+0x4],edx
0x804842d : mov        eax,0x0
0x8048432 : leave
0x8048433 : ret

This is what I understand from the code:

There are 4 variables:

a = [ebp-0x8] ebp
b = [ebp-0x4] eax
c = [eax + 0xc] edx
d = [eax + 0x10] eax

Values:

0x4 = 4
0x8 = 8
0xc = 12
0x10 = 16
0x4b = 75
0x4f = 79

Types:

char (8 bits) = 1 BYTE
short (16 bits) = WORD
int (32 bit) = DWORD
long (32 bits) = DWORD
long long (32 bit) = DWORD

This is what I was able to create:

#include <stdio.h>
int main (void)
{
   int a = 0x80484d0;
   int b
   short c;
   int d;

   c + b?
if (79 <= al) {
instructions
} else {
instructions
}

   return 0
}

But I'm stuck. Nor can I understand what the sentence "cmp al .." compares to, what is "al"?

How do these instructions work?

EDIT1:

That said, as you comment the assembly seems to be wrong or as someone comments say, it is insane!

The code and the exercise are from the following book called: "Reversing, Reverse Engineering" on page 140 (3.8 Proposed Exercises). It would never have occurred to me that it was wrong, if so, this clearly makes it difficult for me to learn ...

So it is not possible to do a reversing to get the source code because it is not a good assembly? Maybe I am not oppressed? Is it possible to optimize it?

EDIT2:

Hi!

I did ask and finally she says this should be the c code:

inf foo(void){
    char *string;//ebp-0x8
    unsigned int *pointerstring//[ebp-0x4]
    unsigned int *position;
    *position = *(pointerstring+0xc);
    unsigned char character;
    character=(unsigned char) string[*position];
    if ((character != 0x4)||(character != 0x4b))
    {
     *(position+0x4)=(unsigned int)(*position & 0x0f0f0f0f);
    }
    return(0);
}

Does it have any sense at all for you?, could someone please explain this to me?
Does anyone really program like this?

Thanks very much!


问:
How to train your own(w/o YOLO etc.) object detector in tf/keras
I successfully trained multi-classificator model, that was really easy with simple class related folder structure and keras.preprocessing.image.ImageDataGenerator with flow_from_directory (no one-hot encoding by hand btw!) after i just compile fit and evaluate - extremely well done pipeline by Keras!

BUT! when i decided to make my own (not cats, not dogs, not you_named) object detector - this is became a nightmare...

TFRecord and tf.Example are just madness! but ok, i almost get it (my dataset is small, i have plenty of ram, but who cares, write f. boilerplate, so much meh...)

The main thing - i just can't find any docs/tutorial how to make it with plain simple tf/keras, everyone just want to build up it on top of someone model, YOLO SSD FRCNN, even if they trying to detect completely new objects!!!

There two links about OD in official docs, and they both using some models underneath.

So my main question WHY ??? or i just blind..? -__-

答:
It becomes a nightmare because Object Detection is way way harder than classification. The most simple object detector is this: first train a classifier on all your objects. Then when you want to detect objects in your image, slide a window over your image, and classify each window. Then, if your classifier is certain that a certain window is one of the objects, mark it as a successful detection.

But this approach has a lot of problems, mainly it's way (like waaaay) too slow. So, researcher improved it and invented RCNNs. That had it problems, so they invented Faster-RCNN, YOLO and SSD, all to make it faster and more accurate.
You won't find any tutorials online on how to implement the sliding window technique because it's not useful anyway, and you won't find any tutorials on how to implement the more advanced stuff because, well, the networks get complicated pretty quick.

Also note that using YOLO doesn't mean you should use the same weights as in YOLO. You can always train YOLO from scratch on your own data if you want by  randomly initiliazing all the weights in the network layers. So the even if they trying to detect completely new objects!!! you mentioned isn't really valid. Also also note that I still would advise you to do use the weights they used in Yolo network. Transfer Learning is generally looked at as being a good idea, especially when starting out and especially in the image processing world, as many images share common features (like edges, for example).


问:
Splitting a long string on last whitespace or after max is exceeded
I am trying to split a long string into smaller chunks based on a line limit. Given the following as an example

This is a long header. It's long on purpose. It\'s purpose is to test that the splitting works correctly. It should be well over the line limit. If it is shorter then it would not test the limit.

If the line limit is 70 it should split into

This is a long header. It's long on purpose. It's purpose is to test

that the splitting works correctly. It should be well over the line

limit. If it is shorter then it would not test the limit.

The regular expression I came up with is as follows but it has a problem.

```<code>(\S*?.{1,70}(\s|\Z))
</code>```

https://regex101.com/r/Vr5QNZ/3/

If one word for some reason is too long it won't split because its only looking for whitespace. As an example, if I put the URL of this question in the string (removing the h in http so it actually displays)

ttps://stackoverflow.com/questions/7528045/large-string-split-into-lines-with-maximum-length-in-java
   remark This is a long header. It's long on purpose. It's purpose is to test
   remark that the splitting works correctly. It should be well over the line
   remark limit. If it is shorter then it would not test the limit.

the output would be

ttps://stackoverflow.com/questions/7528045/large-string-split-into-lines-with-maximum-length-in-java

This is a long header. It's long on purpose. It's purpose is to test

that the splitting works correctly. It should be well over the line

limit. If it is shorter then it would not test the limit.

That first line is well over the limit of 70 characters and since there is no whitespace to split on it just goes past the 70 characters. I would want it to split at a whitespace if there is one present before 70 characters are exhausted or if none are present, then split at the 70 character mark. The correct example would look something like

ttps://stackoverflow.com/questions/7528045/large-string-split-into-lin

es-with-maximum-length-in-java This is a long header. It's long on

purpose. It's purpose is to test that the splitting works

correctly. It should be well over the line limit. If it is

shorter then it would not test the limit.

答: Not sure if I understand the question, but does this fix your problem: (\S*?[^ ]{1,70}(\s|\Z|))</p>

Body:
I am trying to split a long string into smaller chunks based on a line limit. Given the following as an example

This is a long header. It's long on purpose. It\'s purpose is to test that the splitting works correctly. It should be well over the line limit. If it is shorter then it would not test the limit.

If the line limit is 70 it should split into

This is a long header. It's long on purpose. It's purpose is to test

that the splitting works correctly. It should be well over the line

limit. If it is shorter then it would not test the limit.

The regular expression I came up with is as follows but it has a problem.

(\S*?.{1,70}(\s|\Z))

https://regex101.com/r/Vr5QNZ/3/

If one word for some reason is too long it won't split because its only looking for whitespace. As an example, if I put the URL of this question in the string (removing the h in http so it actually displays)

ttps://stackoverflow.com/questions/7528045/large-string-split-into-lines-with-maximum-length-in-java
   remark This is a long header. It's long on purpose. It's purpose is to test
   remark that the splitting works correctly. It should be well over the line
   remark limit. If it is shorter then it would not test the limit.

the output would be

ttps://stackoverflow.com/questions/7528045/large-string-split-into-lines-with-maximum-length-in-java

This is a long header. It's long on purpose. It's purpose is to test

that the splitting works correctly. It should be well over the line

limit. If it is shorter then it would not test the limit.

That first line is well over the limit of 70 characters and since there is no whitespace to split on it just goes past the 70 characters. I would want it to split at a whitespace if there is one present before 70 characters are exhausted or if none are present, then split at the 70 character mark. The correct example would look something like

ttps://stackoverflow.com/questions/7528045/large-string-split-into-lin

es-with-maximum-length-in-java This is a long header. It's long on

purpose. It's purpose is to test that the splitting works

correctly. It should be well over the line limit. If it is

shorter then it would not test the limit.


问:
check if database exits in union sql server
i want to union query from multiple database. but before union i want to check if database exits then union, if second database exits then union and so on...

```<code>IF EXISTS(SELECT * FROM sys.sysdatabases where name='FirstDB')
select * from FirstDB.dbo.tablename
union
IF EXISTS(SELECT * FROM sys.sysdatabases where name='SecondDB')
select * from SecondDB.dbo.tablename.
</code>```

How to do that.
Thanks in advance.

答:
If a database is missing (don't quite understand) the batch will not compile therefore the code will not run. This means any tests for database existence will fail.

Assuming you really have databases appearing and disappearing randomly, the only "practical" option is dynamic SQL

```<code>...
IF DB_ID('FirstDB') IS NOT NULL
   SET @sql ='select * from FirstDB.dbo.tablename'

IF DB_ID('SecondDB') IS NOT NULL
   SET @sql =  @sql + CASE WHEN @sql = '' THEN '' ELSE 'union ' END +
                      'select * from SecondDB.dbo.tablename'
...
</code>```

Body:
i want to union query from multiple database. but before union i want to check if database exits then union, if second database exits then union and so on...

IF EXISTS(SELECT * FROM sys.sysdatabases where name='FirstDB')
select * from FirstDB.dbo.tablename
union
IF EXISTS(SELECT * FROM sys.sysdatabases where name='SecondDB')
select * from SecondDB.dbo.tablename.

How to do that.
Thanks in advance.

Body:
If a database is missing (don't quite understand) the batch will not compile therefore the code will not run. This means any tests for database existence will fail.

Assuming you really have databases appearing and disappearing randomly, the only "practical" option is dynamic SQL

...
IF DB_ID('FirstDB') IS NOT NULL
   SET @sql ='select * from FirstDB.dbo.tablename'

IF DB_ID('SecondDB') IS NOT NULL
   SET @sql =  @sql + CASE WHEN @sql = '' THEN '' ELSE 'union ' END +
                      'select * from SecondDB.dbo.tablename'
...


问:
Keras Library OR shall i choose neural network from Scratch
I am new to deep learning.

We already have good libraries like Keras etc., to develop neural network application.

To develop deep learning models (apart from Keras) shall I also need to learn more about
 neural network layer development from scratch.

Following link is an example showing how to develop deep learning models from scratch. I am just assuming we can use Keras or other libraies to finish the task. Do we still need to learn this neural network from scratch to develop deep leaning models. Could you kindly tell something on this.

https://medium.com/from-the-scratch/deep-learning-deep-guide-for-all-your-matrix-dimensions-and-calculations-415012de1568

答:
If you are a beginner, I would rather suggest you to make neural networks from scratch and understand the basics of neural networks. You can use at the most numpy and pandas for this. In this way, you will learn the whereabouts of NN and won't mess up when you switch to DL frameworks.

It is not much difficult to make neural networks from scratch without any DL libraries.

After gaining significant knowledge about NN, you may then go for keras and other deep learning frameworks.

For any new skill always follow the path, basics -> practice -> intermediate -> advanced


问:
How to check the occurrence of the words in the SQL of a sentence using PHP and html
I'm getting a sentence from user input then chopping it into words and listing them in a array.

After that I want to pass this array depending on number of words in the sentence to a SQL query which will check for the occurrence of each word separately and return then number.

The first part is done by using regex:

```<code>preg_match_all('/<[^>]++>|[^<>\s]++/', $sent, $tokens);
print_r($tokens);
</code>```

The output is like this:

But for the SQL query loop I'm stuck.  I don't know where to start with my database table is like this:

And my expected output is something like:

P.S.:- I think the PHP code should know the length of the user input sentence first, then tokenize it to pass the words to the SQL loop  query to be searched separately.

答:
```<code>$words = array();
while (...) {
    $word = ...;  // extract the word
    $words[] = "'$word'";
}
$in_list = implode(', ', $words);  //  'hi', 'how', 'are', 'you'
$sql = "SELECT  word,
                COUNT(*) as freq   -- COUNT(*) is the common syntax
            FROM tbl_words
            WHERE word IN ($in_list)";
... $sql ...   // perform the query and deal with the results
</code>```

To do the update, generate this and execute:

```<code>$sql = "UPDATE tbl_words
            SET freq = freq + 1
            WHERE word IN ($in_list)";
</code>```

If a sentence can have a word twice, do you want the table to incremented twice?  Whether or not you want that, I might build a hash instead of an array:

```<code>$words = array();
while (...) {
    $word = ...;  // extract the word
    $words[$word] = (isset($words[$word]) ? $words[$word] + 1 : 1);
}
$in_list = implode(', ', array_keys($words));  //  'hi', 'how', 'are', 'you'
</code>```

That assumes multiple copies of a word count as only 1.

For the incrementing by the repeated count, things get messier.

Based on your parsing code:

```<code>$words = array();
preg_match_all('/<[^>]++>|[^<>\s]++/', $sent, $tokens);
foreach($tokens as $token) {
    $words[$word] = (isset($words[$word]) ? $words[$word] + 1 : 1);
}
$in_list = implode(', ', array_keys($words));
echo $in_list;
</code>```

Body:
I'm getting a sentence from user input then chopping it into words and listing them in a array.

After that I want to pass this array depending on number of words in the sentence to a SQL query which will check for the occurrence of each word separately and return then number.

The first part is done by using regex:

preg_match_all('/<[^>]++>|[^<>\s]++/', $sent, $tokens);
print_r($tokens);

The output is like this:

But for the SQL query loop I'm stuck.  I don't know where to start with my database table is like this:

And my expected output is something like:

P.S.:- I think the PHP code should know the length of the user input sentence first, then tokenize it to pass the words to the SQL loop  query to be searched separately.

Body:
$words = array();
while (...) {
    $word = ...;  // extract the word
    $words[] = "'$word'";
}
$in_list = implode(', ', $words);  //  'hi', 'how', 'are', 'you'
$sql = "SELECT  word,
                COUNT(*) as freq   -- COUNT(*) is the common syntax
            FROM tbl_words
            WHERE word IN ($in_list)";
... $sql ...   // perform the query and deal with the results

To do the update, generate this and execute:

$sql = "UPDATE tbl_words
            SET freq = freq + 1
            WHERE word IN ($in_list)";

If a sentence can have a word twice, do you want the table to incremented twice?  Whether or not you want that, I might build a hash instead of an array:

$words = array();
while (...) {
    $word = ...;  // extract the word
    $words[$word] = (isset($words[$word]) ? $words[$word] + 1 : 1);
}
$in_list = implode(', ', array_keys($words));  //  'hi', 'how', 'are', 'you'

That assumes multiple copies of a word count as only 1.

For the incrementing by the repeated count, things get messier.

Based on your parsing code:

$words = array();
preg_match_all('/<[^>]++>|[^<>\s]++/', $sent, $tokens);
foreach($tokens as $token) {
    $words[$word] = (isset($words[$word]) ? $words[$word] + 1 : 1);
}
$in_list = implode(', ', array_keys($words));
echo $in_list;


问:
missing arguments message in discord
so i was making an help command with different help menu's. Like mee6 has. but i want to add an message for as there are no arguments given. How to do that? This is waht i have now:</p>

```<code>@bot.command(name='help')
async def help(ctx, *, content):
    if content == ('Moderation'):
        await ctx.send(moderationmenu)
    if content == ('fun'):
        await ctx.send(funmenu)
    if content == None:
        await ctx.send('please provide an argument (Moderation / fun)')
</code>```

答:
You're able to provide default arg values like so:

@bot.command(name="help")
async def help(ctx, *, content = None):
    if not content: # more pythonic way of checking a variable is None or not
        await ctx.send("Please provide an argument (moderation / fun)")
    elif content.lower() == "fun": # brackets not necessary
        await ctx.send(funmenu)
    elif content.lower() == "moderation": # makes it case insensitive
        await ctx.send(moderationmenu)
    else:
        await ctx.send("Sorry, I didn't recognise that category. Please choose (moderation / fun)")
```

<p>A quick edit - if you have your menus sorted out into separate variables, you can map them in a dict:</p>

<pre class="lang-py prettyprint-override"><code>@bot.command(name="help")
async def help(ctx, *, content = None):
    menus = {"fun": funmenu, "moderation": moderationmenu}
    if not content:
        await ctx.send("Please provide an argument (moderation / fun)")
    else:
        try:
            await ctx.send(menus[content.lower()])
        except KeyError:
            await ctx.send("Sorry, I didn't recognise that category. Please choose (moderation / fun)")
</code>```

References:

Default args

Title: missing arguments message in discord

Body:
so i was making an help command with different help menu's. Like mee6 has. but i want to add an message for as there are no arguments given. How to do that? This is waht i have now:

@bot.command(name='help')
async def help(ctx, *, content):
    if content == ('Moderation'):
        await ctx.send(moderationmenu)
    if content == ('fun'):
        await ctx.send(funmenu)
    if content == None:
        await ctx.send('please provide an argument (Moderation / fun)')

Body:
You're able to provide default arg values like so:

@bot.command(name="help")
async def help(ctx, *, content = None):
    if not content: # more pythonic way of checking a variable is None or not
        await ctx.send("Please provide an argument (moderation / fun)")
    elif content.lower() == "fun": # brackets not necessary
        await ctx.send(funmenu)
    elif content.lower() == "moderation": # makes it case insensitive
        await ctx.send(moderationmenu)
    else:
        await ctx.send("Sorry, I didn't recognise that category. Please choose (moderation / fun)")

A quick edit - if you have your menus sorted out into separate variables, you can map them in a dict:

@bot.command(name="help")
async def help(ctx, *, content = None):
    menus = {"fun": funmenu, "moderation": moderationmenu}
    if not content:
        await ctx.send("Please provide an argument (moderation / fun)")
    else:
        try:
            await ctx.send(menus[content.lower()])
        except KeyError:
            await ctx.send("Sorry, I didn't recognise that category. Please choose (moderation / fun)")

References:

Default args


问:
IDisposable - automated check for using construct
Does anybody know of a way to automatically find any variable, where the type implements IDisposable but the using construct is not used?

ie. a way to check for potentially unreleased unmanaged resources?

Also, is it possible to see the number and types of resource held by a running application?

答:
VS 2010 code analyzer's and FxCop? (not sure) Reliability Rules will do a pretty good job on detecting if there exists execution paths in the analyized code where objects implementing IDisposable are going out of scope without calling Dispsoe() (it is overeager and will in many ocasions detect false positives).

This will of course not enforce the using construct as a correctly implemented try-finally block will pass the test (both are obviously equivalent under the hood, so I'm not sure if thats an issue).

EDIT: FX Cop does not support this warning. Its availabe since VS 2005 code analyzer.


答:
Some commands are built into the shell, so they don't need to fork. All the commands that implement control flow (e.g. if, while, case) have to be built in. So do the commands that change the shell process's state, such as cd and ulimit.

In addition, a number of simple commands are implemented as shell built-ins; these include echo and printf. So you won't see any forks in the first script with two echo commands.

The type command (itself a built-in) can be used to show which commands are built-ins. For example, type echo reports echo is a shell builtin, but type cat reports cat is /bin/cat.

Finally, the exit status of a script is the same as the exit status of the last command. So as an optimization, it doesn't fork for the last command, it simply execs it. That's why you see forks when the script has two cat commands, but not when there's only one.

Title: Do exec() calls fork for each command if passed a shell script?


问:
Allow Visual Studio for Mac permission to use the Desktop?
When opening a Visuals Studio solution on a Mac I got a popup asking me to give VS permission to use the Desktop. I accidentally clicked don't allow and now can't load the solution.

I tried looking under preferences but couldn't find how to allow it. I also tried closing and reopening the solution, but to no avail.

答:
```<code>System Preferences --> Security & Privacy --> Privacy tab --> Files & Folders
-> Grant VS permisions
</code>```

OR... just move your solution to another folder

Body:
System Preferences --> Security & Privacy --> Privacy tab --> Files & Folders
-> Grant VS permisions

OR... just move your solution to another folder


答:
I believe the event does fire, the problem is you have misused the content css property.
Check the following link from W3Schools. The content css property is meant to be used with the ::before and ::after pseudo elements. There is a example showing how it should be used: https://jsfiddle.net/vno85egh/.

```<code>.checkmark::after {
   content: url(path/to/asset);
}
</code>```

Although in your case it seems to me you can simply set the body inner html:

```<code>document.body.innerHtml = "<img src=...>"
</code>```

Hope this was somewhat helpful :).

Title: Firing off event listeners and CSS classes in the same condition

Body:
In the following code block in JS, I would like to hide/show a button depending on the validity of input fields in a form. When the .confirm button is clicked and the form is valid, I would like to fire off an event listener on the latter button to add a checkmark.

However, only the first two lines of code are firing off but the event listener is not. Any suggestions on how I could add/remove buttons and upon the same condition make the checkmark appear on the body?

if (form.checkValidity()) {
 document.querySelector(".formSubmit").classList.add("formSubmitShow");
 document.querySelector(".confirm").classList.add("confirmHide");
 document.querySelector(".confirm").addEventListener("click", (e)=>{
         body.classList.add("checkmark");
        });
      } else {
        formElements.forEach((el) => {
          if (!el.checkValidity()) {
            el.classList.add("invalid");
          }
        });
      }

.checkmark {
  content: url(static/gifs/check.gif);
}

Body:
I believe the event does fire, the problem is you have misused the content css property.
Check the following link from W3Schools. The content css property is meant to be used with the ::before and ::after pseudo elements. There is a example showing how it should be used: https://jsfiddle.net/vno85egh/.

.checkmark::after {
   content: url(path/to/asset);
}

Although in your case it seems to me you can simply set the body inner html:

document.body.innerHtml = "<img src=...>"

Hope this was somewhat helpful :).


问:
Angular - Display message on specific item in a Loop
I have a list of rows using For Loop. Clicking on any row, pops up a modal window. The modal window contains a Cancel and Ok button. When clicked on OK button, a message should appear on the ROW which was clicked.
Currently I can get the index number of the row and the message is showing on ALL rows when clicked OK. How can I display the message only on that specific ROW.

```<code><div class="row" *ngFor="let item of items; let i = index">
</code>```

```<code><div class="row">
    <div class="col-2">
        <span (click)="showModalWindow">
            <img class="actionIcon" src="images/action.png" />
        </span>
    </div>
    <div class="col-4">
        <div class="ietm-img" *ngIf="item.image">
            <img [src]="item.image" alt="item" />
        </div>
    </div>
    <div class="col-6">
        <div class="text">
            <h6>{{item.name}}</h6>
            <p>MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW</p>
            <span>{{item.measurement}} {{item.length}}</span>
        </div>
    </div>
</div>
</code>```

答:
I believe there are multiple ways to do it. One way would be to introduce an additional boolean property (eg. clicked) in the items array of objects.

```<code>items = [
  {
    'name': 'sample',
    'measurement': 'sample',
    'clicked': false,
    ...
  },
  ...
]
</code>```

And set that property to true when the OK button is clicked in the modal. Now you could check this property using *ngIf in the template to display the message.

Template

{{item.name}}

    <ng-container *ngIf="item.clicked">

MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW

    </ng-container>
    {{item.measurement}} {{item.length}}

```
<h3>Update: add <code>clicked</code> property</h3>
<p>You could introduce the <code>clicked</code> property to the data obtained from the API before assigning it to the <code>items</code> variable.</p>
<pre class="lang-js prettyprint-override"><code>this.apiService.getItems().pipe(
  map(items => items.map(item => ({ ...item, clicked: false });
).subscribe(
  items => { this.items = items },
  error => { }
);
</code>```

Now there is property called clicked in each object of the array. Set it to false if an object is opened in the template and the OK button is clicked in the modal.

Body:
I have a list of rows using For Loop. Clicking on any row, pops up a modal window. The modal window contains a Cancel and Ok button. When clicked on OK button, a message should appear on the ROW which was clicked.
Currently I can get the index number of the row and the message is showing on ALL rows when clicked OK. How can I display the message only on that specific ROW.

{{item.name}}

MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW

            {{item.measurement}} {{item.length}}

Body:
I believe there are multiple ways to do it. One way would be to introduce an additional boolean property (eg. clicked) in the items array of objects.

items = [
  {
    'name': 'sample',
    'measurement': 'sample',
    'clicked': false,
    ...
  },
  ...
]

And set that property to true when the OK button is clicked in the modal. Now you could check this property using *ngIf in the template to display the message.

Template

<div class="col-6">
  <div class="text">
    <h6>{{item.name}}</h6>
    <ng-container *ngIf="item.clicked">      <!-- check condition -->
      <p>MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW</p>
    </ng-container>
    <span>{{item.measurement}} {{item.length}}</span>
  </div>
</div>

Update: add clicked property

You could introduce the clicked property to the data obtained from the API before assigning it to the items variable.

this.apiService.getItems().pipe(
  map(items => items.map(item => ({ ...item, clicked: false });
).subscribe(
  items => { this.items = items },
  error => { }
);

Now there is property called clicked in each object of the array. Set it to false if an object is opened in the template and the OK button is clicked in the modal.


问:
add LineOfSight custom widget into appbuilder 2.16 for esri ArcGIS (Developer Edition)
I'm new to this area. I succeeded in adding 2d ListView widget by following esri tutorials, but will appreciate some help in adding the 3d LineOfSight custom widget into appbuilder 2.16 for esri ArcGIS (Developer Edition)</p>

答: I succeeded to do it right by properly attaching the LineOfSight to the htmnl.</p>


答:
The way I was able to do it was by starting the count from 0 so that the brackets would be accurate:  </p>

```<code>with cte as
(select CASE WHEN rn=0 then 1
when rn%10=0 then 1
else 0 end chk,x.*
from
(
select ROW_NUMBER() over (partition by fk order by fk,from)-1 rn,* from dbo.Thous_Data
)x

)
,cte2 as(
SELECT
      distinct fk,to,from,
       SUM([Chk]) OVER (PARTITION BY  fk ORDER BY  to,from) AS Groups

    FROM cte

)

    Select distinct fk,
        Min(from) over (partition by fk,groups) from_
,Max(to) over (partition by fk,groups) to_
,avg(speed) over (partition by fk,groups) Aspeed
,avg(score) over (partition by fk,groups) Ascore

from
cte2
</code>```

Title: Converting Data to Tenths and averaging values

Body:
so I have a table in thousandths of a mile like this:

id |fk |from  |to    |speed|score
1  |123|10.002|10.003|20   |10
2  |123|10.003|10.004|25   |11
3  |123|10.004|10.005|40   |44
4  |123|10.005|10.006|50   |23
5  |123|10.006|10.007|20   |54
6  |123|10.007|10.008|10   |24
7  |123|10.008|10.009|65   |24
8  |123|10.009|10.010|23   |24
9  |123|10.010|10.011|74   |56
10 |123|10.011|10.012|25   |43
11 |123|10.012|10.013|10   |76
12 |123|10.013|10.014|5    |10
...

I need to convert the thousandth mile table to tenths of a mile and take average of speed and score like this:

id |fk |from  |to    |Avgspeed|Avgscore
1  |123|10.002|10.012|35.2    |31.3
10 |123|10.012|...   |...     |...

I came up with this query to get the tenth of a mile:

select CASE WHEN rn=1 then 1
when rn%10=0 then 1
else 0 end chk,x.* from
(
select row_number() over (partition by fk order by fk,from) rn,* from dbo.Thous_Data
)x

This gives me

id |fk |from  |to    |speed|score|chk|rn
1  |123|10.002|10.003|20   |10   |1  |1
2  |123|10.003|10.004|25   |11   |0  |2
3  |123|10.004|10.005|40   |44   |0  |3
4  |123|10.005|10.006|50   |23   |0  |4
5  |123|10.006|10.007|20   |54   |0  |5
6  |123|10.007|10.008|10   |24   |0  |6
7  |123|10.008|10.009|65   |24   |0  |7
8  |123|10.009|10.010|23   |24   |0  |8
9  |123|10.010|10.011|74   |56   |0  |9
10 |123|10.011|10.012|25   |43   |1  |10
11 |123|10.012|10.013|10   |76   |0  |11
12 |123|10.013|10.014|5    |10   |0  |12
...

Not sure how to proceed with getting the averages and setting up the from and to correctly. Any ideas appreciated.

Body:
The way I was able to do it was by starting the count from 0 so that the brackets would be accurate:

with cte as
(select CASE WHEN rn=0 then 1
when rn%10=0 then 1
else 0 end chk,x.*
from
(
select ROW_NUMBER() over (partition by fk order by fk,from)-1 rn,* from dbo.Thous_Data
)x

)
,cte2 as(
SELECT
      distinct fk,to,from,
       SUM([Chk]) OVER (PARTITION BY  fk ORDER BY  to,from) AS Groups

    FROM cte

)

    Select distinct fk,
        Min(from) over (partition by fk,groups) from_
,Max(to) over (partition by fk,groups) to_
,avg(speed) over (partition by fk,groups) Aspeed
,avg(score) over (partition by fk,groups) Ascore

from
cte2


问:
Implementing infinite wait in shell scripting
This may sound trivial, but I'm pretty sure this question hasn't been asked, or at least I can't find it.

I'm looking for a way to construct an infinite wait (not necessarily a loop) with shell scripting so that it waits forever and can be killed (or technically, to receive a SIGTERM). The following are known possible constructs and arguments against them:

while true; do sleep 1; done This almost gets it, but since sleep is an external command, when I send a SIGTERM to the running script, it has to wait for the sleep to finish first and then process the signal. Change sleep 1 to something like sleep 10 and the lag will be obvious. Also the solution wakes up the CPU every 1 second, which is not ideal.

while true; do read; done This is perfect when stdin is tty. read is a shell builtin and SIGTERM arrives at the script instantly. But, when stdin is /dev/null, the script eats up all the CPU by helplessly running read forever on /dev/null.

Thus a shell builtin construct that waits forever is required. Skimming through man dash I didn't find such one - the only blocking builtins are read and wait, and I don't have idea how I can construct an ideal one using wait.

The answer should be applicable to POSIX shell (effectively dash), or less preferably, Bash.

Additional notes.

The situation where the first example doesn't work perfectly is more complex than I thought. With the following shell script:

```<code>#!/bin/sh
echo $$
while true; do
    sleep 100
done
</code>```

if you kill it at another tty, it terminates immediately. The funny thing begins when you attempt to do trapping. With this script:

```<code>#!/bin/sh
at_term() {
    echo 'Terminated.'
    exit 0
}
trap at_term TERM
echo $$
while true; do
    sleep 20
done
</code>```

What happens is exactly described in example 1. This happens with bash, dash and zsh. And it's under this condition that I'm seeking a "perfect" infinite look construct.

答: Why do not you use sleep forever? This is designed to forever block.

Body:
This may sound trivial, but I'm pretty sure this question hasn't been asked, or at least I can't find it.

I'm looking for a way to construct an infinite wait (not necessarily a loop) with shell scripting so that it waits forever and can be killed (or technically, to receive a SIGTERM). The following are known possible constructs and arguments against them:

while true; do sleep 1; done This almost gets it, but since sleep is an external command, when I send a SIGTERM to the running script, it has to wait for the sleep to finish first and then process the signal. Change sleep 1 to something like sleep 10 and the lag will be obvious. Also the solution wakes up the CPU every 1 second, which is not ideal.

while true; do read; done This is perfect when stdin is tty. read is a shell builtin and SIGTERM arrives at the script instantly. But, when stdin is /dev/null, the script eats up all the CPU by helplessly running read forever on /dev/null.

Thus a shell builtin construct that waits forever is required. Skimming through man dash I didn't find such one - the only blocking builtins are read and wait, and I don't have idea how I can construct an ideal one using wait.

The answer should be applicable to POSIX shell (effectively dash), or less preferably, Bash.

Additional notes.

The situation where the first example doesn't work perfectly is more complex than I thought. With the following shell script:

#!/bin/sh
echo $$
while true; do
    sleep 100
done

if you kill it at another tty, it terminates immediately. The funny thing begins when you attempt to do trapping. With this script:

#!/bin/sh
at_term() {
    echo 'Terminated.'
    exit 0
}
trap at_term TERM
echo $$
while true; do
    sleep 20
done

What happens is exactly described in example 1. This happens with bash, dash and zsh. And it's under this condition that I'm seeking a "perfect" infinite look construct.


问:
Scrolling Colorbox in IE
I'm using ColorBox's  Ajax mode.

```<code><a class='data-content' href='data/<?=$id?>'> <img src=uploads/thumb_<?=$img?> /> </a>

     <script type="text/javascript">

      $(document).ready(function(){

        $(".data-content").colorbox({
              transition: "none",
              title: false,
              width: "700px",
              top: "10px",
              loop: false,
              scrolling: false
        });

      });

     </script>
</code>```

After clicking on photo thumb it loads colorbox with photo and other content. Usually it's height is larger than screen. So scrollbars appear. With other browsers (Mozilla, Chrome) I can scroll up and down and see all content in box with no problems.

When scrolling with IE8 colorbox stays in the same place and instead that background scrolls. So I can't see all content.

Here is an example. Actually it's the default Colorbox example.

Any ideas on what may be causing the problem?

答:
It could be this... from the site - http://colorpowered.com/colorbox/#doctype

ColorBox requires a valid doctype and
  rendering in quirks mode is not
  supported. If you aren't using the
  HTML5 doctype, make sure you are using
  the full doctype declaration (with
  URI) to insure rendering in standards
  mode.

Unfortunately, this abbreviated
  doctype renders the document in quirks
  mode for Internet Explorer:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
</code>```

The doctype with URI renders in
  standards mode for all browsers:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
</code>```

Title: Scrolling Colorbox in IE

Body:
I'm using ColorBox's  Ajax mode.

<a class='data-content' href='data/<?=$id?>'> <img src=uploads/thumb_<?=$img?> />

After clicking on photo thumb it loads colorbox with photo and other content. Usually it's height is larger than screen. So scrollbars appear. With other browsers (Mozilla, Chrome) I can scroll up and down and see all content in box with no problems.

When scrolling with IE8 colorbox stays in the same place and instead that background scrolls. So I can't see all content.

Here is an example. Actually it's the default Colorbox example.

Any ideas on what may be causing the problem?

Body:
It could be this... from the site - http://colorpowered.com/colorbox/#doctype

ColorBox requires a valid doctype and
  rendering in quirks mode is not
  supported. If you aren't using the
  HTML5 doctype, make sure you are using
  the full doctype declaration (with
  URI) to insure rendering in standards
  mode.

Unfortunately, this abbreviated
  doctype renders the document in quirks
  mode for Internet Explorer:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

The doctype with URI renders in
  standards mode for all browsers:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">


问:
Why my React app is not loading correctly (broken) in localhost?
I had my react project working correctly in localhost. Then, I decided to deploy it to github pages and it worked perfectly on the server too. Now, I'm trying to work on it again on localhost but it is not showing correctly. For some reason, photos are not loading and some css is not working correctly and after compile it in PowerShell says this:

```<code>Compiled successfully!

You can now view myportfolio in the browser.

Local: http://localhost:3000/myportfolio

On Your Network: http://192.168.56.1:3000/myportfolio

Note that the development build is not optimized.

To create a production build, use npm run build.
</code>```

So if I go to my GitHub pages it is loading correctly but not in localhost (running npm start).

Any suggestion? Thank you in advance and let me know if you need more clarification

答:
I did clone your repositories and found these problems:

You have been directly imported many third-party js given their relative path in the index.html. That doesn't work. You should append %PUBLIC_URL% before them. For e.g.

 and similary for other script files.

But even this is not the best that you can do. You must not try to use jquery or third party js in a React App. Also, make it a part to install the related JS though npm and make them a part of the package.

You'll have to use <img src={require('/public/images/background.png')}... (Btw, the image name on your gh-pages is different. It's logo.png there)if you want the webpack to compile and make it a part of your project. Also, the path must reside within src and not public folder.

Other errors are are related to keys. Whenever you're mapping and iterating through a list in react you must specify a unique key.

Body:
I had my react project working correctly in localhost. Then, I decided to deploy it to github pages and it worked perfectly on the server too. Now, I'm trying to work on it again on localhost but it is not showing correctly. For some reason, photos are not loading and some css is not working correctly and after compile it in PowerShell says this:

Compiled successfully!

You can now view myportfolio in the browser.

Local: http://localhost:3000/myportfolio

On Your Network: http://192.168.56.1:3000/myportfolio

Note that the development build is not optimized.

To create a production build, use npm run build.

So if I go to my GitHub pages it is loading correctly but not in localhost (running npm start).

Any suggestion? Thank you in advance and let me know if you need more clarification

Body:
I did clone your repositories and found these problems:

You have been directly imported many third-party js given their relative path in the index.html. That doesn't work. You should append %PUBLIC_URL% before them. For e.g.

<script src="%PUBLIC_URL%/js/jquery.flexslider.js"></script> and similary for other script files.

But even this is not the best that you can do. You must not try to use jquery or third party js in a React App. Also, make it a part to install the related JS though npm and make them a part of the package.

You'll have to use <img src={require('/public/images/background.png')}... (Btw, the image name on your gh-pages is different. It's logo.png there)if you want the webpack to compile and make it a part of your project. Also, the path must reside within src and not public folder.

Other errors are are related to keys. Whenever you're mapping and iterating through a list in react you must specify a unique key.


问:
Using only CSS, is there a way to change a specific image's color to white on black?
I use CSS to create dark theme versions of some popular websites.

One of the issues I run into is images like these:

https://www.gstatic.com/images/icons/material/system/1x/reply_black_20dp.png

https://www.gstatic.com/images/icons/material/system/1x/more_vert_black_20dp.png

Sites use background-image to display these images.

When I apply filter: invert(1) to these images, I get a white-on-white image in Firefox.

Is there a way, using only CSS, to make these images display as white on black?  It doesn't matter to me if you use filter or another technique.

答:
Simply apply a white background and then do your filter:

img {
  background: #fff;
  filter: invert(1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://i.stack.imgur.com/ZLpPT.png"></code>```

And with background:

img {
  background: #fff;
}
.box {
  background:
   url(https://i.stack.imgur.com/ZLpPT.png) 0 0/20px 20px no-repeat,
   #fff;
  width:100px;
  height:100px;
  filter: invert(1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code>```

Body:
Simply apply a white background and then do your filter:

img {
  background: #fff;
  filter: invert(1);
}

<img src="https://i.stack.imgur.com/ZLpPT.png">

And with background:

img {
  background: #fff;
}
.box {
  background:
   url(https://i.stack.imgur.com/ZLpPT.png) 0 0/20px 20px no-repeat,
   #fff;
  width:100px;
  height:100px;
  filter: invert(1);
}

<div class="box"></div>


问:
How to connect output layers to the input layer of another neural network?
The Actor-network has 5 input neurons representing the state values and will produce one output value held by one output neuron.

The Q Network has 6 input neurons: 5 representing the state values and 1 representing the output of Actor-network.

I'll do gradient descent to train the Actor-network seperately, holding Q network's weights as constant.

My question is:
How should I structure to plug the output layer of Actor-Network into the input layer of the Q network, with TensorFlow 2.x?

答:
You can just use the ŧf.keras.Model API:

```<code>actor_model = tf.keras.Model(inputs=...,outputs=...)
Q_model = tf.keras.Model(inputs=actor_model.outputs, outputs=...)
</code>```

Body:
You can just use the ŧf.keras.Model API:

actor_model = tf.keras.Model(inputs=...,outputs=...)
Q_model = tf.keras.Model(inputs=actor_model.outputs, outputs=...)


问:
How to split single rows into multiple rows depending on whether one field contains comma separated string in oracle sql?
I have created a function get_depatment_names which returns comma separated values in the single Return Value.
The output of function is : Sales,Retail,Electronic.

Another function get_location_names returns the same way for the location. Output: West York,Shire,Lancas

Now, these two functions , I'm calling in my select statement along with other columns.

```<code>SELECT dept_id,
       date,
       get_department_names dept_name,
       get_location_names location
       status
FROM   department
WHERE dept_id = 1;
</code>```

Output is displayed as below:

dept_id ---date               ----dept_name -------location----- status

1            ---01/01/2018 --- Sales,Retail,Electronic ---West York,Shire,Lancas-- Active

Expected output:

1--01/01/2018 --- Sales      --- West York--  Active

1--01/01/2018 --- Retail     --- Shire -- Active

1--01/01/2018 --- Electronic ---Lancas --Active

I tried using the regexp_sub with connect in the select stmt as below but is giving an error of "single row subquery returns more than one row".

```<code>SELECT dept_id,
       date,
       (select regexp_substr(get_department_names(id),'[^,]+',1,level) from dual
        connect by regexp_substr(get_department_names(id),'[^,]+',1,level) is not null)  dept_name,
       (select regexp_substr(get_location_names (id),'[^,]+',1,level) from dual
        connect by regexp_substr(get_location_names(id),'[^,]+',1,level) is not null) location
       status
FROM   department
WHERE dept_id = 1;
</code>```

Please let me know how to correct this.

答:
That would be something like this (lines #1 - 4 represent sample data; query you need begins at line #5):</p>

```<code>SQL> with department (dept_id, datum, dept_name, location, status) as
  2    (select 1, date '2018-01-01', 'sales,retail,electronic',
  3      'West York,Shire,Lancas', 'active' from dual
  4    )
  5  select dept_id,
  6    datum,
  7    regexp_substr(dept_name, '[^,]+', 1, level) dept_name,
  8    regexp_substr(location , '[^,]+', 1, level) location,
  9    status
 10  from department
 11  where dept_id = 1
 12  connect by level <= regexp_count(dept_name, ',') + 1;

   DEPT_ID DATUM      DEPT_NAME       LOCATION        STATUS
---------- ---------- --------------- --------------- ------
         1 01/01/2018 sales           West York       active
         1 01/01/2018 retail          Shire           active
         1 01/01/2018 electronic      Lancas          active

SQL>
</code>```

Body:
I have created a function get_depatment_names which returns comma separated values in the single Return Value.
The output of function is : Sales,Retail,Electronic.

Another function get_location_names returns the same way for the location. Output: West York,Shire,Lancas

Now, these two functions , I'm calling in my select statement along with other columns.

SELECT dept_id,
       date,
       get_department_names dept_name,
       get_location_names location
       status
FROM   department
WHERE dept_id = 1;

Output is displayed as below:

dept_id ---date               ----dept_name -------location----- status

1            ---01/01/2018 --- Sales,Retail,Electronic ---West York,Shire,Lancas-- Active

Expected output:

1--01/01/2018 --- Sales      --- West York--  Active

1--01/01/2018 --- Retail     --- Shire -- Active

1--01/01/2018 --- Electronic ---Lancas --Active

I tried using the regexp_sub with connect in the select stmt as below but is giving an error of "single row subquery returns more than one row".

SELECT dept_id,
       date,
       (select regexp_substr(get_department_names(id),'[^,]+',1,level) from dual
        connect by regexp_substr(get_department_names(id),'[^,]+',1,level) is not null)  dept_name,
       (select regexp_substr(get_location_names (id),'[^,]+',1,level) from dual
        connect by regexp_substr(get_location_names(id),'[^,]+',1,level) is not null) location
       status
FROM   department
WHERE dept_id = 1;

Please let me know how to correct this.

Body:
That would be something like this (lines #1 - 4 represent sample data; query you need begins at line #5):

SQL> with department (dept_id, datum, dept_name, location, status) as
  2    (select 1, date '2018-01-01', 'sales,retail,electronic',
  3      'West York,Shire,Lancas', 'active' from dual
  4    )
  5  select dept_id,
  6    datum,
  7    regexp_substr(dept_name, '[^,]+', 1, level) dept_name,
  8    regexp_substr(location , '[^,]+', 1, level) location,
  9    status
 10  from department
 11  where dept_id = 1
 12  connect by level <= regexp_count(dept_name, ',') + 1;

   DEPT_ID DATUM      DEPT_NAME       LOCATION        STATUS
---------- ---------- --------------- --------------- ------
         1 01/01/2018 sales           West York       active
         1 01/01/2018 retail          Shire           active
         1 01/01/2018 electronic      Lancas          active

SQL>