问:
Execute system command in x64 bit assembly?
I recently been trying to execute system commands using pure assembly. I managed to achieve it in a x32 bit binary as posted here: execute system command (bash) using assembly?

But Now I am trying to integrate that same procedure to a x64 bit binary. I might be very bad at art of googling but I couldn't find any article showing how to execute system commands in x64 bit.

Precisely said, below is what I did:

```<code>SECTION .data
SECTION .text
global main
main:
xor rax, rax
xor rdx, rdx

push rdx

mov rdi, 0x736c2f2f6369622f    ; "sl/nib/"
push rdi
mov rbx, rsp

push rdx

mov rdi, 0x2f
push rdi
mov rsi, rsp

push rax
push rsi
push rbx

mov rcx, rsp

mov rax, 59
syscall

mov rax, 60
syscall
</code>```

breakpoint at first syscall:

```<code>(gdb) x/20x $rsp
0x7fffffffe140: 0xffffe168      0x00007fff      0xffffe158      0x00007fff
0x7fffffffe150: 0x00000000      0x00000000      0x0000002f      0x00000000
0x7fffffffe160: 0x00000000      0x00000000      0x6369622f      0x736c2f2f
0x7fffffffe170: 0x00000000      0x00000000      0xf7e1bbbb      0x00007fff
0x7fffffffe180: 0x00000000      0x00000000      0xffffe258      0x00007fff
(gdb) x/20x $rcx
0x7fffffffe140: 0xffffe168      0x00007fff      0xffffe158      0x00007fff
0x7fffffffe150: 0x00000000      0x00000000      0x0000002f      0x00000000
0x7fffffffe160: 0x00000000      0x00000000      0x6369622f      0x736c2f2f
0x7fffffffe170: 0x00000000      0x00000000      0xf7e1bbbb      0x00007fff
0x7fffffffe180: 0x00000000      0x00000000      0xffffe258      0x00007fff
(gdb) x/20x $rsi
0x7fffffffe158: 0x0000002f      0x00000000      0x00000000      0x00000000
0x7fffffffe168: 0x6369622f      0x736c2f2f      0x00000000      0x00000000
</code>```

Strace output:

```<code>execve("./system", ["./system"], 0x7ffd27c17790 /* 45 vars */) = 0
brk(NULL)                               = 0x5642527c2000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or     directory)
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=104798, ...}) = 0
mmap(NULL, 104798, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fc05fca4000
close(3)                                = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) =     3
read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\320l\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1820104, ...}) = 0
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fc05fca2000
mmap(NULL, 1832568, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fc05fae2000
mprotect(0x7fc05fb07000, 1642496, PROT_NONE) = 0
mmap(0x7fc05fb07000, 1339392, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x25000) = 0x7fc05fb07000
mmap(0x7fc05fc4e000, 299008, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x16c000) = 0x7fc05fc4e000
mmap(0x7fc05fc98000, 24576, PROT_READ|PROT_WRITE,     MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b5000) = 0x7fc05fc98000
mmap(0x7fc05fc9e000, 13944, PROT_READ|PROT_WRITE,     MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fc05fc9e000
close(3)                                = 0
arch_prctl(ARCH_SET_FS, 0x7fc05fca3500) = 0
mprotect(0x7fc05fc98000, 12288, PROT_READ) = 0
mprotect(0x564250be4000, 4096, PROT_READ) = 0
mprotect(0x7fc05fce5000, 4096, PROT_READ) = 0
munmap(0x7fc05fca4000, 104798)          = 0
execve(0x2f, [0x2f], NULL)              = -1 EFAULT (Bad address)
exit(47)                                = ?
+++ exited with 47 +++
</code>```

Since we are dealing with a 64 bit arc, then presuming that we might have to push a 64 bit NULL after every arguments too, right?
I played around a little to push a 32 bit NULL to separate the arguments in the stack, but that didn't work as well.

Not sure what mistake am I committing that the script is not working :(

Any guidance are much appreciated.

I am using nasm in a x64 bit kali linux

答:
Huge thanks to @PeterCordes.

In 64 bit architecture, you can visit unistd_64.h to find codes for system calls. which in this case for execve the system call were 59.

strace helped a lot. with a bit of debugging, found out that the the executing file location /bin//ls should be stored at rdi and the arguments /bin//ls ./ should be stored at rsi.

complete working code is below:

```<code>SECTION .data
SECTION .text
global main
main:
xor rax, rax
xor rdx, rdx

push rdx

mov rcx, 0x736c2f2f6e69622f    ; "sl/nib/"
push rcx
mov rdi, rsp

;push rdx

mov rcx, 0x2f2e
push rcx
mov rsi, rsp

push rax
push rsi
push rdi

mov rsi, rsp
mov rax, 59
syscall

mov rax, 60
syscall
</code>```

Body:
I recently been trying to execute system commands using pure assembly. I managed to achieve it in a x32 bit binary as posted here: execute system command (bash) using assembly?

But Now I am trying to integrate that same procedure to a x64 bit binary. I might be very bad at art of googling but I couldn't find any article showing how to execute system commands in x64 bit.

Precisely said, below is what I did:

SECTION .data
SECTION .text
global main
main:
xor rax, rax
xor rdx, rdx

push rdx

mov rdi, 0x736c2f2f6369622f    ; "sl/nib/"
push rdi
mov rbx, rsp

push rdx

mov rdi, 0x2f
push rdi
mov rsi, rsp

push rax
push rsi
push rbx

mov rcx, rsp

mov rax, 59
syscall

mov rax, 60
syscall

breakpoint at first syscall:

(gdb) x/20x $rsp
0x7fffffffe140: 0xffffe168      0x00007fff      0xffffe158      0x00007fff
0x7fffffffe150: 0x00000000      0x00000000      0x0000002f      0x00000000
0x7fffffffe160: 0x00000000      0x00000000      0x6369622f      0x736c2f2f
0x7fffffffe170: 0x00000000      0x00000000      0xf7e1bbbb      0x00007fff
0x7fffffffe180: 0x00000000      0x00000000      0xffffe258      0x00007fff
(gdb) x/20x $rcx
0x7fffffffe140: 0xffffe168      0x00007fff      0xffffe158      0x00007fff
0x7fffffffe150: 0x00000000      0x00000000      0x0000002f      0x00000000
0x7fffffffe160: 0x00000000      0x00000000      0x6369622f      0x736c2f2f
0x7fffffffe170: 0x00000000      0x00000000      0xf7e1bbbb      0x00007fff
0x7fffffffe180: 0x00000000      0x00000000      0xffffe258      0x00007fff
(gdb) x/20x $rsi
0x7fffffffe158: 0x0000002f      0x00000000      0x00000000      0x00000000
0x7fffffffe168: 0x6369622f      0x736c2f2f      0x00000000      0x00000000

Strace output:

execve("./system", ["./system"], 0x7ffd27c17790 /* 45 vars */) = 0
brk(NULL)                               = 0x5642527c2000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or     directory)
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=104798, ...}) = 0
mmap(NULL, 104798, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fc05fca4000
close(3)                                = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) =     3
read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\320l\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1820104, ...}) = 0
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fc05fca2000
mmap(NULL, 1832568, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fc05fae2000
mprotect(0x7fc05fb07000, 1642496, PROT_NONE) = 0
mmap(0x7fc05fb07000, 1339392, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x25000) = 0x7fc05fb07000
mmap(0x7fc05fc4e000, 299008, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x16c000) = 0x7fc05fc4e000
mmap(0x7fc05fc98000, 24576, PROT_READ|PROT_WRITE,     MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b5000) = 0x7fc05fc98000
mmap(0x7fc05fc9e000, 13944, PROT_READ|PROT_WRITE,     MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fc05fc9e000
close(3)                                = 0
arch_prctl(ARCH_SET_FS, 0x7fc05fca3500) = 0
mprotect(0x7fc05fc98000, 12288, PROT_READ) = 0
mprotect(0x564250be4000, 4096, PROT_READ) = 0
mprotect(0x7fc05fce5000, 4096, PROT_READ) = 0
munmap(0x7fc05fca4000, 104798)          = 0
execve(0x2f, [0x2f], NULL)              = -1 EFAULT (Bad address)
exit(47)                                = ?
+++ exited with 47 +++

Since we are dealing with a 64 bit arc, then presuming that we might have to push a 64 bit NULL after every arguments too, right?
I played around a little to push a 32 bit NULL to separate the arguments in the stack, but that didn't work as well.

Not sure what mistake am I committing that the script is not working :(

Any guidance are much appreciated.

I am using nasm in a x64 bit kali linux

Body:
Huge thanks to @PeterCordes.

In 64 bit architecture, you can visit unistd_64.h to find codes for system calls. which in this case for execve the system call were 59.

strace helped a lot. with a bit of debugging, found out that the the executing file location /bin//ls should be stored at rdi and the arguments /bin//ls ./ should be stored at rsi.

complete working code is below:

SECTION .data
SECTION .text
global main
main:
xor rax, rax
xor rdx, rdx

push rdx

mov rcx, 0x736c2f2f6e69622f    ; "sl/nib/"
push rcx
mov rdi, rsp

;push rdx

mov rcx, 0x2f2e
push rcx
mov rsi, rsp

push rax
push rsi
push rdi

mov rsi, rsp
mov rax, 59
syscall

mov rax, 60
syscall


来源: stackexchange

问:
JQuery Table Row Click Expand/Collapse
I have tried multiple solutions but none have worked for me yet. I have a table with some rows that can be considered section headers or keys and others that contain items under that header or key.

```<code><table>
    <thead>
        <tr><th colspan="2">Name</th><th colspan="2">Date</th></tr>
    </thead>
    <tbody>
    <tr class="key"><td colspan="4">AAA</td></tr>
        <tr class="item"><td colspan="2">ANAME</td><td colspan="2">20200101</td></tr>
        <tr class="item"><td colspan="2">ANAME</td><td colspan="2">20200101</td></tr>
        <tr class="item"><td colspan="2">ANAME</td><td colspan="2">20200101</td></tr>
    <tr class="key"><td colspan="4">BBB</td></tr>
        <tr class="item"><td colspan="2">BNAME</td><td colspan="2">20200101</td></tr>
        <tr class="item"><td colspan="2">BNAME</td><td colspan="2">20200101</td></tr>
    <tr class="key"><td colspan="4">CCC</td></tr>
        <tr class="item"><td colspan="2">CNAME</td><td colspan="2">20200101</td></tr>
    </tbody>
</table>
</code>```

When the page is loaded the rows with class item should be hidden using CSS -> display:none.
Ideally I should be able to click a header or key row and all item under that should expand and become visible. Additionally I want all other item not under the clicked key to be collapse if they were expanded.

My previous solutions used slideToggle and toggleClass but with either one or a combination of the two, I was not able to get the desired outcome.

My current version will only expand the next item in the table. There is currently nothing to tell others to close because I could not get any of my solutions to behave similar to what was desired.

```<code>$(".key").click(function(event) {
    $key = $(this);
    $content = $key.next();
    $content.slideToggle(0, function () {
        $key.text(function () {
            return;
        });
    });
});
</code>```

答:
Basic idea using nextUntil() to get all the rows after it.

$("table tbody").on("click", "tr.key", function () {
  var active = $(this)
  var trs = active.nextUntil(".key")
  trs.show();

  $("tr.item").not(trs).hide()

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.key {
  background-color: #CCC;
}
.item {
  display: none;
}

.item td {
  border: 1px solid black;
}</code>```

      Name
      Date

      AAA

      ANAME
      20200101

      ANAME
      20200101

      ANAME
      20200101

      BBB

      BNAME
      20200101

      BNAME
      20200101

      CCC

      CNAME
      20200101

```

ContentLicense: CC BY-SA 4.0

Title: JQuery Table Row Click Expand/Collapse

Body:
I have tried multiple solutions but none have worked for me yet. I have a table with some rows that can be considered section headers or keys and others that contain items under that header or key.

Name	Date

AAA

ANAME	20200101

ANAME	20200101

ANAME	20200101

BBB

BNAME	20200101

BNAME	20200101

CCC

CNAME	20200101

When the page is loaded the rows with class item should be hidden using CSS -> display:none.
Ideally I should be able to click a header or key row and all item under that should expand and become visible. Additionally I want all other item not under the clicked key to be collapse if they were expanded.

My previous solutions used slideToggle and toggleClass but with either one or a combination of the two, I was not able to get the desired outcome.

My current version will only expand the next item in the table. There is currently nothing to tell others to close because I could not get any of my solutions to behave similar to what was desired.

$(".key").click(function(event) {
    $key = $(this);
    $content = $key.next();
    $content.slideToggle(0, function () {
        $key.text(function () {
            return;
        });
    });
});

Body:
Basic idea using nextUntil() to get all the rows after it.

$("table tbody").on("click", "tr.key", function () {
  var active = $(this)
  var trs = active.nextUntil(".key")
  trs.show();

  $("tr.item").not(trs).hide()

})

.key {
  background-color: #CCC;
}
.item {
  display: none;
}

.item td {
  border: 1px solid black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th colspan="2">Name</th>
      <th colspan="2">Date</th>
    </tr>
  </thead>
  <tbody>
    <tr class="key">
      <td colspan="4">AAA</td>
    </tr>
    <tr class="item">
      <td colspan="2">ANAME</td>
      <td colspan="2">20200101</td>
    </tr>
    <tr class="item">
      <td colspan="2">ANAME</td>
      <td colspan="2">20200101</td>
    </tr>
    <tr class="item">
      <td colspan="2">ANAME</td>
      <td colspan="2">20200101</td>
    </tr>
    <tr class="key">
      <td colspan="4">BBB</td>
    </tr>
    <tr class="item">
      <td colspan="2">BNAME</td>
      <td colspan="2">20200101</td>
    </tr>
    <tr class="item">
      <td colspan="2">BNAME</td>
      <td colspan="2">20200101</td>
    </tr>
    <tr class="key">
      <td colspan="4">CCC</td>
    </tr>
    <tr class="item">
      <td colspan="2">CNAME</td>
      <td colspan="2">20200101</td>
    </tr>
  </tbody>
</table>


问:
Buggy Scrollbar Behavior
I'm trying to implement a scroll-able content layout and I managed to do it, however the scrollbar is displaying strange behavior - sometimes it cannot get clicked, sometimes the arrows do not move it, sometimes only 1 arrow can move it even though there is space to be scrolled in either direction, etc..

.content-wrapper {
  display: flex;
  justify-content: center;
  overflow-y: scroll;
  flex-grow: 1;
  /* for Firefox */
  min-height: 0;
}

.tsp-content {
  display: flex;
  flex-direction: column;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content-wrapper">
  <div class="tsp-content">
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root tsp-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root tsp-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root transportation-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root tsp-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root tsp-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root tsp-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root tsp-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root tsp-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root tsp-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
    <div class="MuiPaper-root MuiCard-root MuiPaper-outlined MuiPaper-rounded">
      <div class="MuiCardContent-root">
        <p>Lorem -> Ipsum (0328)</p>
      </div>
      <div class="MuiCardActions-root tsp-card-buttons MuiCardActions-spacing">
        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button"><span class="MuiButton-label">LoremIpsum</span><span class="MuiTouchRipple-root"></span></button>
      </div>
    </div>
    <br>
  </div>
</div></code>```

Here's the codepen: https://codepen.io/JustM/pen/PoqGNGP

答:
your problem is that the  is on the top of the scrollable content, so that's why it won't scroll.

I added z-index: 0; to .path and z-index:1; to .content-wrapper and it worked.

you can check it here
https://codepen.io/remyjouni/pen/JjdRKxb

I highly recommend any kind of background shapes to be added in CSS as a background.

Title: Buggy Scrollbar Behavior

Body:
I'm trying to implement a scroll-able content layout and I managed to do it, however the scrollbar is displaying strange behavior - sometimes it cannot get clicked, sometimes the arrows do not move it, sometimes only 1 arrow can move it even though there is space to be scrolled in either direction, etc..

.content-wrapper {
  display: flex;
  justify-content: center;
  overflow-y: scroll;
  flex-grow: 1;
  /* for Firefox */
  min-height: 0;
}

.tsp-content {
  display: flex;
  flex-direction: column;
}

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Lorem -> Ipsum (0328)

        <button class="MuiButtonBase-root MuiButton-root MuiButton-outlined MuiButton-outlinedSecondary MuiButton-outlinedSizeSmall MuiButton-sizeSmall" tabindex="0" type="button">LoremIpsum</button>

Here's the codepen: https://codepen.io/JustM/pen/PoqGNGP

Body:
your problem is that the <img class="path"/> is on the top of the scrollable content, so that's why it won't scroll.

I added z-index: 0; to .path and z-index:1; to .content-wrapper and it worked.

you can check it here
https://codepen.io/remyjouni/pen/JjdRKxb

I highly recommend any kind of background shapes to be added in CSS as a background.


问:
Click an item in autocomplete list with VBA and HTML
I've created an automation where it will allow me to enter details on a website (though I cannot share it as it is internal). My code below is working only until it enters a text on "received from". However, this "received from" field has an autocomplete list and I need to select it in order to populate other fields such as TIN and Address.

The autocomplete list is quite similar with the one in
https://jqueryui.com/autocomplete/
or http://demos.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/

Below is my code:

```<code>Sub Automate_IE_Enter_Data()
'This will load a webpage in IE
Dim i               As Long
Dim Url             As String
Dim IE              As InternetExplorer
Dim objElement      As Object
Dim objCollection   As Object
Dim HWNDSrc         As Long
Dim wsTemplate      As Worksheet
Dim objEvent        As Object
Dim li_arr          As Variant
Dim NodeList        As Object
Dim x               As Long

Set wsTemplate = ThisWorkbook.Sheets("Template")

'Create InternetExplorer Object
Set IE = New InternetExplorerMedium

'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True

'Define URL by getting the value in rngURL; can be found in the main sheet
Url = "http://URL Path"

'Navigate to URL
IE.Navigate Url

' Statusbar let's user know website is loading
Application.StatusBar = Url & " is loading. Please wait..."

Do
DoEvents
Loop Until IE.ReadyState = READYSTATE_COMPLETE

'Webpage Loaded
Application.StatusBar = Url & " Loaded"

'Get Window ID for IE so we can set it as activate window
HWNDSrc = IE.hwnd
'Set IE as Active Window
SetForegroundWindow HWNDSrc
ShowWindow IE.hwnd, SW_SHOWMAXIMIZED

Dim Doc As HTMLDocument
Set Doc = IE.document

inputString = "Nuevo"

With Doc.getElementById("supName")

    .Focus
    SendKeys inputString 'Trigger the field to show autocomplete list

End With

'----THIS IS WHERE I AM TRYING TO CLICK THE AUTOCOMPLETE LIST THAT IS BEING DISPLAYED-----
'-----HOWEVER, CLICKING DOESN'T SEEM TO WORK.-----

Set NodeList = Doc.querySelectorAll(".ui-active-menuitem[role=""menuitem""]")

For x = 0 To NodeList.Length - 1
'Debug.Print NodeList.Item(x).Click '<==this way
NodeList.Item(x).Focus
NodeList(x).Click   '<==Or this method

Next x

MsgBox "Done"

'Unload IE
endmacro:
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing

End Sub
</code>```

Below is the HTML which I think would be helpful to understand my issue:

```<code>'----- NAME OF THE FIELD THAT HAS AN AUTOCOMPLETE LIST----
<INPUT name=supName class="required-placeholder simple-placeholder ui-autocomplete-input placeholding" id=supName role=textbox aria-haspopup=true aria-autocomplete=list type=text value=Required jQuery17102032699680461189="39" placeholder="Required" autocomplete="off">

<UL class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all" role=listbox aria-activedescendant=ui-active-menuitem style="WIDTH: 400px; LEFT: 751px; Z-INDEX: 1; DISPLAY: none; TOP: 287px" jQuery17102032699680461189="42"><LI class=ui-menu-item role=menuitem jQuery17102032699680461189="104"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="114">List 0</A></LI>

<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="105"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="115">List 1</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="106"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="116">List 2</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="107"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="117">List 3</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="108"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="118">List 4</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="109"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="119">List 5</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="110"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="120">List 6</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="111"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="121">List 7</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="112"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="122">List 8</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="113"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="123">List 9</A></LI></UL>
</code>```

A sample screenshot of autocomplete list:

More of the HTML:

  <FORM id=receiptEntryForm action=/ReceiptEntry/SaveReceipt method=post jQuery17109198838813964318="40">

          OR No:
          Date:
          Received From:
          TIN:
          Address:

          <INPUT name=ReceiptNumber disabled id=ReceiptNumber type=text data-val-required="The ReceiptNumber field is required." data-val-number="The field ReceiptNumber must be a number." data-val="true">

          <INPUT name=printDate class="datepicker hasDatepicker" id=printDate type=text jQuery17109198838813964318="38">

          <INPUT name=supName class="required-placeholder simple-placeholder ui-autocomplete-input placeholding" id=supName role=textbox aria-haspopup=true aria-autocomplete=list type=text value=Required jQuery17109198838813964318="39" placeholder="Required" autocomplete="off">

          <INPUT name=SupplierCode id=SupplierCode type=hidden data-val-required="The SupplierCode field is required." data-val="true" data-val-length-max="20" data-val-length="You've reached the maximum length allowed.">

          <INPUT name=SupTIN class="required-placeholder placeholding simple-placeholder" id=SupTIN type=text value=Required jQuery17109198838813964318="41" placeholder="Required" ,>

          <TEXTAREA name=SupAdd class="textarea-wide required-placeholder" id=SupAdd rows=3 cols=48 placeholder="Required"></TEXTAREA>

        The sum of ****:

          Receipt Type:
          VATable Receipt:

IN PAYMENT OF

          <SELECT id=receiptentry-type jQuery17109198838813964318="36">
            <OPTION value=cr selected>Collection Receipt</OPTION>
            <OPTION value=or>Official Receipt</OPTION>
          </SELECT>

          <INPUT disabled id=chk-vatable type=checkbox jQuery17109198838813964318="37">

                  INVOICE NO.
                  AMOUNT
                  FORM OF PAYMENT
                  AMOUNT

                  CASH

                  BANK
                  CHECK NO.
                  DATE

                  TOTAL

      THIS CANCELS OUR P.R.#
      <INPUT name=CancelPrNo id=CancelPrNo type=text data-val="true" data-val-length-max="50" data-val-length="You've reached the maximum length allowed.">
      <INPUT class="right button-style" id=add-receipt type=button value=Add jQuery17109198838813964318="43">

  </FORM>

```

<p><strong>Chrome Console:</strong> </p>

<p><img src="https://i.stack.imgur.com/OuDR7.png" alt="enter image description here"></p>

<p><strong>Inspect element of autocomplete list:</strong> </p>

```

*TEXT RESULT OF THE AUTOCOMPLETE LIST*

```

答:
See how the LI item contains a  tag. You should try clicking the first child.

Instead of:

```<code>NodeList.Item(x).Focus
NodeList(x).Click
</code>```

Try:

```<code>NodeList.Item(x).Focus
NodeList(x).FirstChild.Click
</code>```

https://www.w3schools.com/jsref/prop_node_firstchild.asp

Body:
I've created an automation where it will allow me to enter details on a website (though I cannot share it as it is internal). My code below is working only until it enters a text on "received from". However, this "received from" field has an autocomplete list and I need to select it in order to populate other fields such as TIN and Address.

The autocomplete list is quite similar with the one in
https://jqueryui.com/autocomplete/
or http://demos.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/

Below is my code:

Sub Automate_IE_Enter_Data()
'This will load a webpage in IE
Dim i               As Long
Dim Url             As String
Dim IE              As InternetExplorer
Dim objElement      As Object
Dim objCollection   As Object
Dim HWNDSrc         As Long
Dim wsTemplate      As Worksheet
Dim objEvent        As Object
Dim li_arr          As Variant
Dim NodeList        As Object
Dim x               As Long

Set wsTemplate = ThisWorkbook.Sheets("Template")

'Create InternetExplorer Object
Set IE = New InternetExplorerMedium

'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True

'Define URL by getting the value in rngURL; can be found in the main sheet
Url = "http://URL Path"

'Navigate to URL
IE.Navigate Url

' Statusbar let's user know website is loading
Application.StatusBar = Url & " is loading. Please wait..."

Do
DoEvents
Loop Until IE.ReadyState = READYSTATE_COMPLETE

'Webpage Loaded
Application.StatusBar = Url & " Loaded"

'Get Window ID for IE so we can set it as activate window
HWNDSrc = IE.hwnd
'Set IE as Active Window
SetForegroundWindow HWNDSrc
ShowWindow IE.hwnd, SW_SHOWMAXIMIZED

Dim Doc As HTMLDocument
Set Doc = IE.document

inputString = "Nuevo"

With Doc.getElementById("supName")

    .Focus
    SendKeys inputString 'Trigger the field to show autocomplete list

End With

'----THIS IS WHERE I AM TRYING TO CLICK THE AUTOCOMPLETE LIST THAT IS BEING DISPLAYED-----
'-----HOWEVER, CLICKING DOESN'T SEEM TO WORK.-----

Set NodeList = Doc.querySelectorAll(".ui-active-menuitem[role=""menuitem""]")

For x = 0 To NodeList.Length - 1
'Debug.Print NodeList.Item(x).Click '<==this way
NodeList.Item(x).Focus
NodeList(x).Click   '<==Or this method

Next x

MsgBox "Done"

'Unload IE
endmacro:
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing

End Sub

Below is the HTML which I think would be helpful to understand my issue:

'----- NAME OF THE FIELD THAT HAS AN AUTOCOMPLETE LIST----
<INPUT name=supName class="required-placeholder simple-placeholder ui-autocomplete-input placeholding" id=supName role=textbox aria-haspopup=true aria-autocomplete=list type=text value=Required jQuery17102032699680461189="39" placeholder="Required" autocomplete="off">

List 0

List 1

List 2

List 3

List 4

List 5

List 6

List 7

List 8

List 9

A sample screenshot of autocomplete list:

More of the HTML:

  <FORM id=receiptEntryForm action=/ReceiptEntry/SaveReceipt method=post jQuery17109198838813964318="40">

          OR No:
          Date:
          Received From:
          TIN:
          Address:

          <INPUT name=ReceiptNumber disabled id=ReceiptNumber type=text data-val-required="The ReceiptNumber field is required." data-val-number="The field ReceiptNumber must be a number." data-val="true">

          <INPUT name=printDate class="datepicker hasDatepicker" id=printDate type=text jQuery17109198838813964318="38">

          <INPUT name=supName class="required-placeholder simple-placeholder ui-autocomplete-input placeholding" id=supName role=textbox aria-haspopup=true aria-autocomplete=list type=text value=Required jQuery17109198838813964318="39" placeholder="Required" autocomplete="off">

          <INPUT name=SupplierCode id=SupplierCode type=hidden data-val-required="The SupplierCode field is required." data-val="true" data-val-length-max="20" data-val-length="You&#39;ve reached the maximum length allowed.">

          <INPUT name=SupTIN class="required-placeholder placeholding simple-placeholder" id=SupTIN type=text value=Required jQuery17109198838813964318="41" placeholder="Required" ,>

          <TEXTAREA name=SupAdd class="textarea-wide required-placeholder" id=SupAdd rows=3 cols=48 placeholder="Required"></TEXTAREA>

        The sum of ****:

          Receipt Type:
          VATable Receipt:

IN PAYMENT OF

          <SELECT id=receiptentry-type jQuery17109198838813964318="36">
            <OPTION value=cr selected>Collection Receipt</OPTION>
            <OPTION value=or>Official Receipt</OPTION>
          </SELECT>

          <INPUT disabled id=chk-vatable type=checkbox jQuery17109198838813964318="37">

                  INVOICE NO.
                  AMOUNT
                  FORM OF PAYMENT
                  AMOUNT

                  CASH

                  BANK
                  CHECK NO.
                  DATE

                  TOTAL

      THIS CANCELS OUR P.R.#
      <INPUT name=CancelPrNo id=CancelPrNo type=text data-val="true" data-val-length-max="50" data-val-length="You&#39;ve reached the maximum length allowed.">
      <INPUT class="right button-style" id=add-receipt type=button value=Add jQuery17109198838813964318="43">

  </FORM>

Chrome Console:

Inspect element of autocomplete list:

*TEXT RESULT OF THE AUTOCOMPLETE LIST*

Body:
See how the LI item contains a  tag. You should try clicking the first child.

Instead of:

NodeList.Item(x).Focus
NodeList(x).Click

Try:

NodeList.Item(x).Focus
NodeList(x).FirstChild.Click

https://www.w3schools.com/jsref/prop_node_firstchild.asp


问:
Do I need to use PrevState even if I spread the state into a variable?
I am testing some code to try and understand the race condition regarding the use of setState().

my code can be found here

my code below:

```<code>import React from "react";

export default class App extends React.Component {
  state = {
    id: "",
    ids: [{ id: 7 }, { id: 14 }]
  };

  // here is where I create the id numbers
  uniqueIdCreatorHandler = incrementAmount => {
    let ids = [...this.state.ids];
    let highestId = 0;
    if (ids.length > 0) {
      highestId = ids
        .map(value => {
          return value.id;
        })
        .reduce((a, b) => {
          return Math.max(a, b);
        });
    }
    let newId = highestId + incrementAmount;
    ids.push({ id: newId });
    this.setState({ ids: ids });
  };

  idDeleterHanlder = currentIndex => {
    let ids = this.state.ids;
    ids.splice(currentIndex, 1);
    this.setState({ ids: ids });
  };
  //below is when I test performing the function twice, in order to figure if the result would be a race condition
  double = (firstIncrementAmount, secondIncrementAmount) => {
    this.uniqueIdCreatorHandler(firstIncrementAmount);
    this.uniqueIdCreatorHandler(secondIncrementAmount);
  };

  render() {
    let ids = this.state.ids.map((id, index) => {
      return (
        <p onClick={() => this.idDeleterHanlder(index)} key={id.id}>
          id:{id.id}
        </p>
      );
    });

    return (
      <div className="App">
        <button onClick={() => this.uniqueIdCreatorHandler(1)}>
          Push new id
        </button>
        <button onClick={() => this.double(1, 2)}>Add some Ids</button>
        <p>all ids below:</p>
        {ids}
      </div>
    );
  }
}

</code>```

when invoking the double function on the second button only the secondIncrementAmount works. You can test it by changing the argument values on the call made on the onClick method.

I think that I should somehow use prevState on this.setState in order to fix this.

How could I avoid this issue here? This matter started at CodeReview but I did not realize how could I fix this.

There is also a recommendation to spread the mapped ids into Math.max and I could not figure out how and Why to do it. Isn't the creation of the new array by mapping the spreaded key values safe enough?

答:
setState can be asynchronous, batching up multiple changes and then applying them all at once. So when you spread the state you might be spreading an old version of the state and throwing out a change that should have happened.

The function version of setState avoids this. React guarantees that you will be passed in the most recent state, even if there's some other state update that you didn't know about. And then you can product the new state based on that.

There is also a recommendation to spread the mapped ids into Math.max and I could not figure out how and Why to do it

That's just to simplify the code for finding the max. Math.max can be passed an abitrary number of arguments, rather than just two at a time, so you don't need to use reduce to get the maximum of an array.

```<code>uniqueIdCreatorHandler = incrementAmount => {
  this.setState(prevState => {
    let ids = [...prevState.ids];
    let highestId = Math.max(...ids.map(value => value.id));
    let newId = highestId + incrementAmount;
    ids.push({ id: newId });
    this.setState({ ids: ids });
  });
};
</code>```

Body:
I am testing some code to try and understand the race condition regarding the use of setState().

my code can be found here

my code below:

import React from "react";

export default class App extends React.Component {
  state = {
    id: "",
    ids: [{ id: 7 }, { id: 14 }]
  };

  // here is where I create the id numbers
  uniqueIdCreatorHandler = incrementAmount => {
    let ids = [...this.state.ids];
    let highestId = 0;
    if (ids.length > 0) {
      highestId = ids
        .map(value => {
          return value.id;
        })
        .reduce((a, b) => {
          return Math.max(a, b);
        });
    }
    let newId = highestId + incrementAmount;
    ids.push({ id: newId });
    this.setState({ ids: ids });
  };

  idDeleterHanlder = currentIndex => {
    let ids = this.state.ids;
    ids.splice(currentIndex, 1);
    this.setState({ ids: ids });
  };
  //below is when I test performing the function twice, in order to figure if the result would be a race condition
  double = (firstIncrementAmount, secondIncrementAmount) => {
    this.uniqueIdCreatorHandler(firstIncrementAmount);
    this.uniqueIdCreatorHandler(secondIncrementAmount);
  };

  render() {
    let ids = this.state.ids.map((id, index) => {
      return (

 this.idDeleterHanlder(index)} key={id.id}>
          id:{id.id}

      );
    });

    return (

        <button onClick={() => this.uniqueIdCreatorHandler(1)}>
          Push new id
        </button>
        <button onClick={() => this.double(1, 2)}>Add some Ids</button>

all ids below:

        {ids}

    );
  }
}

when invoking the double function on the second button only the secondIncrementAmount works. You can test it by changing the argument values on the call made on the onClick method.

I think that I should somehow use prevState on this.setState in order to fix this.

How could I avoid this issue here? This matter started at CodeReview but I did not realize how could I fix this.

There is also a recommendation to spread the mapped ids into Math.max and I could not figure out how and Why to do it. Isn't the creation of the new array by mapping the spreaded key values safe enough?

Body:
setState can be asynchronous, batching up multiple changes and then applying them all at once. So when you spread the state you might be spreading an old version of the state and throwing out a change that should have happened.

The function version of setState avoids this. React guarantees that you will be passed in the most recent state, even if there's some other state update that you didn't know about. And then you can product the new state based on that.

There is also a recommendation to spread the mapped ids into Math.max and I could not figure out how and Why to do it

That's just to simplify the code for finding the max. Math.max can be passed an abitrary number of arguments, rather than just two at a time, so you don't need to use reduce to get the maximum of an array.

uniqueIdCreatorHandler = incrementAmount => {
  this.setState(prevState => {
    let ids = [...prevState.ids];
    let highestId = Math.max(...ids.map(value => value.id));
    let newId = highestId + incrementAmount;
    ids.push({ id: newId });
    this.setState({ ids: ids });
  });
};


问:
Endianess macros not correctly defined
I'm trying to compile grpc, and one of the targets uses /usr/include/netinet/tcp.h which contains this :

```<code># if __BYTE_ORDER == __LITTLE_ENDIAN
        uint8_t th_x2:4;        /* (unused) */
        uint8_t th_off:4;       /* data offset */
# endif
# if __BYTE_ORDER == __BIG_ENDIAN
        uint8_t th_off:4;       /* data offset */
        uint8_t th_x2:4;        /* (unused) */
# endif
</code>```

Somehow, the two conditions are fulfilled which makes the compilation fail (error: duplicate member 'th_off'). I wrote a test C program and it seems that the three macros are not correctly defined.

I tried to reinstall gcc and g++, and also downgrade them to a previous version. I also tried to reinstall the Linux headers. I finally tried to compile with clang, but it doesn't work either.

My two test computers are running Ubuntu 19.10 and the result is the same on both of them. Is there a compiler flag or a system configuration needed to define these macros?

EDIT : tcp.h is a system header. I did not write it and it's an almost fresh install of Ubuntu with a standard installation of build-essentials.

EDIT 2 : I used a test program and it works correctly in this case. It shows little:

```<code>#include <iostream>
#include <netinet/tcp.h>

int main() {
#if __BYTE_ORDER == __LITTLE_ENDIAN
    std::cout << "little\n";
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
    std::cout << "big\n";
#endif
}
</code>```

答:
You could use the gcc builtins:

```<code># if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
        uint8_t th_x2:4;        /* (unused) */
        uint8_t th_off:4;       /* data offset */
# endif
# if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        uint8_t th_off:4;       /* data offset */
        uint8_t th_x2:4;        /* (unused) */
# endif
</code>```

In the c preprocessor, two macros which do not exist are equal.

Source: https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html

Title: Endianess macros not correctly defined

Body:
I'm trying to compile grpc, and one of the targets uses /usr/include/netinet/tcp.h which contains this :

# if __BYTE_ORDER == __LITTLE_ENDIAN
        uint8_t th_x2:4;        /* (unused) */
        uint8_t th_off:4;       /* data offset */
# endif
# if __BYTE_ORDER == __BIG_ENDIAN
        uint8_t th_off:4;       /* data offset */
        uint8_t th_x2:4;        /* (unused) */
# endif

Somehow, the two conditions are fulfilled which makes the compilation fail (error: duplicate member 'th_off'). I wrote a test C program and it seems that the three macros are not correctly defined.

I tried to reinstall gcc and g++, and also downgrade them to a previous version. I also tried to reinstall the Linux headers. I finally tried to compile with clang, but it doesn't work either.

My two test computers are running Ubuntu 19.10 and the result is the same on both of them. Is there a compiler flag or a system configuration needed to define these macros?

EDIT : tcp.h is a system header. I did not write it and it's an almost fresh install of Ubuntu with a standard installation of build-essentials.

EDIT 2 : I used a test program and it works correctly in this case. It shows little:

#include <iostream>
#include <netinet/tcp.h>

int main() {
#if __BYTE_ORDER == __LITTLE_ENDIAN
    std::cout << "little\n";
#endif
#if __BYTE_ORDER == __BIG_ENDIAN
    std::cout << "big\n";
#endif
}

Body:
You could use the gcc builtins:

# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
        uint8_t th_x2:4;        /* (unused) */
        uint8_t th_off:4;       /* data offset */
# endif
# if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        uint8_t th_off:4;       /* data offset */
        uint8_t th_x2:4;        /* (unused) */
# endif

In the c preprocessor, two macros which do not exist are equal.

Source: https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html


问:
Button click wont trigger function
I'm having trouble triggering a function. I have the following code:</p>

```<code>var dnfmomd;

dnfmomd = new function () {
//function content
}

$("#launch_button").on("click", dnfmomd.init);
</code>```

答:
Have you tried this?</p>

```<code>var dnfmomd = function () {
//function content
}

$("#launch_button").on("click", dnfmomd());
</code>```

Title: Button click wont trigger function

Body:
I'm having trouble triggering a function. I have the following code:

var dnfmomd;

dnfmomd = new function () {
//function content
}

$("#launch_button").on("click", dnfmomd.init);

Body:
Have you tried this?

var dnfmomd = function () {
//function content
}

$("#launch_button").on("click", dnfmomd());


问:
Dereference Operator Before an Array Element?
What does the notation in something like int y = *x[0] do, i.e. when you have a dereference operator right before an array element?

答:
The postfix operator [] binds stronger than the prefix operator *, and more generally all postfix operators bind stronger than all prefix operators. Hence *x[0] is equivalent to *(x[0]) which can occur and have type int in different cases:

if x is an array of arrays of int, also known as a 2D array of int: int x[2][2];

if x is an array of pointers to int: int *x[2];

if x is a pointer to a pointer to int: int **x;

if x is a pointer to an array of int: int (*x)[2]; (this one is very confusing)

For all of the above, the expression *x[0] is equivalent to any of these:

x[0][0]

**x

and by coincidence (*x)[0]

As well as these unusual and surprising expressions:

0[*x]

0[x[0]]

0[0[x]]

*0[x]

0[x][0]


问:
Django: ManyToManyField appears as empty on my template
I'm having an issue displaying a ManyToManyField in a character profile template using Django.

The template has to show an avatar, alongside some information about the character, including a list of guilds this character had joined. But, when I try to display that list, it appears as if it is empty. I had a look into my site administration page, and that information is there, so I have confirmation that the data can be displayed in my template. I just don't know how. How could I handle that?

These are my models:

```<code>""" Modelos de la aplicación de personajes """
from django.db import models

class Guild(models.Model):
    """ Modelo del clan """
    guild_name = models.CharField(max_length=25)
    rank = models.PositiveSmallIntegerField()

    def __str__(self):
        return self.guild_name

class Character(models.Model):
    """ Modelo del personaje """
    character_name = models.CharField(max_length=25)
    level = models.PositiveSmallIntegerField()
    race = models.CharField(max_length=25)
    gender = models.CharField(max_length=25)
    job = models.CharField(max_length=25)
    avatar = models.ImageField(upload_to='', blank=True)
    character_guilds = models.ManyToManyField(Guild, blank=True)

    def __str__(self):
        return self.character_name+': '+self.race+' '+self.job+' level '+str(self.level)+'. '
</code>```

My view.py file:

```<code>def characterprofile(request, pk):
    """ Método para mostrar el perfil de un personaje """
    template = '../templates/character/characterProfile.html'
    profile = Character.objects.get(pk=pk)
    guilds = profile.character_guilds.all()
    context = {
        'profile': profile,
        'guilds': guilds
    }
    return render (request, template, context)
</code>```

And my template.html:

```<code>{% extends 'base.html' %}

{% block content %}
    <header>
        <h2>{{ profile.character_name }}'s profile</h2>
    </header>
    <nav class="nav nav-pills nav-justified">
        <a class="nav-item nav-link" href="{% url 'characters' %}">Return</a>
    </nav>
    <br>
    <div class="container">
        <div class="container">
            {% if profile.avatar %}
            <img class="rounded" src="{{ profile.avatar.url }}" width="184" height="184">
            {% else %}
            <p>There is no avatar to display here.</p>
            {% endif %}
        </div>
        <br>
        <h4>Information</h4>
        <ul class="list-group list-group-flush-sm">
            <li class="list-group-item">Name: {{ profile.character_name }}</li>
            <li class="list-group-item">Level: {{ profile.level }}</li>
            <li class="list-group-item">Race: {{ profile.race }}</li>
            <li class="list-group-item">Gender: {{ profile.gender }}</li>
            <li class="list-group-item">Job: {{ profile.job }}</li>
            <li class="list-group-item">
                Guilds:
                {% for g in guilds %}
                    {{ g }}
                {%endfor%}
            </li>
        </ul>
        <br>
    </div>
    <br>
    <footer>
        <span>Copyright© 2020</span>
    </footer>
{% endblock %}
</code>```

Many thanks in advance!

答:
I think the problem is with your primary key, because with database when a row is deleted and you recreate a new one the primary key does not restart from 1.

For instance try somthing like this in your view function:

```<code>profile = Character.objects.get(character_name=character_name)
</code>```

hope it help

Body:
I'm having an issue displaying a ManyToManyField in a character profile template using Django.

The template has to show an avatar, alongside some information about the character, including a list of guilds this character had joined. But, when I try to display that list, it appears as if it is empty. I had a look into my site administration page, and that information is there, so I have confirmation that the data can be displayed in my template. I just don't know how. How could I handle that?

These are my models:

""" Modelos de la aplicación de personajes """
from django.db import models

class Guild(models.Model):
    """ Modelo del clan """
    guild_name = models.CharField(max_length=25)
    rank = models.PositiveSmallIntegerField()

    def __str__(self):
        return self.guild_name

class Character(models.Model):
    """ Modelo del personaje """
    character_name = models.CharField(max_length=25)
    level = models.PositiveSmallIntegerField()
    race = models.CharField(max_length=25)
    gender = models.CharField(max_length=25)
    job = models.CharField(max_length=25)
    avatar = models.ImageField(upload_to='', blank=True)
    character_guilds = models.ManyToManyField(Guild, blank=True)

    def __str__(self):
        return self.character_name+': '+self.race+' '+self.job+' level '+str(self.level)+'. '

My view.py file:

def characterprofile(request, pk):
    """ Método para mostrar el perfil de un personaje """
    template = '../templates/character/characterProfile.html'
    profile = Character.objects.get(pk=pk)
    guilds = profile.character_guilds.all()
    context = {
        'profile': profile,
        'guilds': guilds
    }
    return render (request, template, context)

And my template.html:

{% extends 'base.html' %}

{% block content %}

{{ profile.character_name }}'s profile

        Return

            {% if profile.avatar %}

            {% else %}

There is no avatar to display here.

            {% endif %}

Information

Name: {{ profile.character_name }}

Level: {{ profile.level }}

Race: {{ profile.race }}

Gender: {{ profile.gender }}

Job: {{ profile.job }}

                Guilds:
                {% for g in guilds %}
                    {{ g }}
                {%endfor%}

        Copyright© 2020

{% endblock %}

Many thanks in advance!

Body:
I think the problem is with your primary key, because with database when a row is deleted and you recreate a new one the primary key does not restart from 1.

For instance try somthing like this in your view function:

profile = Character.objects.get(character_name=character_name)

hope it help


问:
BizTalk 2013 R2 - Rate based Throttling on flooding messages
We have a solution that takes a message, and sends it to a web API.
Every day, an automatic procedure is run by another department that passes thousands of records into the messagebox, which seems to cause errors related to the API solicit-response port (strangely these errors don't allude to a timeout, but they do only trigger when such a massive quantity of data is sent downstream).

I've contacted the service supplier to determine the capacity of their API calls, so I'll be able to tailor our flow once I have a better idea.

I've been reading up on Rate Based Throttling this morning, and have a few questions I can't find an answer to;

If throttling is enabled, does it only process the Minimum number of samples/messages? If so, what happens to the remaining messages? I read somewhere they're queued in memory, but only of a max of 100, so where do all the others go?

If I have 2350 messages flood through in the space of 2 seconds, and I want to control the flow, would changing my Sampling Window duration down to 1 second and setting Throttling override to initiate throttling make a difference?

答:
If you are talking about Host Throttling setting, the remaining messages will be in the message box database and will show as being in a Dehydrated state.

You would have to test the throttling settings under load.  If you get it wrong it can be very bad.  I've come across one server where the settings were configured incorrectly and it is constantly throttling.


答:
.splice and .push mutate the array. Thus the current state then does not match the currently rendered version anymore. Instead, use .slice (or .filter) and [...old, new] for immutable stateupdates:

```<code> deleteId = index => {
  this.setState(({ ids }) => ({ ids: ids.filter((id, i) => i !== index) }));
 };

 uniqueIdCreatorHandler = increment => {
   const highest = Math.max(0, ...this.state.ids.map(it => it.id ));
   this.setState(({ ids }) => ({ ids: [...ids, { id: highest + increment }] }));
 };
</code>```

Title: Do I need to use PrevState even if I spread the state into a variable?

Body:
.splice and .push mutate the array. Thus the current state then does not match the currently rendered version anymore. Instead, use .slice (or .filter) and [...old, new] for immutable stateupdates:

 deleteId = index => {
  this.setState(({ ids }) => ({ ids: ids.filter((id, i) => i !== index) }));
 };

 uniqueIdCreatorHandler = increment => {
   const highest = Math.max(0, ...this.state.ids.map(it => it.id ));
   this.setState(({ ids }) => ({ ids: [...ids, { id: highest + increment }] }));
 };


问:
PHPmailer not connecting to office365 SMTP
I have a script that uses phpmailer to send emails via office 365 smtp. It had been working for the last year or so. Now I'm getting an error connecting to the server.

```<code>PHP Fatal error:  Uncaught PHPMailer\PHPMailer\Exception: SMTP Error: Could not connect to SMTP host. in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php:1898
Stack trace:
#0 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1725): PHPMailer\PHPMailer\PHPMailer->smtpConnect(Array)
#1 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1481): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Fri, 14 F...', 'This is a multi...')
#2 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1320): PHPMailer\PHPMailer\PHPMailer->postSend()
#3 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\submitform2.php(195): PHPMailer\PHPMailer\PHPMailer->send()
#4 {main}
thrown in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php on line 1898
</code>```

The script is as follows:

```<code>require 'vendor/autoload.php';
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port       = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth   = true;
$mail->Username = "user@company.org";
$mail->Password = "password";
$mail->SetFrom('sentfromemail@company.org', 'FromEmail');
//$mail->addAddress('user@company.org', 'ToEmail');
$mail->addAddress('user2@company.org', 'ToEmail');
$mail->addBCC('user2@company.org', 'ToBCCEmail');
$mail->SMTPDebug  = 3;
$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
$mail->Debugoutput = 'echo';
$mail->IsHTML(true);

$mail->Subject = 'Parish Registration Form';
$mail->Body    = $body;
$mail->AltBody = $body;

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else {
    echo 'Message has been sent';
}
</code>```

I've searched the internet for the connection settings associated with Office 365 and I see nothing wrong. Did something change on the Microsoft servers that I should know about but don't?

答:
It turns out to be a certificate error. When no certificate file is specified in php.ini the root certificate is supposed to be used. but it was not being used.

I had to add the following code to get it working:

```<code>$mail->SMTPOptions = array(
    'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
    )
);
</code>```

Body:
I have a script that uses phpmailer to send emails via office 365 smtp. It had been working for the last year or so. Now I'm getting an error connecting to the server.

PHP Fatal error:  Uncaught PHPMailer\PHPMailer\Exception: SMTP Error: Could not connect to SMTP host. in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php:1898
Stack trace:
#0 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1725): PHPMailer\PHPMailer\PHPMailer->smtpConnect(Array)
#1 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1481): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Fri, 14 F...', 'This is a multi...')
#2 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php(1320): PHPMailer\PHPMailer\PHPMailer->postSend()
#3 C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\submitform2.php(195): PHPMailer\PHPMailer\PHPMailer->send()
#4 {main}
thrown in C:\inetpub\wwwroot\Parishes_staging\ChristTheKing\vendor\phpmailer\phpmailer\src\PHPMailer.php on line 1898

The script is as follows:

require 'vendor/autoload.php';
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port       = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth   = true;
$mail->Username = "user@company.org";
$mail->Password = "password";
$mail->SetFrom('sentfromemail@company.org', 'FromEmail');
//$mail->addAddress('user@company.org', 'ToEmail');
$mail->addAddress('user2@company.org', 'ToEmail');
$mail->addBCC('user2@company.org', 'ToBCCEmail');
$mail->SMTPDebug  = 3;
$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
$mail->Debugoutput = 'echo';
$mail->IsHTML(true);

$mail->Subject = 'Parish Registration Form';
$mail->Body    = $body;
$mail->AltBody = $body;

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else {
    echo 'Message has been sent';
}

I've searched the internet for the connection settings associated with Office 365 and I see nothing wrong. Did something change on the Microsoft servers that I should know about but don't?

Body:
It turns out to be a certificate error. When no certificate file is specified in php.ini the root certificate is supposed to be used. but it was not being used.

I had to add the following code to get it working:

$mail->SMTPOptions = array(
    'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
    )
);


问:
Conditional execution of maven plugin depending on profile property
Given pom.xml

```<code><plugin>
    <groupId>com.myplugin</groupId>
    <artifactId>my-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <id>generate-file</id>
            <phase>package</phase>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <templateFile>
                    ${project.build.directory}/template.json
                </templateFile>
                <outputFile>
                    ${project.build.directory}/${env}-${server}-file.json
                </outputFile>
            </configuration>
        </execution>
        <execution>
            <id>send-file</id>
            <phase>package</phase>
            <goals>
                <goal>send</goal>
            </goals>
            <configuration>
                <file>
                    ${project.build.directory}/${env}-${server}-file.json
                </file>
            </configuration>
        </execution>
    </executions>
</plugin>

<profiles>
    <profile>
        <id>dev-a</id>
        <properties>
            <env>test</env>
            <server>serverA</server>
        </properties>
    </profile>
    <profile>
        <id>prod-a</id>
        <properties>
            <env>prod</env>
            <server>serverA</server>
        </properties>
    </profile>
    <profile>
        <id>dev-b</id>
        <properties>
            <env>test</env>
            <server>serverB</server>
        </properties>
    </profile>
    <profile>
        <id>prod-b</id>
        <properties>
            <env>prod</env>
            <server>serverB</server>
        </properties>
    </profile>
</profiles>
</code>```

How can I execute send-file task only when env property is equal to prod? I know I can move the plugin tag to dev-a and prod-a profiles in that example but I would need to duplicate that part for each profile which doesn't seem to be good solution. In my case I have many more profiles defined and the plugin execution definition is much longer, it would clutter my pom file a lot and make any changes very error-prone.
Is there any condition tag that I can pass to execution that would let me decide if it is invoked or not? Or maybe is there a possibility to exclude executions by id in profile tag?

Thanks for help!

答: If my-plugin is really your plugin (i.e. you wrote it), the easiest thing would be to just implement the logic you want inside the plugin.

Body:
Given pom.xml

<plugin>
    <groupId>com.myplugin</groupId>
    <artifactId>my-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <id>generate-file</id>
            <phase>package</phase>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <templateFile>
                    ${project.build.directory}/template.json
                </templateFile>
                <outputFile>
                    ${project.build.directory}/${env}-${server}-file.json
                </outputFile>
            </configuration>
        </execution>
        <execution>
            <id>send-file</id>
            <phase>package</phase>
            <goals>
                <goal>send</goal>
            </goals>
            <configuration>
                <file>
                    ${project.build.directory}/${env}-${server}-file.json
                </file>
            </configuration>
        </execution>
    </executions>
</plugin>

<profiles>
    <profile>
        <id>dev-a</id>
        <properties>
            <env>test</env>
            <server>serverA</server>
        </properties>
    </profile>
    <profile>
        <id>prod-a</id>
        <properties>
            <env>prod</env>
            <server>serverA</server>
        </properties>
    </profile>
    <profile>
        <id>dev-b</id>
        <properties>
            <env>test</env>
            <server>serverB</server>
        </properties>
    </profile>
    <profile>
        <id>prod-b</id>
        <properties>
            <env>prod</env>
            <server>serverB</server>
        </properties>
    </profile>
</profiles>

How can I execute send-file task only when env property is equal to prod? I know I can move the plugin tag to dev-a and prod-a profiles in that example but I would need to duplicate that part for each profile which doesn't seem to be good solution. In my case I have many more profiles defined and the plugin execution definition is much longer, it would clutter my pom file a lot and make any changes very error-prone.
Is there any condition tag that I can pass to execution that would let me decide if it is invoked or not? Or maybe is there a possibility to exclude executions by id in profile tag?

Thanks for help!


问:
Truth tables in code? How to structure state machine?
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

```<code>u8 newState[] = decisionTable[input1][input2][input3][input4];
</code>```

And then I could access the output values with:

```<code>setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );
</code>```

But in order to get that, it looks like I would have to do a fairly confusing table like so:

```<code>static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};
</code>```

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

```<code>#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))
</code>```

And that will let my truth table array look like this:

```<code>static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};
</code>```

And I can then access my truth table like so:

```<code>decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]
</code>```

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

答:
if your truth-table is all booleans, you could just collapse it to a list of pairs, e.g.

```<code>1111,0000
1110,0110
...
</code>```

for data compression, represent the values as bytes (two nybbles)...

where/how to store it for soft-coding in your particular embedded-system configuration, only you can say ;-)

OwnerDisplayName: HanClinto

ContentLicense: CC BY-SA 2.5

Body:
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

u8 newState[] = decisionTable[input1][input2][input3][input4];

And then I could access the output values with:

setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );

But in order to get that, it looks like I would have to do a fairly confusing table like so:

static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))

And that will let my truth table array look like this:

static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};

And I can then access my truth table like so:

decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

LastEditorDisplayName: Im safe against SQL injection

Body:
if your truth-table is all booleans, you could just collapse it to a list of pairs, e.g.

1111,0000
1110,0110
...

for data compression, represent the values as bytes (two nybbles)...

where/how to store it for soft-coding in your particular embedded-system configuration, only you can say ;-)

OwnerDisplayName: Steven A. Lowe


问:
Automatic documentation tool for eclipse Java
is there an automatic documentation tool for eclipse? (Like the Ghost Doc Tool)
I'm working in Java and i want a reccomended tool.

thanks

答: Found a nice tool http://jautodoc.sourceforge.net/</p>

ContentLicense: CC BY-SA 3.0


问:
Render components conditionally, based on items of deeply nested array
I have a React component that's receiving a data object returned from an API response.

I'm trying to write a function that accepts a field from that data response, checks an element inside of that field and iterates over it checking each object inside the array for the value of a specific alert.

If a value for a specific alert is found I need to render an Icon for that alert.

The data object looks like this:

```<code>location: {
  ...,
details: {
  summary: [
            {
             type: 'calling',
             icon: 'phone'
             },
             {
             type: 'power',
             icon: 'electric'
             },
             {
             type: 'water',
             icon: 'water-icon'
             },
           ]
        }
      }
</code>```

And here's the section where I'm trying to conditionally render the icons (this was my first pass and rudimentary attempt):

```<code>           <div>
            {location.alertDetails && (
                <IconBox title={`Alerts`}>
                  <IconSection>
                  {location.details.summary.includes(type === calling) &&
                   <CallIcon />
                   }
                   {location.details.summary.includes(type === power) &&
                   <ElectricIcon />
                   }
                  {location.details.summary.includes(type === water) &&
                   <WaterIcon />
                  }
                  </IconSection>
                </IconBox>
              )}
            </div>
</code>```

答:
You can use a map to easily iterate over these -</p>

```<code> <div>
   {location.alertDetails && location.details.summary.map(item =>{ item.icon && return  (
                <IconBox title={`Alerts`}>
                  <IconSection>
                  {location.details.summary.includes(type === calling) &&
                   <CallIcon />
                   }
                   {location.details.summary.includes(type === power) &&
                   <ElectricIcon />
                   }
                  {location.details.summary.includes(type === water) &&
                   <WaterIcon />
                  }
                  </IconSection>
                </IconBox>
    )})}
 </div>
</code>```

Body:
I have a React component that's receiving a data object returned from an API response.

I'm trying to write a function that accepts a field from that data response, checks an element inside of that field and iterates over it checking each object inside the array for the value of a specific alert.

If a value for a specific alert is found I need to render an Icon for that alert.

The data object looks like this:

location: {
  ...,
details: {
  summary: [
            {
             type: 'calling',
             icon: 'phone'
             },
             {
             type: 'power',
             icon: 'electric'
             },
             {
             type: 'water',
             icon: 'water-icon'
             },
           ]
        }
      }

And here's the section where I'm trying to conditionally render the icons (this was my first pass and rudimentary attempt):

            {location.alertDetails && (
                <IconBox title={`Alerts`}>
                  <IconSection>
                  {location.details.summary.includes(type === calling) &&
                   <CallIcon />
                   }
                   {location.details.summary.includes(type === power) &&
                   <ElectricIcon />
                   }
                  {location.details.summary.includes(type === water) &&
                   <WaterIcon />
                  }
                  </IconSection>
                </IconBox>
              )}

Body:
You can use a map to easily iterate over these -

 <div>
   {location.alertDetails && location.details.summary.map(item =>{ item.icon && return  (
                <IconBox title={`Alerts`}>
                  <IconSection>
                  {location.details.summary.includes(type === calling) &&
                   <CallIcon />
                   }
                   {location.details.summary.includes(type === power) &&
                   <ElectricIcon />
                   }
                  {location.details.summary.includes(type === water) &&
                   <WaterIcon />
                  }
                  </IconSection>
                </IconBox>
    )})}
 </div>


问:
500 error "Uncaught Error: Class '\XF\App' not found"
From yesterday evening I've got a fatal error on my site and I've seen in Error Log file that error:

```<code>[15-Feb-2020 13:40:22 UTC] PHP Fatal error:  Uncaught Error: Class '\XF\App' not found in /home/stealths/public_html/src/XF.php:361
Stack trace:
#0 /home/stealths/public_html/src/XF.php(352): XF::setupApp('\\XF\\App')
#1 /home/stealths/public_html/src/XF.php(169): XF::app()
#2 [internal function]: XF::handleException(Object(Error))
#3 {main}
thrown in /home/stealths/public_html/src/XF.php on line 361
</code>```

I don't know what I can do to resolve this problem.

答:
It looks like you posted this question on multiple websites, and have already received an answer on one of them. I'll cross-post the answer made by Mike, a XenForo developer who posted on the XenForo Forums for future potential readers.

It looks like the files haven't been uploaded properly. I'd reupload all of the XF files.

Body:
From yesterday evening I've got a fatal error on my site and I've seen in Error Log file that error:

[15-Feb-2020 13:40:22 UTC] PHP Fatal error:  Uncaught Error: Class '\XF\App' not found in /home/stealths/public_html/src/XF.php:361
Stack trace:
#0 /home/stealths/public_html/src/XF.php(352): XF::setupApp('\\XF\\App')
#1 /home/stealths/public_html/src/XF.php(169): XF::app()
#2 [internal function]: XF::handleException(Object(Error))
#3 {main}
thrown in /home/stealths/public_html/src/XF.php on line 361

I don't know what I can do to resolve this problem.


问:
SQL Server Procedure with dynamic IN operator and INT datatype
I have a SQL Server Table with some basic Sales information as follows

```<code>SaleID  |   TotalValue  |   PaymentMethod   |   User    |     Date
--------|---------------|-------------------|-----------|--------------
   1    |     10        |   CASH            |   USER 1  |   2020-01-01
   2    |     120       |   DEBIT CARD      |   USER 2  |   2020-01-01
   3    |     1000      |   CREDIT CARD     |   USER 2  |   2020-01-01
   4    |     305       |   CREDIT CARD     |   USER 1  |   2020-01-01
   5    |     15        |   CASH            |   USER 5  |   2020-01-01
</code>```

I need to write a Dynamic Procedure os something of the sort that's able to search for the sales information using an array of SaleIDs as a filter. It's a simple select query, as follows:

```<code>SELECT
     [SaleID]
    ,[TotalValue] as 'Total Value'
    ,[Date] as 'Date'
FROM
    [Sales]
WHERE
    [SaleID] in (1, 2, 3, 4)
</code>```

I created the following Stored Procedure so I can input an array of SalesID:

```<code>CREATE PROCEDURE [dbo].[usp_SearchSales]
(
      @SaleID NVARCHAR(max)
)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @ParameterDef NVARCHAR(500)

    SET @ParameterDef = '@SaleID NVARCHAR(max)'

SET @SQL = 'SELECT
                 [SaleID]
                ,[TotalValue]
                ,[PaymentMethod]
                ,[User]
                ,[Date]
            FROM
                [Sales]
            WHERE
                -1=-1'

IF @SaleID IS NOT NULL
SET @SQL = @SQL+ ' AND SaleID in (@SaleID)'

EXEC sp_Executesql @SQL, @ParameterDef, @SaleID = @SaleID

END

GO
</code>```

Then I execute the Procedure through the Exec command

```<code>EXEC [usp_SearchSales] @SaleID = '1, 2, 3, 4'
GO
</code>```

Then the procedure returns the following error uppon execution:

Msg 245, Level 16, State 1, Procedure usp_SearchSales, Line 26 [Batch Start Line 49]

Conversion failed when converting the nvarchar value '1, 2, 3, 4' to data type int.

Here is a SQL Query to create and insert some values on the designed table

```<code>CREATE TABLE [Sales] (
    [SaleID] int,
    [TotalValue] float,
    [PaymentMethod] varchar(50),
    [User] varchar(50),
    [Date] date
)

insert into sales values (1, 10, 'CASH', 'USER 1', '2020-01-01')
insert into sales values (2, 120, 'DEBIT CARD', 'USER 2', '2020-01-01')
insert into sales values (3, 10000, 'CREDIT CARD', 'USER 2', '2020-01-01')
insert into sales values (4, 305, 'CREDIT CARD', 'USER 1', '2020-01-01')
insert into sales values (5, 15, 'CASH', 'USER 5', '2020-01-01')
</code>```

I need some help to create a procedure, or something of the sort, where an array of SalesIDs gives me back the Sales informations of those Sales.

答:
change the SP like the following :
I changed SET @SQL = @SQL+ CONCAT(' AND SaleID in (',@SaleID,')') part of your query.
Regarding the injection, Dynamic queries are vulnerable to inject, I only fixed the issue you had.

```<code>alter PROCEDURE [dbo].[usp_SearchSales]
(
      @SaleID NVARCHAR(max)
)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @ParameterDef NVARCHAR(500)

    SET @ParameterDef = '@SaleID NVARCHAR(max)'

SET @SQL = 'SELECT
                 [SaleID]
                ,[TotalValue]
                ,[PaymentMethod]
                ,[User]
                ,[Date]
            FROM
                [Sales]
            WHERE
                -1=-1'

IF @SaleID IS NOT NULL
SET @SQL = @SQL+ CONCAT(' AND SaleID in (',@SaleID,')')
print @SQL

EXEC sp_Executesql @SQL, @ParameterDef, @SaleID = @SaleID

END

GO
</code>```

Another thing you can do is creating a User Defined Table and call it in SP, like the following :

```<code>CREATE TYPE [dbo].[udt_Sales] AS TABLE(
    [SaleID] [int] NULL
)
</code>```

and the SP would be like this :

```<code>CREATE PROCEDURE [dbo].[sp_Name]
(
    @Ids [dbo].[udt_Sales] READONLY
)
AS
BEGIN
SELECT [SaleID]
      ,[TotalValue]
      ,[PaymentMethod]
      ,[User]
      ,[Date]
FROM [Sales]
WHERE [SaleID] IN (SELECT * FROM @Ids)
END
</code>```

and the you can call the SP like the following :

```<code>DECLARE @IDs udt_Sales

INSERT INTO @IDs VALUES (1)
INSERT INTO @IDs VALUES (2)
INSERT INTO @IDs VALUES (3)
INSERT INTO @IDs VALUES (4)

EXECUTE usp_SearchSales @IDs
</code>```

This is much faster than Dynamic query.
hope it helps

Body:
I have a SQL Server Table with some basic Sales information as follows

SaleID  |   TotalValue  |   PaymentMethod   |   User    |     Date
--------|---------------|-------------------|-----------|--------------
   1    |     10        |   CASH            |   USER 1  |   2020-01-01
   2    |     120       |   DEBIT CARD      |   USER 2  |   2020-01-01
   3    |     1000      |   CREDIT CARD     |   USER 2  |   2020-01-01
   4    |     305       |   CREDIT CARD     |   USER 1  |   2020-01-01
   5    |     15        |   CASH            |   USER 5  |   2020-01-01

I need to write a Dynamic Procedure os something of the sort that's able to search for the sales information using an array of SaleIDs as a filter. It's a simple select query, as follows:

SELECT
     [SaleID]
    ,[TotalValue] as 'Total Value'
    ,[Date] as 'Date'
FROM
    [Sales]
WHERE
    [SaleID] in (1, 2, 3, 4)

I created the following Stored Procedure so I can input an array of SalesID:

CREATE PROCEDURE [dbo].[usp_SearchSales]
(
      @SaleID NVARCHAR(max)
)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @ParameterDef NVARCHAR(500)

    SET @ParameterDef = '@SaleID NVARCHAR(max)'

SET @SQL = 'SELECT
                 [SaleID]
                ,[TotalValue]
                ,[PaymentMethod]
                ,[User]
                ,[Date]
            FROM
                [Sales]
            WHERE
                -1=-1'

IF @SaleID IS NOT NULL
SET @SQL = @SQL+ ' AND SaleID in (@SaleID)'

EXEC sp_Executesql @SQL, @ParameterDef, @SaleID = @SaleID

END

GO

Then I execute the Procedure through the Exec command

EXEC [usp_SearchSales] @SaleID = '1, 2, 3, 4'
GO

Then the procedure returns the following error uppon execution:

Msg 245, Level 16, State 1, Procedure usp_SearchSales, Line 26 [Batch Start Line 49]

Conversion failed when converting the nvarchar value '1, 2, 3, 4' to data type int.

Here is a SQL Query to create and insert some values on the designed table

CREATE TABLE [Sales] (
    [SaleID] int,
    [TotalValue] float,
    [PaymentMethod] varchar(50),
    [User] varchar(50),
    [Date] date
)

insert into sales values (1, 10, 'CASH', 'USER 1', '2020-01-01')
insert into sales values (2, 120, 'DEBIT CARD', 'USER 2', '2020-01-01')
insert into sales values (3, 10000, 'CREDIT CARD', 'USER 2', '2020-01-01')
insert into sales values (4, 305, 'CREDIT CARD', 'USER 1', '2020-01-01')
insert into sales values (5, 15, 'CASH', 'USER 5', '2020-01-01')

I need some help to create a procedure, or something of the sort, where an array of SalesIDs gives me back the Sales informations of those Sales.

Body:
change the SP like the following :
I changed SET @SQL = @SQL+ CONCAT(' AND SaleID in (',@SaleID,')') part of your query.
Regarding the injection, Dynamic queries are vulnerable to inject, I only fixed the issue you had.

alter PROCEDURE [dbo].[usp_SearchSales]
(
      @SaleID NVARCHAR(max)
)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @ParameterDef NVARCHAR(500)

    SET @ParameterDef = '@SaleID NVARCHAR(max)'

SET @SQL = 'SELECT
                 [SaleID]
                ,[TotalValue]
                ,[PaymentMethod]
                ,[User]
                ,[Date]
            FROM
                [Sales]
            WHERE
                -1=-1'

IF @SaleID IS NOT NULL
SET @SQL = @SQL+ CONCAT(' AND SaleID in (',@SaleID,')')
print @SQL

EXEC sp_Executesql @SQL, @ParameterDef, @SaleID = @SaleID

END

GO

Another thing you can do is creating a User Defined Table and call it in SP, like the following :

CREATE TYPE [dbo].[udt_Sales] AS TABLE(
    [SaleID] [int] NULL
)

and the SP would be like this :

CREATE PROCEDURE [dbo].[sp_Name]
(
    @Ids [dbo].[udt_Sales] READONLY
)
AS
BEGIN
SELECT [SaleID]
      ,[TotalValue]
      ,[PaymentMethod]
      ,[User]
      ,[Date]
FROM [Sales]
WHERE [SaleID] IN (SELECT * FROM @Ids)
END

and the you can call the SP like the following :

DECLARE @IDs udt_Sales

INSERT INTO @IDs VALUES (1)
INSERT INTO @IDs VALUES (2)
INSERT INTO @IDs VALUES (3)
INSERT INTO @IDs VALUES (4)

EXECUTE usp_SearchSales @IDs

This is much faster than Dynamic query.
hope it helps


问:
How to pass values to a function which is a list item in Python
I want to pass a value as argument in a function which is a list item.

For example:

```<code>def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

l = [1,2,3, foo('want values here as arguments')]

def foo_bar():
    x = 0, y = 1
    print(“want to pass x and y inside: “ , l[3])
</code>```

Thanks ahead.

答:
You write

```<code>l = [1,2,3,foo]
</code>```

and later

```<code>print l[3](x,y)
</code>```

Body:
I want to pass a value as argument in a function which is a list item.

For example:

def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

l = [1,2,3, foo('want values here as arguments')]

def foo_bar():
    x = 0, y = 1
    print(“want to pass x and y inside: “ , l[3])

Thanks ahead.

Body:
You write

l = [1,2,3,foo]

and later

print l[3](x,y)


问:
Playframework inserting wrong date in database
I'm having a strage problem. In my form I'm using the jQuery datetime picker. This generates a string like 05/23/2011 07:33.

In my java code i'm using DateFormat to create a date object out of that string:

```<code>    System.out.println(execute);
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy kk:mm");
    Date date = null;
    try {
        date = df.parse(execute);
    } catch (ParseException e) {
        e.printStackTrace();
    }
</code>```

(execute is the string which contains the date).
In the console, println() is showing the right date. And I'm using that date object when I write an instane of a Model to the database. But once I call the save() function (from the model), the timestamp that is inserted in the database is completely wrong.

In this case it is: 2012-11-05 07:33:00 The time is correct, but the date is sometimes more than a year off!

Any ideas what's causing this?

答:
Are you sure about your date format "dd/MM/yyyy kk:mm"?

You get day/month/year but in "05/23/2011 07:33" it's month/day/year, isn't it?

Body:
I'm having a strage problem. In my form I'm using the jQuery datetime picker. This generates a string like 05/23/2011 07:33.

In my java code i'm using DateFormat to create a date object out of that string:

    System.out.println(execute);
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy kk:mm");
    Date date = null;
    try {
        date = df.parse(execute);
    } catch (ParseException e) {
        e.printStackTrace();
    }

(execute is the string which contains the date).
In the console, println() is showing the right date. And I'm using that date object when I write an instane of a Model to the database. But once I call the save() function (from the model), the timestamp that is inserted in the database is completely wrong.

In this case it is: 2012-11-05 07:33:00 The time is correct, but the date is sometimes more than a year off!

Any ideas what's causing this?


问:
Building JavaFX application as Singleton
I have JavaFX application built and used as desktop app with an installer which created a shortcut on desktop. It works perfectly fine, but whenever clicks on shortcut, it opens a new window. I want to make changes to the app to act as singleton and open the same window if it is already opened.

Can anyone help?

答: Each time you launch your application, you are creating another JVM. So what you want is  a way to ensure that, at most, only one JVM of your application is running. So you need a way to find the running JVMs. One way is the JPS utility. Its output includes the name of the class that you launched. You can run JPS from java code using class ProcessBuilder. Alternatively you could write an operating-system script, i.e. PowerShell for Windows or bash for linux, to launch your application which would first run JPS to see if the application wasn't already running.