问:
Cannot edit css of a class with variable
I am trying to get a line through  the li that i added when i click the li(like a grocery list).

```<code>$('document').ready(() => {
            let id = 1;

            $('.knop').click(() => {
                let boodschap = $('.tekst').val();
                let newli = `<li id="boodschap${id}"> ${boodschap}</li>`;
                $(".result").append(`${newli}`);
                id++;
            });

            $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });
                console.log(event.target.id);
            });
        });
</code>```

I know the problem is in this part:

```<code> $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });
</code>```

I dont get a error in my console. so im stuck.
but when i hard code the part where i put my ${target} it works.
you cant use a variable in the css function?
is there a way around this?

答:
So you need to strikeout an
 when it's clicked.

```<code>$('li').on('click', (evt)=>{
    let target = evt.target;
    $(target).css({'text-decoration': 'line-through'});
    console.log(evt.target.id);
}
</code>```

The main problem with your code is that you store target
's id, in a variable called target, rather than the target element itself. Misleading variable names can lead to confusion.

Body:
I am trying to get a line through  the li that i added when i click the li(like a grocery list).

$('document').ready(() => {
            let id = 1;

            $('.knop').click(() => {
                let boodschap = $('.tekst').val();
                let newli = `<li id="boodschap${id}"> ${boodschap}</li>`;
                $(".result").append(`${newli}`);
                id++;
            });

            $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });
                console.log(event.target.id);
            });
        });

I know the problem is in this part:

 $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });

I dont get a error in my console. so im stuck.
but when i hard code the part where i put my ${target} it works.
you cant use a variable in the css function?
is there a way around this?

Body:
So you need to strikeout an <li> when it's clicked.

$('li').on('click', (evt)=>{
    let target = evt.target;
    $(target).css({'text-decoration': 'line-through'});
    console.log(evt.target.id);
}

The main problem with your code is that you store target <li>'s id, in a variable called target, rather than the target element itself. Misleading variable names can lead to confusion.


来源: stackexchange

问:
Docker container cannot resolve dns
I'm trying to configure my docker container to see my local private rpm repository through http.  It cannot resolve the dns name and I'm probably not setting up DNS correctly on the host CENTOS 6.5 VM.

http://
  172.17.42.1

/repository/CENTOS/6/nginx/x86_64/repodata/repomd.xml:

[Errno 14] PYCURL ERROR 7 - > "couldn't connect to host"

bash-4.1# more /etc/yum.repos.d/nginx.repo

[nginx]
    name=nginx repo

baseurl=http://
      172.17.42.1/repository/CENTOS/$releasever/nginx/$basearch/

(can't connect to host)

gpgcheck=0
    enabled=1

The container /etc/resolv.conf contains this

bash-4.1# cat /etc/resolv.conf
    nameserver 192.168.64.2
    nameserver 192.168.64.129
    nameserver 127.0.0.1
    search localdomain eadis.local

When I try to add the domainname to the IP address it does not
  resolve.

Docker container IP address

eth0      Link encap:Ethernet  HWaddr 7E:EB:4C:25:F4:DA

             inet addr:172.17.0.7  Bcast:0.0.0.0  Mask:255.255.0.0

Host VM Docker server

docker0   Link encap:Ethernet  HWaddr FE:EF:63:A8:65:5C

inet addr:
    172.17.42.1

Bcast:0.0.0.0  Mask:255.255.0.0

eth3      Link encap:Ethernet  HWaddr 00:0C:29:10:0A:77

             inet addr:192.168.64.129  Bcast:192.168.64.255  Mask:255.255.255.0

[root@centos named]# cat /etc/resolv.conf

domain localdomain
        search localdomain eadis.local
        nameserver 192.168.64.129
        nameserver 192.168.64.2

答:
When you run your container with --net or --network, docker will use a self DNS server to discover services that runs with it. All DNS queries are sent to the docker engine.

In normal times (when using default network) you can use the --dns option on your run command. But when you run your images with a self-defined network, you must add your customize resolv.conf file to the container. You make one on your system and name it custom-resolv.conf.

In this file you can add your custom dns address and add it to your container.

```<code>nameserver 1.0.0.1
nameserver 4.2.2.4
</code>```

Then you must add this small part to your run command:

```<code>-v /path/to/file/custom-resolv.conf:/etc/resolv.conf:ro
</code>```

Use ro for read-only volume mapping. When your container is started, you can exec to your container and check the /etc/resolv.conf file which must be the same as custom-resolv.conf.

Now all of your DNS requests are sent to your DNS server.

ContentLicense: CC BY-SA 4.0

Title: Docker container cannot resolve dns

Body:
When you run your container with --net or --network, docker will use a self DNS server to discover services that runs with it. All DNS queries are sent to the docker engine.

In normal times (when using default network) you can use the --dns option on your run command. But when you run your images with a self-defined network, you must add your customize resolv.conf file to the container. You make one on your system and name it custom-resolv.conf.

In this file you can add your custom dns address and add it to your container.

nameserver 1.0.0.1
nameserver 4.2.2.4

Then you must add this small part to your run command:

-v /path/to/file/custom-resolv.conf:/etc/resolv.conf:ro

Use ro for read-only volume mapping. When your container is started, you can exec to your container and check the /etc/resolv.conf file which must be the same as custom-resolv.conf.

Now all of your DNS requests are sent to your DNS server.


问:
Vuejs 3 : components scope, and how to provide components to slots
I'd like in Vue 3 to be able to provide/overwrite existing components to slots by doing something like:

  <ProvideFun>

      Hello
      <FunA></FunA>

  </ProvideFun>
  <ProvideOtherFun>

      Hello
      <FunA></FunA>

  </ProvideOtherFun>
```

in order to be allowed to use some components (here <FunA>) inside others components (here <ProvideFun> and <ProvideOtherFun>). Note that ProvideFun and ProvideOtherFun may provide different versions of the <FunA> component.

How could I do something like that?

You can find a demo here.

答:
Option 1: Provide/inject components

The parent (i.e., ProvideFun or ProvideOtherFun) could provide its own component definition (named "comp") to be used in FunA:

<template>

    Provide fun

  <slot />
</template>
```
<pre class="lang-html prettyprint-override"><code><!-- ProvideOtherFun.vue -->
<script setup>
import { provide } from 'vue'
import CompB from './CompB.vue'

provide('comp', CompB)
</script>

<template>
  <h1>
    Provide other fun
  </h1>
  <slot />
</template>
</code>```

Make FunA.vue a <component> wrapper that injects the "comp" component definition from a parent:

<template>
  <component :is="comp" />
</template>
```
<p>This requires registering the <code>FunA</code> placeholder component before it could be used in <code>ProvideFun</code>/<code>ProvideOtherFun</code>:</p>
<pre class="lang-html prettyprint-override"><code><script setup>
import ProvideFun from './ProvideFun.vue'
import ProvideOtherFun from './ProvideOtherFun.vue'

import FunA from './FunA.vue'
</script>

<template>
  <ProvideFun>
    <p>
      Hello
      <FunA />
    </p>
  </ProvideFun>

  <ProvideOtherFun>
    <p>
      Hello
      <FunA />
    </p>
  </ProvideOtherFun>
</template>
</code>```

demo 1

Option 2: Components via slot props

Bind the CompA component definition as a slot prop (named "FunA") in ProvideFun.vue, and CompB in ProvideOtherFun.vue:

<template>
  <slot :FunA="CompA">
</template>
```
<pre class="lang-html prettyprint-override"><code><!-- ProvideOtherFun.vue -->
<script setup>
import CompB from './CompB.vue'
</script>

<template>
  <slot :FunA="CompB">
</template>
</code>```

Then use a <component> to render it in the parent:

<template>
  <ProvideFun>
    <template v-slot="{ FunA }">

        Hello
        <component :is="FunA" />

    </template>
  </ProvideFun>

  <ProvideOtherFun>
    <template v-slot="{ FunA }">

        Hello
        <component :is="FunA" />

    </template>
  </ProvideOtherFun>
</template>
```

demo 2

Body:
I'd like in Vue 3 to be able to provide/overwrite existing components to slots by doing something like:

  <ProvideFun>

      Hello
      <FunA></FunA>

  </ProvideFun>
  <ProvideOtherFun>

      Hello
      <FunA></FunA>

  </ProvideOtherFun>

in order to be allowed to use some components (here <FunA>) inside others components (here <ProvideFun> and <ProvideOtherFun>). Note that ProvideFun and ProvideOtherFun may provide different versions of the <FunA> component.

How could I do something like that?

You can find a <a href="https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cD5cbmltcG9ydCB7IHJlZiB9IGZyb20gJ3Z1ZSdcbmltcG9ydCBQcm92aWRlRnVuIGZyb20gJy4vUHJvdmlkZUZ1bi52dWUnXG5jb25zdCBtc2cgPSByZWYoJ0hlbGxvIFdvcmxkIScpXG48L3NjcmlwdD5cblxuPHRlbXBsYXRlPlxuICA8UHJvdmlkZUZ1bj5cbiAgICA8cD5cbiAgICBIZWxsb1xuICAgICAgPEZ1bkE+PC9GdW5BPlxuICAgIDwvcD5cbiAgPC9Qcm92aWRlRnVuPlxuPC90ZW1wbGF0ZT4iLCJpbXBvcnQtbWFwLmpzb24iOiJ7XG4gIFwiaW1wb3J0c1wiOiB7XG4gICAgXCJ2dWVcIjogXCJodHRwczovL3NmYy52dWVqcy5vcmcvdnVlLnJ1bnRpbWUuZXNtLWJyb3dzZXIuanNcIlxuICB9XG59IiwiUHJvdmlkZUZ1bi52dWUiOiI8c2NyaXB0IHNldHVwPlxuXHRpbXBvcnQgeyByZWYgfSBmcm9tICd2dWUnXG4gXHRpbXBvcnQgRnVuQSBmcm9tICcuL0Z1bkEudnVlJ1xuXG5cdGNvbnN0IG1zZyA9IHJlZignSGVsbG8gV29ybGQhJylcbjwvc2NyaXB0PlxuXG48dGVtcGxhdGU+XG4gIDxoMT5cbiAgICBGdW4gc3RhcnRzLlxuICA8L2gxPlxuICA8c2xvdD48L3Nsb3Q+XG48L3RlbXBsYXRlPiIsIkZ1bkEudnVlIjoiPHRlbXBsYXRlPlxuICA8cD5cbiAgICBJJ20gYSBzdXBlciBmdW4gY29tcG9uZW50LlxuICA8L3A+XG48L3RlbXBsYXRlPiJ9" rel="nofollow noreferrer">demo here.

Body:
Option 1: Provide/inject components

The parent (i.e., ProvideFun or ProvideOtherFun) could provide its own component definition (named "comp") to be used in FunA:

<!-- ProvideFun.vue -->
<script setup>
import { provide } from 'vue'
import CompA from './CompA.vue'

provide('comp', CompA)
</script>

<template>
  <h1>
    Provide fun
  </h1>
  <slot />
</template>

<!-- ProvideOtherFun.vue -->
<script setup>
import { provide } from 'vue'
import CompB from './CompB.vue'

provide('comp', CompB)
</script>

<template>
  <h1>
    Provide other fun
  </h1>
  <slot />
</template>

Make FunA.vue a <component> wrapper that injects the "comp" component definition from a parent:

<!-- FunA.vue -->
<script setup>
import { inject } from 'vue'

const comp = inject('comp')
</script>

<template>
  <component :is="comp" />
</template>

This requires registering the FunA placeholder component before it could be used in ProvideFun/ProvideOtherFun:

<script setup>
import ProvideFun from './ProvideFun.vue'
import ProvideOtherFun from './ProvideOtherFun.vue'

import FunA from './FunA.vue'
</script>

<template>
  <ProvideFun>
    <p>
      Hello
      <FunA />
    </p>
  </ProvideFun>

  <ProvideOtherFun>
    <p>
      Hello
      <FunA />
    </p>
  </ProvideOtherFun>
</template>

<a href="https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cD5cbmltcG9ydCBQcm92aWRlRnVuIGZyb20gJy4vUHJvdmlkZUZ1bi52dWUnXG5pbXBvcnQgUHJvdmlkZU90aGVyRnVuIGZyb20gJy4vUHJvdmlkZU90aGVyRnVuLnZ1ZSdcbmltcG9ydCBGdW5BIGZyb20gJy4vRnVuQS52dWUnXG48L3NjcmlwdD5cblxuPHRlbXBsYXRlPlxuICA8UHJvdmlkZUZ1bj5cbiAgICA8cD5cbiAgICAgIEhlbGxvXG4gICAgICA8RnVuQSAvPlxuICAgIDwvcD5cbiAgPC9Qcm92aWRlRnVuPlxuICBcbiAgPFByb3ZpZGVPdGhlckZ1bj5cbiAgICA8cD5cbiAgICAgIEhlbGxvXG4gICAgICA8RnVuQSAvPlxuICAgIDwvcD5cbiAgPC9Qcm92aWRlT3RoZXJGdW4+XG48L3RlbXBsYXRlPiIsImltcG9ydC1tYXAuanNvbiI6IntcbiAgXCJpbXBvcnRzXCI6IHtcbiAgICBcInZ1ZVwiOiBcImh0dHBzOi8vc2ZjLnZ1ZWpzLm9yZy92dWUucnVudGltZS5lc20tYnJvd3Nlci5qc1wiXG4gIH1cbn0iLCJQcm92aWRlRnVuLnZ1ZSI6IjxzY3JpcHQgc2V0dXA+XG5pbXBvcnQgeyBwcm92aWRlIH0gZnJvbSAndnVlJ1xuaW1wb3J0IENvbXBBIGZyb20gJy4vQ29tcEEudnVlJ1xucHJvdmlkZSgnY29tcCcsIENvbXBBKVxuPC9zY3JpcHQ+XG5cbjx0ZW1wbGF0ZT5cbiAgPGgxPlxuICAgIFByb3ZpZGUgZnVuXG4gIDwvaDE+XG4gIDxzbG90IC8+XG48L3RlbXBsYXRlPiIsIkZ1bkEudnVlIjoiPHNjcmlwdCBzZXR1cD5cbmltcG9ydCB7IGluamVjdCB9IGZyb20gJ3Z1ZSdcbmNvbnN0IGNvbXAgPSBpbmplY3QoJ2NvbXAnKVxuPC9zY3JpcHQ+XG48dGVtcGxhdGU+XG4gIDxjb21wb25lbnQgOmlzPVwiY29tcFwiIC8+XG48L3RlbXBsYXRlPlxuIiwiUHJvdmlkZU90aGVyRnVuLnZ1ZSI6IjxzY3JpcHQgc2V0dXA+XG5pbXBvcnQgeyBwcm92aWRlIH0gZnJvbSAndnVlJ1xuaW1wb3J0IENvbXBCIGZyb20gJy4vQ29tcEIudnVlJ1xucHJvdmlkZSgnY29tcCcsIENvbXBCKVxuPC9zY3JpcHQ+XG5cbjx0ZW1wbGF0ZT5cbiAgPGgxPlxuICAgIFByb3ZpZGUgb3RoZXIgZnVuXG4gIDwvaDE+XG4gIDxzbG90IC8+XG48L3RlbXBsYXRlPiIsIkNvbXBBLnZ1ZSI6Ijx0ZW1wbGF0ZT5cbiAgPHA+XG4gICAgSSdtIGEgc3VwZXIgZnVuIGNvbXBvbmVudC5cbiAgPC9wPlxuPC90ZW1wbGF0ZT4iLCJDb21wQi52dWUiOiI8dGVtcGxhdGU+XG4gIDxwPlxuICAgIEknbSBhbm90aGVyIGNvbXBvbmVudC5cbiAgPC9wPlxuPC90ZW1wbGF0ZT4ifQ==" rel="nofollow noreferrer">demo 1

Option 2: Components via slot props

Bind the CompA component definition as a slot prop (named "FunA") in ProvideFun.vue, and CompB in ProvideOtherFun.vue:

<!-- ProvideFun.vue -->
<script setup>
import CompA from './CompA.vue'
</script>

<template>
  <slot :FunA="CompA">
</template>

<!-- ProvideOtherFun.vue -->
<script setup>
import CompB from './CompB.vue'
</script>

<template>
  <slot :FunA="CompB">
</template>

Then use a <component> to render it in the parent:

<script setup>
import ProvideFun from './ProvideFun.vue'
import ProvideOtherFun from './ProvideOtherFun.vue'
</script>

<template>
  <ProvideFun>
    <template v-slot="{ FunA }">
      <p>
        Hello
        <component :is="FunA" />
      </p>
    </template>
  </ProvideFun>

  <ProvideOtherFun>
    <template v-slot="{ FunA }">
      <p>
        Hello
        <component :is="FunA" />
      </p>
    </template>
  </ProvideOtherFun>
</template>

<a href="https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cD5cbmltcG9ydCBQcm92aWRlRnVuIGZyb20gJy4vUHJvdmlkZUZ1bi52dWUnXG5pbXBvcnQgUHJvdmlkZU90aGVyRnVuIGZyb20gJy4vUHJvdmlkZU90aGVyRnVuLnZ1ZSdcbjwvc2NyaXB0PlxuXG48dGVtcGxhdGU+XG4gIDxQcm92aWRlRnVuPlxuICAgIDx0ZW1wbGF0ZSB2LXNsb3Q9XCJ7IEZ1bkEgfVwiPlxuICAgICAgPHA+XG4gICAgICBcdEhlbGxvXG4gICAgICAgIDxjb21wb25lbnQgOmlzPVwiRnVuQVwiIC8+XG4gICAgICA8L3A+XG4gICAgPC90ZW1wbGF0ZT5cbiAgPC9Qcm92aWRlRnVuPlxuICBcbiAgPFByb3ZpZGVPdGhlckZ1bj5cbiAgICA8dGVtcGxhdGUgdi1zbG90PVwieyBGdW5BIH1cIj5cbiAgICAgIDxwPlxuICAgICAgXHRIZWxsb1xuICAgICAgICA8Y29tcG9uZW50IDppcz1cIkZ1bkFcIiAvPlxuICAgICAgPC9wPlxuICAgIDwvdGVtcGxhdGU+XG4gIDwvUHJvdmlkZU90aGVyRnVuPlxuPC90ZW1wbGF0ZT4iLCJpbXBvcnQtbWFwLmpzb24iOiJ7XG4gIFwiaW1wb3J0c1wiOiB7XG4gICAgXCJ2dWVcIjogXCJodHRwczovL3NmYy52dWVqcy5vcmcvdnVlLnJ1bnRpbWUuZXNtLWJyb3dzZXIuanNcIlxuICB9XG59IiwiUHJvdmlkZUZ1bi52dWUiOiI8c2NyaXB0IHNldHVwPlxuIFx0aW1wb3J0IENvbXBBIGZyb20gJy4vQ29tcEEudnVlJ1xuPC9zY3JpcHQ+XG5cbjx0ZW1wbGF0ZT5cbiAgPGgxPlxuICAgIFByb3ZpZGUgZnVuXG4gIDwvaDE+XG4gIDxzbG90IDpGdW5BPVwiQ29tcEFcIj48L3Nsb3Q+XG48L3RlbXBsYXRlPiIsIlByb3ZpZGVPdGhlckZ1bi52dWUiOiI8c2NyaXB0IHNldHVwPlxuIFx0aW1wb3J0IENvbXBCIGZyb20gJy4vQ29tcEIudnVlJ1xuPC9zY3JpcHQ+XG5cbjx0ZW1wbGF0ZT5cbiAgPGgxPlxuICAgIFByb3ZpZGUgb3RoZXIgZnVuXG4gIDwvaDE+XG4gIDxzbG90IDpGdW5BPVwiQ29tcEJcIj48L3Nsb3Q+XG48L3RlbXBsYXRlPiIsIkNvbXBBLnZ1ZSI6Ijx0ZW1wbGF0ZT5cbiAgPHA+XG4gICAgSSdtIGEgc3VwZXIgZnVuIGNvbXBvbmVudC5cbiAgPC9wPlxuPC90ZW1wbGF0ZT4iLCJDb21wQi52dWUiOiI8dGVtcGxhdGU+XG4gIDxwPlxuICAgIEknbSBhbm90aGVyIGNvbXBvbmVudC5cbiAgPC9wPlxuPC90ZW1wbGF0ZT4ifQ==" rel="nofollow noreferrer">demo 2


问:
What the heck is this: background-image: url("/images/sprites.png?v=3");

Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

```<code>/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }
</code>```

I've seen this used on link tags also on http://html5boilerplate.com/:

```<code>   <link rel="stylesheet" href="css/style.css?v=2">
</code>```

答: The URL could refer to a web server that directs the request to a script (e.g. using apache's mod_rewrite), but more likely, the query string is used to make the URL different from a previous version without modifying the actual location, thereby causing browser caches to see it as a different image.</p>

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }

I've seen this used on link tags also on http://html5boilerplate.com/:

   <link rel="stylesheet" href="css/style.css?v=2">


问:
PHP Websocket failed: Error during WebSocket handshake: net::ERR_CONNECTION_CLOSED (anonymous)
i learning the websocket in PHP but i don't know why have this handshake error.

My client.html :

```<code><html>
<body>
    <div id="root"></div>
    <script>
        var host = 'ws://127.0.0.1:8020/';
        var socket = new WebSocket(host);
        socket.onmessage = function(e) {
            console.log(e.data)
        };
    </script>
</body>
</html>
</code>```

And server.php :

```<code><?php

$address = "127.0.0.1";
$port = 8020;

$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,$address,$port) or die('bind error');
socket_listen($socket) or die('listen error');
$client = socket_accept($socket) or die('accept error');

$socketread = socket_read($client,5000) or die('Failed to read');

preg_match("#Sec-WebSocket-Key: (.*)\r\n#",$socketread,$match);
$key = base64_encode(sha1($match[1].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11',true));

$header = "HTTP/1.1 101 Switching Protocols\r\n";
$header .= "Upgrade: websocket\r\n";
$header .= "Connection: Upgrade\r\n";
$header .= "Sec-WebSocket-Accept: $key\r\n";
$header .= "Sec-WebSocket-Version: 13\r\n";

var_dump($header);
socket_write($client,$header,strlen($header));

$msg = "connected";
socket_write($client,$msg,strlen($msg));
socket_close($socket);
</code>```

However, I followed the Mozilla documentation on the handshake :/

Thank you for that.

Body:
i learning the websocket in PHP but i don't know why have this handshake error.

My client.html :

And server.php :

<?php

$address = "127.0.0.1";
$port = 8020;

$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,$address,$port) or die('bind error');
socket_listen($socket) or die('listen error');
$client = socket_accept($socket) or die('accept error');

$socketread = socket_read($client,5000) or die('Failed to read');

preg_match("#Sec-WebSocket-Key: (.*)\r\n#",$socketread,$match);
$key = base64_encode(sha1($match[1].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11',true));

$header = "HTTP/1.1 101 Switching Protocols\r\n";
$header .= "Upgrade: websocket\r\n";
$header .= "Connection: Upgrade\r\n";
$header .= "Sec-WebSocket-Accept: $key\r\n";
$header .= "Sec-WebSocket-Version: 13\r\n";

var_dump($header);
socket_write($client,$header,strlen($header));

$msg = "connected";
socket_write($client,$msg,strlen($msg));
socket_close($socket);

However, I followed the Mozilla documentation on the handshake :/

Thank you for that.

Body:
Your request and still relevant ?

I send :

$key = base64_encode(sha1($match[1].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11',true));
$header = "HTTP/1.1 101 Switching Protocols\n\r"
                        ."Upgrade: websocket\n\r"
                        ."Connection: Upgrade\n\r"
                        ."Sec-WebSocket-Accept: ".base64_encode(sha1($cartouche['Sec-WebSocket-Key'].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true))."\n\n\r";

I end up with 2 \n\n\r.

this part can't work :

$msg = "connected";
socket_write($client,$msg,strlen($msg));
socket_close($socket);

You must respect the frame

 0               1               2               3
 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len |    Extended payload length    |
|I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
|N|V|V|V|       |S|             |   (if payload len==126/127)   |
| |1|2|3|       |K|             |                               |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
 4               5               6               7
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
|     Extended payload length continued, if payload len == 127  |
+ - - - - - - - - - - - - - - - +-------------------------------+
 8               9               10              11
+ - - - - - - - - - - - - - - - +-------------------------------+
|                               |Masking-key, if MASK set to 1  |
+-------------------------------+-------------------------------+
 12              13              14              15
+-------------------------------+-------------------------------+
| Masking-key (continued)       |          Payload Data         |
+-------------------------------- - - - - - - - - - - - - - - - +
:                     Payload Data continued ...                :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
|                     Payload Data continued ...                |
+---------------------------------------------------------------+


问:
Docker fails to start on Windows 11 with WSL
I searched on SO for similar questions already, and none of the answers helped.

I installed and uninstalled docker many times and restarted every time. I set the env variable, and I can run docker, and see that it's installed in terminal, but the GUI won't startup.

This is the error I get when trying to run a hello world command.

docker: error during connect: In the default daemon configuration on Windows, the docker client must be run with elevated privileges to connect.: Post "http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/containers/create": open //./pipe/docker_engine: The system cannot find the file specified.
```

I am running it on a Windows 11 Home version.

Any help is appreciated.

答:
Seems like and issue with the new Docker release. After I downgraded I was able to get it too work. Docker version 4.4.4.

Make sure you allow virtualization too, by running the following command in powershell as Admin: bcdedit /set hypervisorlaunchtype auto

Body:
I searched on SO for similar questions already, and none of the answers helped.

I installed and uninstalled docker many times and restarted every time. I set the env variable, and I can run docker, and see that it's installed in terminal, but the GUI won't startup.

This is the error I get when trying to run a hello world command.

docker: error during connect: In the default daemon configuration on Windows, the docker client must be run with elevated privileges to connect.: Post "http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/containers/create": open //./pipe/docker_engine: The system cannot find the file specified.

I am running it on a Windows 11 Home version.

Any help is appreciated.


问:
SQL - Counting users that have multiple transactions and have at least one transaction that has been made within 7 days interval of the other one
Dataset Here is the task : Count users that have multiple transactions and have at least one transaction that has been made within 7 days interval of the other one.

Structure of dataset: Row, userId, orderId, date

Date is formatted as YYYY-MM-DDTHH:MM:SS Example: 2016-09-16T11:32:06

I have completed the first part (counting users with multiple transactions), but I do not know how to do the second part in the same query. I will be thankful for help.

Here is the console:

```<code>query = '''
SELECT COUNT(*)
FROM
  (SELECT userId FROM `dataset` GROUP BY userId HAVING COUNT(orderId) > 1)
'''

project_id = 'acdefg'

df = pd.io.gbq.read_gbq(query, project_id=project_id, dialect='standard')
display(df)
</code>```

答:
To solve this issue you want to be able to compare each record to a previous record: when was the last order from the same user. This hints to the use of partitions and window functions, in this case LAG.

A possible way to solve the problem is to organise records per user and order them by orderDate and then for each record have a look at the record just above:

```<code>WITH intermediate_table AS (
    SELECT
        userId,
        orderDate,
        LAG(orderDate)
            OVER (PARTITION BY userId ORDER BY orderDate) -- this is where we pick the orderDate of the record right above, once the orders are organized by userId and ordered by orderDate
    FROM `dataset.table`
)

SELECT userId
FROM intermediate_table
WHERE DATE_DIFF(orderDate, previous_order, DAY) <= 7
GROUP BY userId
</code>```

Once orderDate and previous_order info are gathered in the same record, it's easy to compare them and see if there is less than 7 days between the two.

(GROUP BY is used for returning userIds only once in the resulting table)

Body:
Dataset Here is the task : Count users that have multiple transactions and have at least one transaction that has been made within 7 days interval of the other one.

Structure of dataset: Row, userId, orderId, date

Date is formatted as YYYY-MM-DDTHH:MM:SS Example: 2016-09-16T11:32:06

I have completed the first part (counting users with multiple transactions), but I do not know how to do the second part in the same query. I will be thankful for help.

Here is the console:

query = '''
SELECT COUNT(*)
FROM
  (SELECT userId FROM `dataset` GROUP BY userId HAVING COUNT(orderId) > 1)
'''

project_id = 'acdefg'

df = pd.io.gbq.read_gbq(query, project_id=project_id, dialect='standard')
display(df)

Body:
To solve this issue you want to be able to compare each record to a previous record: when was the last order from the same user. This hints to the use of partitions and window functions, in this case LAG.

A possible way to solve the problem is to organise records per user and order them by orderDate and then for each record have a look at the record just above:

WITH intermediate_table AS (
    SELECT
        userId,
        orderDate,
        LAG(orderDate)
            OVER (PARTITION BY userId ORDER BY orderDate) -- this is where we pick the orderDate of the record right above, once the orders are organized by userId and ordered by orderDate
    FROM `dataset.table`
)

SELECT userId
FROM intermediate_table
WHERE DATE_DIFF(orderDate, previous_order, DAY) <= 7
GROUP BY userId

Once orderDate and previous_order info are gathered in the same record, it's easy to compare them and see if there is less than 7 days between the two.

(GROUP BY is used for returning userIds only once in the resulting table)


问:
dbeaver mysql access denied
Can anyone tell me why I got an alert with the access denied error?
I tried to create a mysql database and I confidently sure I entered the correct password for root yet I still got this error.

However, based on the mysql documentation for troubleshooting, my error specified that I did not enter the correct password which in fact I did not.

Mysql documentation

https://dev.mysql.com/doc/refman/5.5/en/problems-connecting.html

Also , I tried to run this command sudo mysql -u root -pand it also show me the same error.

P.S Because my reputation is too low, I can't attach the full image.

答:
I had this problem on Beekeeper and DBeaver.  It was driving me INSANE.  I literally copied the password and was testing the connections manually and it was working perfectly. Annoyingly this server was working perfectly with MySQL workbench on Windows before I migrated over to Fedora.

So I needed to set the "SSH" section so that it would log me in to the other device.  That test connection worked perfectly.  But STILL no success.  "Password failure" an incredibly inaccurate error message...

Turns out after enabling the SSH connection I forgot to change the "Server host" variable from it's IP (192...) to 'localhost'.  Now it works perfectly.

Title: dbeaver mysql access denied


问:
How can I insert a key-value pair in an unordered map that is present in the innermost struct in rust programming language?
This is my data model:

```<code>pub struct RaffleDetails {
    prize: Balance,
    start: Timestamp,
    end: Timestamp,
    participants: UnorderedMap<AccountId, Balance>,
}

pub struct RaffleDapp {
    raffles: UnorderedMap<AccountId, RaffleDetails>,
}
</code>```

How can I insert a key-value pair in the 'participants' variable?

I tried self.raffles.get(&raffle_account_id).unwrap().participants.insert(&env::predecessor_account_id(), &confidence); but it's not persistent.

References:
UnorderedMap
NEAR Rust SDK

答:
You need to make sure you are updating the RaffleDetails instance that is in the map, not a copy/clone of it.

I'm not familiar with UnorderedMap, but it seems to me the get() method returns a copy of the value that is in the map, so you are only updating the copied value. I don't know if UnorderedMap allows you to mutate a value in it directly (skimming through the docs, I don't see such a method). What you can do though is re-insert the modified RaffleDetails into the raffles map (so as to replace the old one with the modified one).

I'm talking about something like this (I haven't tested compiling it):

```<code>let o = self.raffles.get(&raffle_account_id);
if let copied_rd = Some(o) {
    copied_rd.participants.insert(&env::predecessor_account_id(), &confidence);
    self.raffles.insert(&raffle_account_id, &copied_rd);
}
</code>```

Body:
This is my data model:

pub struct RaffleDetails {
    prize: Balance,
    start: Timestamp,
    end: Timestamp,
    participants: UnorderedMap<AccountId, Balance>,
}

pub struct RaffleDapp {
    raffles: UnorderedMap<AccountId, RaffleDetails>,
}

How can I insert a key-value pair in the 'participants' variable?

I tried self.raffles.get(&raffle_account_id).unwrap().participants.insert(&env::predecessor_account_id(), &confidence); but it's not persistent.

References:
UnorderedMap
NEAR Rust SDK

Body:
You need to make sure you are updating the RaffleDetails instance that is in the map, not a copy/clone of it.

I'm not familiar with UnorderedMap, but it seems to me the get() method returns a copy of the value that is in the map, so you are only updating the copied value. I don't know if UnorderedMap allows you to mutate a value in it directly (skimming through the docs, I don't see such a method). What you can do though is re-insert the modified RaffleDetails into the raffles map (so as to replace the old one with the modified one).

I'm talking about something like this (I haven't tested compiling it):

let o = self.raffles.get(&raffle_account_id);
if let copied_rd = Some(o) {
    copied_rd.participants.insert(&env::predecessor_account_id(), &confidence);
    self.raffles.insert(&raffle_account_id, &copied_rd);
}


问:
How to get an element in a map and change it
How to get an element in a map and change it? For example, if I have:

```<code>{'a', 100},  {'b', 200},  {'c', 300},  {'d', 400},  {'e', 500}
</code>```

I want to get to the value of 'a' and change it from 100 to 105.

答:
```<code>map<char, int>::iterator it = m.find('a');
if (it != m.end() {
    it->second = 105;
</code>```

Body:
How to get an element in a map and change it? For example, if I have:

{'a', 100},  {'b', 200},  {'c', 300},  {'d', 400},  {'e', 500}

I want to get to the value of 'a' and change it from 100 to 105.


问:
Get "Component auth has not been registered yet" when using Firebase authentication from Angular app
I'm trying to add authentication to my Angular/Firebase app. I got it working no-problem in a small demo app, but when I try to add it to my real Angular application, I get "Component auth has not been registered yet" console errors in the browser.

To narrow the issue down, I copied this minimal authentication component from the Firebase "angularfire" samples ():

import { Component, OnInit, OnDestroy, PLATFORM_ID } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from '@firebase/app-compat';
import { Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
import { trace } from '@angular/fire/compat/performance';
import { Inject } from '@angular/core';
import { isPlatformServer } from '@angular/common';

@Component({
  selector: 'app-auth',
  template: `

      Auth!
      {{ (auth.user | async)?.uid | json }}
      {{ (auth.credential | async)?.additionalUserInfo?.isNewUser | json }}
      <button (click)="login()" *ngIf="showLoginButton">Log in with Google</button>
      <button (click)="loginAnonymously()" *ngIf="showLoginButton">Log in anonymously</button>
      <button (click)="logout()" *ngIf="showLogoutButton">Log out</button>

  `,
  styles: []
})
export class AuthComponent implements OnInit, OnDestroy {

  private readonly userDisposable: Subscription | undefined;

  showLoginButton = false;
  showLogoutButton = false;

  constructor(public readonly auth: AngularFireAuth, @Inject(PLATFORM_ID) platformId: object) {
    if (!isPlatformServer(platformId)) {
      this.userDisposable = this.auth.authState.pipe(
        trace('auth'),
        map(u => !!u)
      ).subscribe(isLoggedIn => {
        this.showLoginButton = !isLoggedIn;
        this.showLogoutButton = isLoggedIn;
      });
    }
  }

  ngOnInit(): void { }

  ngOnDestroy(): void {
    if (this.userDisposable) {
      this.userDisposable.unsubscribe();
    }
  }

  async login() {
    const user = await this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
    // TODO sign into offline app
  }

  async loginAnonymously() {
    const user = await this.auth.signInAnonymously();
    // TODO sign into offline app
  }

  logout() {
    this.auth.signOut();
    // TODO sign out of offline app
  }

}```
</div>
</div>
</p>
<p>The imports section of my app.module.ts looks like this (edited):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  imports: [
    AppRoutingModule,
    ...
    AngularFireModule.initializeApp(environment.firebase),
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideAnalytics(() => getAnalytics()),
    provideAuth(() => getAuth()),
    provideFirestore(() => getFirestore()),
    provideFunctions(() => getFunctions()),
  ],</code>```

The console error that I'm seeing looks like this:

zone.js:182 Uncaught Error: Component auth has not been registered yet
at Provider.initialize (index.esm2017.js:232:19)
at new Auth (index.esm2017.js:651:35)
at Component.instance.INTERNAL.registerComponent.firebase_component__WEBPACK_IMPORTED_MODULE_3_.Component.setServiceProps.ActionCodeInfo.Operation.EMAIL_SIGNIN [as instanceFactory] (index.esm2017.js:969:16)
at Provider.getOrInitializeService (index.esm2017.js:290:39)
at Provider.getImmediate (index.esm2017.js:128:29)
at FirebaseAppImpl._getService (index.esm2017.js:83:1)
at FirebaseAppImpl.firebaseAppImpl. [as auth] (index.esm2017.js:291:1)
at angular-fire-compat-auth.js:59:51
at ZoneDelegate.invoke (zone.js:372:1)
at Zone.run (zone.js:134:1)

I've examined the Authentication settings of my app in the Firebase console, and they're identical for what I have set in my demo app, which works.

Any suggestions?

答:
Wew, that took hours and hours or work to narrow down the issue!

I finally figured out that the problem was that I had "@firebase/app" in my dependencies and that was causing the error. I'm guessing that it conflicted with the "@angular/fire" package, or something similar. I removed it, and Firebase authentication is now working in my app.

Body:
I'm trying to add authentication to my Angular/Firebase app. I got it working no-problem in a small demo app, but when I try to add it to my real Angular application, I get "Component auth has not been registered yet" console errors in the browser.

To narrow the issue down, I copied this minimal authentication component from the Firebase "angularfire" samples ():

import { Component, OnInit, OnDestroy, PLATFORM_ID } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from '@firebase/app-compat';
import { Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
import { trace } from '@angular/fire/compat/performance';
import { Inject } from '@angular/core';
import { isPlatformServer } from '@angular/common';

@Component({
  selector: 'app-auth',
  template: `

      Auth!
      {{ (auth.user | async)?.uid | json }}
      {{ (auth.credential | async)?.additionalUserInfo?.isNewUser | json }}
      <button (click)="login()" *ngIf="showLoginButton">Log in with Google</button>
      <button (click)="loginAnonymously()" *ngIf="showLoginButton">Log in anonymously</button>
      <button (click)="logout()" *ngIf="showLogoutButton">Log out</button>

  `,
  styles: []
})
export class AuthComponent implements OnInit, OnDestroy {

  private readonly userDisposable: Subscription | undefined;

  showLoginButton = false;
  showLogoutButton = false;

  constructor(public readonly auth: AngularFireAuth, @Inject(PLATFORM_ID) platformId: object) {
    if (!isPlatformServer(platformId)) {
      this.userDisposable = this.auth.authState.pipe(
        trace('auth'),
        map(u => !!u)
      ).subscribe(isLoggedIn => {
        this.showLoginButton = !isLoggedIn;
        this.showLogoutButton = isLoggedIn;
      });
    }
  }

  ngOnInit(): void { }

  ngOnDestroy(): void {
    if (this.userDisposable) {
      this.userDisposable.unsubscribe();
    }
  }

  async login() {
    const user = await this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
    // TODO sign into offline app
  }

  async loginAnonymously() {
    const user = await this.auth.signInAnonymously();
    // TODO sign into offline app
  }

  logout() {
    this.auth.signOut();
    // TODO sign out of offline app
  }

}

The imports section of my app.module.ts looks like this (edited):

  imports: [
    AppRoutingModule,
    ...
    AngularFireModule.initializeApp(environment.firebase),
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideAnalytics(() => getAnalytics()),
    provideAuth(() => getAuth()),
    provideFirestore(() => getFirestore()),
    provideFunctions(() => getFunctions()),
  ],

The console error that I'm seeing looks like this:

zone.js:182 Uncaught Error: Component auth has not been registered yet
at Provider.initialize (index.esm2017.js:232:19)
at new Auth (index.esm2017.js:651:35)
at Component.instance.INTERNAL.registerComponent.firebase_component__WEBPACK_IMPORTED_MODULE_3_.Component.setServiceProps.ActionCodeInfo.Operation.EMAIL_SIGNIN [as instanceFactory] (index.esm2017.js:969:16)
at Provider.getOrInitializeService (index.esm2017.js:290:39)
at Provider.getImmediate (index.esm2017.js:128:29)
at FirebaseAppImpl._getService (index.esm2017.js:83:1)
at FirebaseAppImpl.firebaseAppImpl. [as auth] (index.esm2017.js:291:1)
at angular-fire-compat-auth.js:59:51
at ZoneDelegate.invoke (zone.js:372:1)
at Zone.run (zone.js:134:1)

I've examined the Authentication settings of my app in the Firebase console, and they're identical for what I have set in my demo app, which works.

Any suggestions?


问:
How to chcek if a variable is "False" in Django templates?
How do I check if a variable is False using Django template syntax?

```<code>{% if myvar == False %}
</code>```

Doesn't seem to work.

Note that I very specifically want to check if it has the Python value False. This variable could be an empty array too, which is not what I want to check for.

答:
you can use the int value of true and false

True = any int
False = zero
so, if we take an example:

```<code>{% if user.is_authenticated == 1 %}
do something
{% endif %}
</code>```

this mean in python

```<code>if user.is_authenticated:
    #do something
</code>```

and

```<code>{% if user.is_authenticated == 0 %}
do something
{% endif %}
</code>```

this mean in python

```<code>if not user.is_authenticated :
    #do something
</code>```

OR equal

```<code>if !(user.is_authenticated) :
    #do something
</code>```

OR equal

```<code>if user.is_authenticated == False :
    #do something
</code>```

Body:
How do I check if a variable is False using Django template syntax?

{% if myvar == False %}

Doesn't seem to work.

Note that I very specifically want to check if it has the Python value False. This variable could be an empty array too, which is not what I want to check for.

Body:
you can use the int value of true and false

True = any int
False = zero
so, if we take an example:

{% if user.is_authenticated == 1 %}
do something
{% endif %}

this mean in python

if user.is_authenticated:
    #do something

and

{% if user.is_authenticated == 0 %}
do something
{% endif %}

this mean in python

if not user.is_authenticated :
    #do something

OR equal

if !(user.is_authenticated) :
    #do something

OR equal

if user.is_authenticated == False :
    #do something


问:
Using a date field in a ts?
I wonder how I can make use of an already existing date field when creating a ts in R.
Sometimes you simply have a date before you have a ts object, e.g.

```<code>x <- as.Date("2008-01-01") + c(30,60,90,120,150)
# add some data to it
df = data.frame(datefield=x,test=1:length(x))
</code>```

Now, is there a way to use the datefield of the df to as an index when creating a ts object? Because:

```<code>   ts(df$test,start=c(2008,1,2),frequency=12)
</code>```

(obviuously) completely ignores the date information I already have. Making use of ts methods like acf is the reason why I´d like to make it a ts object. I typcically use monthly an quarterly time series...

答:
If you want:

Use the date information you already have

Easily set the frequency to a desired value

End up with a ts object

You can start with an xts object, add a frequency attribute, and then convert to ts:

```<code>library("xts")
my_xts <- xts(df$test, df$datefield)
attr(my_xts, 'frequency') <- 12  # Set the frequency
my_ts <- as.ts(my_xts)
</code>```

The resulting ts object will have the specified period and will have the correct dates assigned to each data point.

ContentLicense: CC BY-SA 2.5

Title: Using a date field in a ts?

Body:
I wonder how I can make use of an already existing date field when creating a ts in R.
Sometimes you simply have a date before you have a ts object, e.g.

x <- as.Date("2008-01-01") + c(30,60,90,120,150)
# add some data to it
df = data.frame(datefield=x,test=1:length(x))

Now, is there a way to use the datefield of the df to as an index when creating a ts object? Because:

   ts(df$test,start=c(2008,1,2),frequency=12)

(obviuously) completely ignores the date information I already have. Making use of ts methods like acf is the reason why I´d like to make it a ts object. I typcically use monthly an quarterly time series...

Body:
If you want:

Use the date information you already have

Easily set the frequency to a desired value

End up with a ts object

You can start with an xts object, add a frequency attribute, and then convert to ts:

library("xts")
my_xts <- xts(df$test, df$datefield)
attr(my_xts, 'frequency') <- 12  # Set the frequency
my_ts <- as.ts(my_xts)

The resulting ts object will have the specified period and will have the correct dates assigned to each data point.


问:
Position Elements within a flex container with predefined widths using tailwind CSS
I am currently having trouble with styling a card component using tailwind CSS.

As you cann see, the prices are not aligned properly - how can I make it aligned?

My current code for the Cards

```<code><div onClick={deleteItem} className="flex flex-row justify-center">
      <div className="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
        <div>
          <p>{props.itemName}</p>
        </div>
        <div>
          <p>{props.itemPrice} €</p>
        </div>
        <div>
          <p>X</p>
        </div>
      </div>
    </div>
</code>```

答:
One solution would be, two wrap the itemPrice and X div in another div and give it the class flex.
This way would would have two divs, one on the very left, containing the item name, and one on the very right, containing the item price and the x button right next to each other.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

{props.itemName}

{props.itemPrice} €

X

```

Body:
I am currently having trouble with styling a card component using tailwind CSS.

As you cann see, the prices are not aligned properly - how can I make it aligned?

My current code for the Cards

{props.itemName}

{props.itemPrice} €

X

Body:
One solution would be, two wrap the itemPrice and X div in another div and give it the class flex.
This way would would have two divs, one on the very left, containing the item name, and one on the very right, containing the item price and the x button right next to each other.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class="flex flex-row justify-center">
  <div class="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
    <div>
      <p>{props.itemName}</p>
    </div>
    <div>
      <div class="flex space-x-4">
        <p>{props.itemPrice} €</p>
        <div>
          <p>X</p>
        </div>
      </div>
    </div>
  </div>
</div>


问:
Optimize display of a large number of images (1000+) for performance and ease of use in a web application
In our web application, the users need to review a large number of images. This is my current layout. 20 images will be displayed at a time, with a pagination bar above the thumbnails. Clicking a thumbnail will show the enlarged image to the left. The enlarged image will follow the scrollbar so it's always visible. Quite simple actually.

I was wondering what the best interface would be in this scenario:

One option is to implement an infinite scroll script which will lazy load thumbnails as the user scrolls. The thumbnails not visible will be removed from the DOM. But my concern with this approach is the number of changes in the DOM slowing down the page.

Another option could be something like Google's Fastflip.

What do you think is the best approach for this application? Radical ideas welcomed.

答:
I would show the thumbnails, since the user might want to skip some of the pictures. I would also stay away of pagination in the terms of

```<code><<first <previuos n of x next> last>>
</code>```

and go for something more easy to implement and efficient. A

```<code>load x more pictures.
</code>```

No infinite scroll whatsoever and why not, even no scroll at all. Just load x more, previous x.

Body:
I would show the thumbnails, since the user might want to skip some of the pictures. I would also stay away of pagination in the terms of

<<first <previuos n of x next> last>>

and go for something more easy to implement and efficient. A

load x more pictures.

No infinite scroll whatsoever and why not, even no scroll at all. Just load x more, previous x.


问:
I'm trying to delete a data in row even t code was correct it is showing error:1175 "you are using safe update mode"
delete from gov.msme.india
where micro = 212014;
SELECT * FROM msme.gov.msme.india;

答:
You are trying to update without specifying a primary key. You could disable safe update mode with the commande.

```<code>SET SQL_SAFE_UPDATES = 0;
</code>```

To be sure check what will modified by running a SELECT first.

Body:
You are trying to update without specifying a primary key. You could disable safe update mode with the commande.

SET SQL_SAFE_UPDATES = 0;

To be sure check what will modified by running a SELECT first.


答:
I believe your issue is that you are missing the # from your ID selector. Just add it like this:

$('ul').click(() => {
  let target = event.target.id;
  $(`#${target}`).css({
    "text-decoration": "line-through"
  });
});
```
<p>Or just forget about the string ID selection and just select the element already being passed, like this:</p>
<pre class="lang-js prettyprint-override"><code>$('ul').click(() => {
  $(event.target).css({
    "text-decoration": "line-through"
  });
});
</code>```

Title: Cannot edit css of a class with variable

Body:
I am trying to get a line through  the li that i added when i click the li(like a grocery list).

$('document').ready(() => {
            let id = 1;

            $('.knop').click(() => {
                let boodschap = $('.tekst').val();
                let newli = `<li id="boodschap${id}"> ${boodschap}</li>`;
                $(".result").append(`${newli}`);
                id++;
            });

            $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });
                console.log(event.target.id);
            });
        });

I know the problem is in this part:

 $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });

I dont get a error in my console. so im stuck.
but when i hard code the part where i put my ${target} it works.
you cant use a variable in the css function?
is there a way around this?

Body:
I believe your issue is that you are missing the # from your ID selector. Just add it like this:

$('ul').click(() => {
  let target = event.target.id;
  $(`#${target}`).css({
    "text-decoration": "line-through"
  });
});

Or just forget about the string ID selection and just select the element already being passed, like this:

$('ul').click(() => {
  $(event.target).css({
    "text-decoration": "line-through"
  });
});


问:
pass any function parameter which extends a specific base class
I have this base class:

```<code>export class ActVsBudget {
  constructor(
    public budget?: number,
    public actual?: number,
    public monthDiff?: number,
    public cumBudget?: number,
    public cumActual?: number,
    public cumDiff?: number
  ) {}
}
</code>```

And this extended class:

```<code>export class CostOverview extends ActVsBudget {
  constructor(
    public plant?: Plant,
    public plantArea?: PlantArea,
    public costCenter?: CostCenter,
    public costAccType?: CostAccountingType,
    public year?: number,
    public month?: number
  ) {
    super();
  }
}
</code>```

Now, I want a function, which takes a parameter (an array) of any class, which extends the above base class.

With this function signature I can pass the above CostOverview class as a parameter because of the inheritance:

```<code>calculateSums(data: ActVsBudget[])
</code>```

But then what if I need access to any other property of the child class. I can't have acces these properties with this signature.

I tried something like this:

```<code>calculateSums(data: <T extends ActVsBudget>[])
</code>```

But ts complains, that I need some brackets before the [.

What would be the right function signature?

Thanks.

答:
You have you generic definition wrong: :

```<code>calculateSums<T extends ActVsBudget>(data: T[]) {
 ...
}
</code>```

Documentation

Body:
I have this base class:

export class ActVsBudget {
  constructor(
    public budget?: number,
    public actual?: number,
    public monthDiff?: number,
    public cumBudget?: number,
    public cumActual?: number,
    public cumDiff?: number
  ) {}
}

And this extended class:

export class CostOverview extends ActVsBudget {
  constructor(
    public plant?: Plant,
    public plantArea?: PlantArea,
    public costCenter?: CostCenter,
    public costAccType?: CostAccountingType,
    public year?: number,
    public month?: number
  ) {
    super();
  }
}

Now, I want a function, which takes a parameter (an array) of any class, which extends the above base class.

With this function signature I can pass the above CostOverview class as a parameter because of the inheritance:

calculateSums(data: ActVsBudget[])

But then what if I need access to any other property of the child class. I can't have acces these properties with this signature.

I tried something like this:

calculateSums(data: <T extends ActVsBudget>[])

But ts complains, that I need some brackets before the [.

What would be the right function signature?

Thanks.

Body:
You have you generic definition wrong: :

calculateSums<T extends ActVsBudget>(data: T[]) {
 ...
}

Documentation


问:
Why KEY has automatically created when I make fk constraint for field?
I am creating the table with this syntax:

```<code>CREATE TABLE movies_genres
(
    id BIGINT AUTO_INCREMENT,
    movie_id INT NOT NULL,
    genre_id INT NOT NULL,

    PRIMARY KEY (id),
    CONSTRAINT `fk_movie_id` FOREIGN KEY (movie_id) REFERENCES movies(id),
    CONSTRAINT `fk_genre_id` FOREIGN KEY (genre_id) REFERENCES genres(id),
    CONSTRAINT unique_id_pair UNIQUE(movie_id, genre_id)
);
</code>```

But then I look at the info about the table in MySQL Workbench I see:

```<code>CREATE TABLE `movies_genres` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `movie_id` int NOT NULL,
  `genre_id` int NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_id_pair` (`movie_id`,`genre_id`),
  KEY `fk_genre_id` (`genre_id`),
  CONSTRAINT `fk_genre_id` FOREIGN KEY (`genre_id`) REFERENCES `genres` (`id`),
  CONSTRAINT `fk_movie_id` FOREIGN KEY (`movie_id`) REFERENCES `movies` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
</code>```

Why this line of code has generated?

```<code>KEY `fk_genre_id` (`genre_id`)
</code>```

Also I see that extra index was created that I didn't order...

Screenshot with extra index

答:
https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html says:

MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist.

(emphasis mine)

Body:
I am creating the table with this syntax:

CREATE TABLE movies_genres
(
    id BIGINT AUTO_INCREMENT,
    movie_id INT NOT NULL,
    genre_id INT NOT NULL,

    PRIMARY KEY (id),
    CONSTRAINT `fk_movie_id` FOREIGN KEY (movie_id) REFERENCES movies(id),
    CONSTRAINT `fk_genre_id` FOREIGN KEY (genre_id) REFERENCES genres(id),
    CONSTRAINT unique_id_pair UNIQUE(movie_id, genre_id)
);

But then I look at the info about the table in MySQL Workbench I see:

CREATE TABLE `movies_genres` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `movie_id` int NOT NULL,
  `genre_id` int NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_id_pair` (`movie_id`,`genre_id`),
  KEY `fk_genre_id` (`genre_id`),
  CONSTRAINT `fk_genre_id` FOREIGN KEY (`genre_id`) REFERENCES `genres` (`id`),
  CONSTRAINT `fk_movie_id` FOREIGN KEY (`movie_id`) REFERENCES `movies` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

Why this line of code has generated?

KEY `fk_genre_id` (`genre_id`)

Also I see that extra index was created that I didn't order...

Screenshot with extra index


问:
How can I split strings so that only numbers are selected?

please excuse me for the change in this question

I want to split a string (e.g. text1, text2), so that only numbers are output:

I tried the following:

```<code>import re

# example text1

text1 = " climb   -  95/ 85     0.18   low     -  4680"

split_text1 = re.split(" +", text1)

print(split_text1)

['', 'climb', '-', '95/', '85', '0.18', 'low', '-', '4680']

# example text2

text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

split_text2 = re.split(" +", text2)

print(split_text2)

['CD 3 TO', 'F TO GD', '.80000E+02', '.00000E+00', '.00000E+00', '.00000E+00 /']
</code>```

How can I get as result:

```<code># split_text1 = ['95', '85', '0.18', '4680']

# split_text2 = ['3', '80.0','0.0', '0.0', 0.0]
</code>```

答:
Simply add a second space before the +. This will stop the 95/ 85 from being split. If you want \n at the end of the last item, add text += "\n".</p>
```<code>import re

text = " climb   -  95/ 85     0.18   low     -  4680"

text = "a " + text

text += "\n"

split_text = re.split("  +", text)

if split_text[0] == "a":
  split_text[0] = ""
else:
  split_text[0] = split_text[0][2:]

print(split_text)
</code>```

Body:
please excuse me for the change in this question

I want to split a string (e.g. text1, text2), so that only numbers are output:

I tried the following:

import re

# example text1

text1 = " climb   -  95/ 85     0.18   low     -  4680"

split_text1 = re.split(" +", text1)

print(split_text1)

['', 'climb', '-', '95/', '85', '0.18', 'low', '-', '4680']

# example text2

text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

split_text2 = re.split(" +", text2)

print(split_text2)

['CD 3 TO', 'F TO GD', '.80000E+02', '.00000E+00', '.00000E+00', '.00000E+00 /']

How can I get as result:

# split_text1 = ['95', '85', '0.18', '4680']

# split_text2 = ['3', '80.0','0.0', '0.0', 0.0]

Body:
Simply add a second space before the +. This will stop the 95/ 85 from being split. If you want \n at the end of the last item, add text += "\n".

import re

text = " climb   -  95/ 85     0.18   low     -  4680"

text = "a " + text

text += "\n"

split_text = re.split("  +", text)

if split_text[0] == "a":
  split_text[0] = ""
else:
  split_text[0] = split_text[0][2:]

print(split_text)


问:
ConstraintLayout Barrier not visible in design view
I'm trying to add a barrier to my ConstraintLayout in Android Studio but it is not showing up the way it should in design view.

I have been following this tutorial, but I can't get things to work properly.

I'm currently using:

Android Studio 3.1.1

androidx.constraintlayout:constraintlayout:1.1.3

Things I have tried:

Invalidate caches/restart

Removing the attribute tools:layout_editor_absoluteX

Fiddling around!

Here's my test.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                   xmlns:app="http://schemas.android.com/apk/res-auto"
                                                   xmlns:tools="http://schemas.android.com/tools"
                                                   android:layout_width="match_parent"
                                                   android:layout_height="match_parent">

    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button" android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="8dp"/>
    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button2" android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/button" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="8dp"/>
    <androidx.constraintlayout.widget.Barrier android:layout_width="wrap_content" android:layout_height="wrap_content"
                                              android:id="@+id/barrier2" app:barrierDirection="end"
                                              app:constraint_referenced_ids="button,button2"
                                              tools:layout_editor_absoluteX="411dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

In design view, it looks like this

The barrier is stuck to the edge of the layout and doesn't move no matter what I do. If I set barrierDirection start or left it is not visible at all. If I set end or right the dashed line shows up but is stuck to the left side of the layout.

Barriers seem to work fine in another project started from scratch, but this uses the android.support.constraint.ConstraintLayout rather than the androidx library's.

答:
When I upgraded constraintLayout library from version 2.0.4 to 2.1.3, the barriers messed up.

I changed the width and height of my barriers as follow and the problem resolved.

Before:

<androidx.constraintlayout.widget.Barrier
    android:id="@+id/myBarrier"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:barrierDirection="end"
    app:constraint_referenced_ids="textView1,textView2,textView3"
    app:layout_constraintEnd_toEndOf="parent" />
```
<p>After:</p>
<pre class="lang-xml prettyprint-override"><code><androidx.constraintlayout.widget.Barrier
    android:id="@+id/myBarrier"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    ...
/>
</code>```

Body:
I'm trying to add a barrier to my ConstraintLayout in Android Studio but it is not showing up the way it should in design view.

I have been following this tutorial, but I can't get things to work properly.

I'm currently using:

Android Studio 3.1.1

androidx.constraintlayout:constraintlayout:1.1.3

Things I have tried:

Invalidate caches/restart

Removing the attribute tools:layout_editor_absoluteX

Fiddling around!

Here's my test.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                   xmlns:app="http://schemas.android.com/apk/res-auto"
                                                   xmlns:tools="http://schemas.android.com/tools"
                                                   android:layout_width="match_parent"
                                                   android:layout_height="match_parent">

    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button" android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="8dp"/>
    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button2" android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/button" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="8dp"/>
    <androidx.constraintlayout.widget.Barrier android:layout_width="wrap_content" android:layout_height="wrap_content"
                                              android:id="@+id/barrier2" app:barrierDirection="end"
                                              app:constraint_referenced_ids="button,button2"
                                              tools:layout_editor_absoluteX="411dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

In design view, it looks like this

The barrier is stuck to the edge of the layout and doesn't move no matter what I do. If I set barrierDirection start or left it is not visible at all. If I set end or right the dashed line shows up but is stuck to the left side of the layout.

Barriers seem to work fine in another project started from scratch, but this uses the android.support.constraint.ConstraintLayout rather than the androidx library's.

Body:
When I upgraded constraintLayout library from version 2.0.4 to 2.1.3, the barriers messed up.

I changed the width and height of my barriers as follow and the problem resolved.

Before:

<androidx.constraintlayout.widget.Barrier
    android:id="@+id/myBarrier"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:barrierDirection="end"
    app:constraint_referenced_ids="textView1,textView2,textView3"
    app:layout_constraintEnd_toEndOf="parent" />

After:

<androidx.constraintlayout.widget.Barrier
    android:id="@+id/myBarrier"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    ...
/>


问:
Selecting all same html attributes with (different) values included in VSCode
I'm using VSCode for html editing. In VSCode it's very easy to select same occurences of a piece of code. What i need is selecting all ocuurances of an html attribute (like class, aria-label, etc.) with different values. Here's an example:

I want to select all "aria-label" occurences with the values included. So these will be selected:

```<code>aria-label="Apple"
aria-label="Oranges"
aria-label="Multiple Fruit Names"
aria-label=""
...
</code>```

Is there a way to do that in VSCode?

答:
I understood that regex knowledge essential so for last couple of days i studied Regex101, this is what worked for me on this question.</p>
```<code>aria-[a-zA-Z]*="[A-Za-z\s]*"
</code>```

Body:
I'm using VSCode for html editing. In VSCode it's very easy to select same occurences of a piece of code. What i need is selecting all ocuurances of an html attribute (like class, aria-label, etc.) with different values. Here's an example:

I want to select all "aria-label" occurences with the values included. So these will be selected:

aria-label="Apple"
aria-label="Oranges"
aria-label="Multiple Fruit Names"
aria-label=""
...

Is there a way to do that in VSCode?

Body:
I understood that regex knowledge essential so for last couple of days i studied Regex101, this is what worked for me on this question.

aria-[a-zA-Z]*="[A-Za-z\s]*"


问:
how to assign text to ggplot with a condition when y axis is not numeric in r
I want to annotate a percentage number of missing values for each variable that actually has any missing values somewhere above the corresponding variable blue line.
I can add a text using geom_text but I have difficulty with how to select those vars with Nas. I would appreciate any hint with this.

```<code>library(ggplot2)
library(naniar)
gg_miss_var(airquality) + labs(y = "Look at all the missing ones")
</code>```

答:
You can use naniar::miss_var_summary() to create a data frame with labels for all variables with at least one NA:

```<code>df <- miss_var_summary(airquality) %>%
  dplyr::filter(n_miss > 0) %>%
  dplyr::mutate(pct_label = paste0(round(pct_miss, 1), '%'))
</code>```

You can then use this data frame inside your geom_text() line:

```<code>gg_miss_var(airquality) +
  geom_text(data = df, aes(x = as.factor(variable), y = n_miss, label = pct_label),
            vjust = 1.5) +
  labs(y = "Look at all the missing ones")
</code>```

Body:
I want to annotate a percentage number of missing values for each variable that actually has any missing values somewhere above the corresponding variable blue line.
I can add a text using geom_text but I have difficulty with how to select those vars with Nas. I would appreciate any hint with this.

library(ggplot2)
library(naniar)
gg_miss_var(airquality) + labs(y = "Look at all the missing ones")

Body:
You can use naniar::miss_var_summary() to create a data frame with labels for all variables with at least one NA:

df <- miss_var_summary(airquality) %>%
  dplyr::filter(n_miss > 0) %>%
  dplyr::mutate(pct_label = paste0(round(pct_miss, 1), '%'))

You can then use this data frame inside your geom_text() line:

gg_miss_var(airquality) +
  geom_text(data = df, aes(x = as.factor(variable), y = n_miss, label = pct_label),
            vjust = 1.5) +
  labs(y = "Look at all the missing ones")


问:
R - How to condition across two dataframes based on date
Sorry if this is a duplicate but could not quite find what was right for me.

I have a Dataframe 1 - where Episode_ID is unique but patient_ID is not

```<code>  Episode_ID  Patient_ID  Drug   Commenced_date
1 1             0           A      2018-01-02
2 2             0           B      2020-11-26
3 3             1           B      2017-09-26
4 4             2           B      2020-11-26
</code>```

and Dataframe 2 where Visit_ID is unique but Patient_ID is not

```<code>  Patient_ID  Visit_ID   Visit_date  Visit_Score
1  0           1         2018-01-22   2.3
2  0           2         2019-06-01   1.5
3  0           3         2020-11-26   1.6
4  1           B         2020-11-26   1.4
</code>```

What I want to achieve is for each episode (from df1) to be matched to that patients closest visit in (df2) by looping through all the visit_dates (matched by patient_ID) in df 2 and have the associated visit_score appended. As each row in Df1 is iterated, the patient ID can be matched to patient ID in df2. So the first row, should be a 1 to 3 match. datediff with which.min can then be applied to find the closest match. Its the coding syntax that I really can't get down right.

For example, based on the above. The result would be:

```<code>  Episode_ID  Patient_ID  Drug   Commenced_date  Closest_Visit Visit_score
1 1             0           A      2018-01-02    2018-01-22    2.3
2 2             0           B      2020-11-26    2020-11-26    1.6
3 3             1           B      2017-09-26    2018-01-22    2.3
4 4             2           B      2020-11-26    2020-11-26    1.4
</code>```

This should be quite simple but I've becoming really rusty in R and out of practice. I tried to use a nested for loop but it kept breaking. Then tried using sapply but couldn't quite get it to work.

Any help would be greatly appreciated. Happy for a solution in python as well but prefer R for now given the rest of the project at the moment.

答:
There are a few options to consider for approaches with R that do not require loops.

I might consider data.table and join the data.frames with roll:

```<code>library(data.table)

setDT(df1)
setDT(df2)

df2[df1, on = c('Patient_ID', 'Visit_date' = 'Commenced_date'), roll = 'nearest']
</code>```

Output

```<code>   Patient_ID Visit_ID Visit_date Visit_Score Episode_ID Drug
1:          0        1 2018-01-02         2.3          1    A
2:          0        3 2020-11-26         1.6          2    B
3:          1        B 2017-09-26         1.4          3    B
4:          2     <NA> 2020-11-26          NA          4    B
</code>```

Or use sqldf with a join of the two data.frames:

```<code>library(sqldf)

sqldf("select df1.*, df2.*, min(abs(df1.Commenced_date - df2.Visit_date)) diff
       from df1
       left join df2 using(Patient_ID)
       group by df1.rowid")
</code>```

Output

```<code>  Episode_ID Patient_ID Drug Commenced_date Patient_ID Visit_ID Visit_date Visit_Score diff
1          1          0    A     2018-01-02          0        1 2018-01-22         2.3   20
2          2          0    B     2020-11-26          0        3 2020-11-26         1.6    0
3          3          1    B     2017-09-26          1        B 2020-11-26         1.4 1157
4          4          2    B     2020-11-26         NA     <NA>       <NA>          NA   NA
</code>```

In this case, leaving in a calculated difference in dates.

If you did want a tidyverse approach, you could a join and then filter or slice to keep the row with minimum difference in dates:

```<code>library(tidyverse)

left_join(df1, df2, by = "Patient_ID") %>%
  group_by(Patient_ID, Episode_ID) %>%
  slice_min(abs(Visit_date - Commenced_date))
</code>```

Output

```<code>  Episode_ID Patient_ID Drug  Commenced_date Visit_ID Visit_date Visit_Score
       <int>      <int> <chr> <date>         <chr>    <date>           <dbl>
1          1          0 A     2018-01-02     1        2018-01-22         2.3
2          2          0 B     2020-11-26     3        2020-11-26         1.6
3          3          1 B     2017-09-26     B        2020-11-26         1.4
</code>```

In this case, used slice_min which will omit rows in df1 that did not match by Patient_ID on df2.

Body:
Sorry if this is a duplicate but could not quite find what was right for me.

I have a Dataframe 1 - where Episode_ID is unique but patient_ID is not

  Episode_ID  Patient_ID  Drug   Commenced_date
1 1             0           A      2018-01-02
2 2             0           B      2020-11-26
3 3             1           B      2017-09-26
4 4             2           B      2020-11-26

and Dataframe 2 where Visit_ID is unique but Patient_ID is not

  Patient_ID  Visit_ID   Visit_date  Visit_Score
1  0           1         2018-01-22   2.3
2  0           2         2019-06-01   1.5
3  0           3         2020-11-26   1.6
4  1           B         2020-11-26   1.4

What I want to achieve is for each episode (from df1) to be matched to that patients closest visit in (df2) by looping through all the visit_dates (matched by patient_ID) in df 2 and have the associated visit_score appended. As each row in Df1 is iterated, the patient ID can be matched to patient ID in df2. So the first row, should be a 1 to 3 match. datediff with which.min can then be applied to find the closest match. Its the coding syntax that I really can't get down right.

For example, based on the above. The result would be:

  Episode_ID  Patient_ID  Drug   Commenced_date  Closest_Visit Visit_score
1 1             0           A      2018-01-02    2018-01-22    2.3
2 2             0           B      2020-11-26    2020-11-26    1.6
3 3             1           B      2017-09-26    2018-01-22    2.3
4 4             2           B      2020-11-26    2020-11-26    1.4

This should be quite simple but I've becoming really rusty in R and out of practice. I tried to use a nested for loop but it kept breaking. Then tried using sapply but couldn't quite get it to work.

Any help would be greatly appreciated. Happy for a solution in python as well but prefer R for now given the rest of the project at the moment.

Body:
There are a few options to consider for approaches with R that do not require loops.

I might consider data.table and join the data.frames with roll:

library(data.table)

setDT(df1)
setDT(df2)

df2[df1, on = c('Patient_ID', 'Visit_date' = 'Commenced_date'), roll = 'nearest']

Output

   Patient_ID Visit_ID Visit_date Visit_Score Episode_ID Drug
1:          0        1 2018-01-02         2.3          1    A
2:          0        3 2020-11-26         1.6          2    B
3:          1        B 2017-09-26         1.4          3    B
4:          2     <NA> 2020-11-26          NA          4    B

Or use sqldf with a join of the two data.frames:

library(sqldf)

sqldf("select df1.*, df2.*, min(abs(df1.Commenced_date - df2.Visit_date)) diff
       from df1
       left join df2 using(Patient_ID)
       group by df1.rowid")

Output

  Episode_ID Patient_ID Drug Commenced_date Patient_ID Visit_ID Visit_date Visit_Score diff
1          1          0    A     2018-01-02          0        1 2018-01-22         2.3   20
2          2          0    B     2020-11-26          0        3 2020-11-26         1.6    0
3          3          1    B     2017-09-26          1        B 2020-11-26         1.4 1157
4          4          2    B     2020-11-26         NA     <NA>       <NA>          NA   NA

In this case, leaving in a calculated difference in dates.

If you did want a tidyverse approach, you could a join and then filter or slice to keep the row with minimum difference in dates:

library(tidyverse)

left_join(df1, df2, by = "Patient_ID") %>%
  group_by(Patient_ID, Episode_ID) %>%
  slice_min(abs(Visit_date - Commenced_date))

Output

  Episode_ID Patient_ID Drug  Commenced_date Visit_ID Visit_date Visit_Score
       <int>      <int> <chr> <date>         <chr>    <date>           <dbl>
1          1          0 A     2018-01-02     1        2018-01-22         2.3
2          2          0 B     2020-11-26     3        2020-11-26         1.6
3          3          1 B     2017-09-26     B        2020-11-26         1.4

In this case, used slice_min which will omit rows in df1 that did not match by Patient_ID on df2.


问:
Why a PHP warning appearing in Chrome but not in any other browser?
I'm writing a web application in PHP, and I'm getting the following warning in Google Chrome only:

Warning: Cannot use a scalar value as an array in
  M:\xampp\htdocs\MyProjectTitle\php\classes.php on line 18

Background: Please note that the web app works just fine in all browsers I tested (Firefox, Chrome, IE), but the warning appearing in Chrome is bugging the hell outta me.

Notes: I have tried restarting Chrome and clearing the Chrome cache. I have tried restarting the computer. I have tried searching the source code in FF and IE to see if the warning was just hidden, but to no avail. The warning is only popping up in Google Chrome, and I have no idea why.

UPDATE: Even though Safari also uses WebKit, it does not show the PHP warning. For some reason, Chrome is the only one that has the PHP warning. Weird stuff!

UPDATE: Here's the first 21 lines of code:

```<code>class Presenter {
    public function includeFile($filePath) {
        if (is_readable($filePath)) {
            include $filePath;
        } else {
            echo '<p><strong>ERROR 404</strong></p>';
            echo '<p>The resource you requested could not be located.</p>';
        }
    }

    public function sanitize($string) {
        return preg_replace("/\s/","_",$string);
    }

    public function set($varname,$value) {
        $this->$varname = $value;
        $_SESSION[$this->name][$varname] = $value;

        return $this;   // enables chaining!
    }

    // And there's more code after this, but I have cut it out here.
}
</code>```

Note: The above code is inside a PHP class.

UPDATE: I know exactly what lines of code are causing the warning in Chrome (although I still have no clue why Chrome is the only browser that shows the warning). Since my webapp works perfectly despite the warning in Chrome, I have used @ to suppress the warnings in Chrome (I'll fix the warning later).

答: UPDATE: I know exactly what lines of code are causing the warning in Chrome (although I still have no clue why Chrome is the only browser that shows the warning...If you know, please let me know!). Since my webapp works perfectly despite the warning in Chrome, I have used @ to suppress the warning as a temporary fix until I can fix it for real later.

Body:
I'm writing a web application in PHP, and I'm getting the following warning in Google Chrome only:

Warning: Cannot use a scalar value as an array in
  M:\xampp\htdocs\MyProjectTitle\php\classes.php on line 18

Background: Please note that the web app works just fine in all browsers I tested (Firefox, Chrome, IE), but the warning appearing in Chrome is bugging the hell outta me.

Notes: I have tried restarting Chrome and clearing the Chrome cache. I have tried restarting the computer. I have tried searching the source code in FF and IE to see if the warning was just hidden, but to no avail. The warning is only popping up in Google Chrome, and I have no idea why.

UPDATE: Even though Safari also uses WebKit, it does not show the PHP warning. For some reason, Chrome is the only one that has the PHP warning. Weird stuff!

UPDATE: Here's the first 21 lines of code:

class Presenter {
    public function includeFile($filePath) {
        if (is_readable($filePath)) {
            include $filePath;
        } else {
            echo '
ERROR 404
';
            echo '
The resource you requested could not be located.
';
        }
    }

    public function sanitize($string) {
        return preg_replace("/\s/","_",$string);
    }

    public function set($varname,$value) {
        $this->$varname = $value;
        $_SESSION[$this->name][$varname] = $value;

        return $this;   // enables chaining!
    }

    // And there's more code after this, but I have cut it out here.
}

Note: The above code is inside a PHP class.

UPDATE: I know exactly what lines of code are causing the warning in Chrome (although I still have no clue why Chrome is the only browser that shows the warning). Since my webapp works perfectly despite the warning in Chrome, I have used @ to suppress the warnings in Chrome (I'll fix the warning later).


问:
I added tailwindcss to vite+react+ts+sass,but it doesn't work
index.css

```<code>@tailwind base;
@tailwind components;
@tailwind utilities;
</code>```

index.tsx

```<code>...
import "./index.css";
<div className="p-xl text-center">1111</div>
...
</code>```

but neither 'p-xl' nor 'text-center' work.only tailwindcss prefix css work.

答:
I fixed it just now.
add it to tailwind.config.js</p>
```<code> content: [
    "./index.html",
    "./src/**/*.{jsx,tsx}",
  ],
</code>```

Body:
index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

index.tsx

...
import "./index.css";

1111

...

but neither 'p-xl' nor 'text-center' work.only tailwindcss prefix css work.

Body:
I fixed it just now.
add it to tailwind.config.js

 content: [
    "./index.html",
    "./src/**/*.{jsx,tsx}",
  ],


问:
How to add an entry into Room using Coroutines
I'm trying to add an entry into local DB but it's not working for me. It says unresolved reference.

RoomClass.kt

```<code>@Database(entities = [ApodEntity::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun appListDao(): AppDao
}
</code>```

Dao.kt

```<code> @Dao
interface AppDao {

@Insert()
fun saveFavorites(item: AppEntity)
}
</code>```

I'm trying to insert using an adapter:

```<code>GlobalScope.launch {
             AppDatabase.appListDao().saveFavorites(entity)
            }
</code>```

But here appListDao called as unknown reference. Hope my query is cleared. Thanks in advance.

答:
It's because of that you must create instance of AppDabase and then on instance of it call the dao function like this:

create a file DatabaseSinglton.kt

```<code>object DatabaseSingleton {

    var database: AppDatabase? = null

    fun getAppDatabase(context: Context): AppDatabase {
        return if (database == null) {
            database = Room.databaseBuilder(
                context,
                AppDatabase::class.java,
                "AppDatabase"
            ).build()

            database!!
        } else {
            database!!
        }
    }
}
</code>```

and when your code must be change to this:

```<code>GlobalScope.launch {
    DatabaseSingleton.getAppDatabase(
        context
    ).appListDao().saveFavorites(entity)
}
</code>```

Body:
I'm trying to add an entry into local DB but it's not working for me. It says unresolved reference.

RoomClass.kt

@Database(entities = [ApodEntity::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun appListDao(): AppDao
}

Dao.kt

 @Dao
interface AppDao {

@Insert()
fun saveFavorites(item: AppEntity)
}

I'm trying to insert using an adapter:

GlobalScope.launch {
             AppDatabase.appListDao().saveFavorites(entity)
            }

But here appListDao called as unknown reference. Hope my query is cleared. Thanks in advance.

Body:
It's because of that you must create instance of AppDabase and then on instance of it call the dao function like this:

create a file DatabaseSinglton.kt

object DatabaseSingleton {

    var database: AppDatabase? = null

    fun getAppDatabase(context: Context): AppDatabase {
        return if (database == null) {
            database = Room.databaseBuilder(
                context,
                AppDatabase::class.java,
                "AppDatabase"
            ).build()

            database!!
        } else {
            database!!
        }
    }
}

and when your code must be change to this:

GlobalScope.launch {
    DatabaseSingleton.getAppDatabase(
        context
    ).appListDao().saveFavorites(entity)
}


问:
Create JAR file of a specific package in a multi-package project
I understand how to create a JAR file when there is only a single package in a Java project but don't know how to create a JAR file when there are multiple packages in a Java project.

I have a sample project with the following structure:

I have two packages which you can see in the picture i.e.

academy.learnprogramming

academy.ujjwal

I want to create a jar file for the classes which are in the academy.ujjwal package. I tried multiple ways from the Artifacts option but not sure how to do it right.

答:
It's usually uncommon to create jar file from command, Maven, Gradle like build tools are used but you can try following command.</p>
```<code>jar cvp filename.jar /path/to/classes

 jar cvf  learnprogramming.jar src/academy.learnprogramming
 jar cvp abc.jar src/academy.ujjwal
</code>```

Body:
It's usually uncommon to create jar file from command, Maven, Gradle like build tools are used but you can try following command.

jar cvp filename.jar /path/to/classes

 jar cvf  learnprogramming.jar src/academy.learnprogramming
 jar cvp abc.jar src/academy.ujjwal


问:
How do I detect laser line from 2 images and calculate its center using python opencv?
How can I detect laser line using 2 images, first with laser turned off and second with turned on and then calculate its center?
These are my images:
img1.jpg
img2.jpg

This is my code:

```<code>import cv2
import time

img1 = cv2.imread("img1.jpg")
img2 = cv2.imread("img2.jpg")
img_org = img1
img1 = img1[:,:,2]
img2 = img2[:,:,2]

diff = cv2.absdiff(img1, img2)
diff = cv2.medianBlur(diff,5)
ret, diff = cv2.threshold(diff ,0 ,255 ,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

cv2.imwrite("output1.png", diff)

count = 0

height, width = diff.shape[:2]

start = time.time() # time start

for y in range(height):
    for x in range(width):
        if diff[y,x] == 255:
            count += 1
        elif not count == 0:
            img_org[y, round(x - count/2)] = [0, 255, 0]
            count = 0

end = time.time() # time stop
print(end - start)

cv2.imwrite("output2.png", img_org)

cv2.waitKey(0)
</code>```

This code takes red channel from both images, compare them to detect difference, then blur and treshold the difference image. This doesnt work good enought because on the top is some white that shouldn't be there. output1.png (diff)

For detecting center of thresholded line I have tried looping through every row and pixel of the threshold image, counting white pixels. It works correcly but because of slow python loops and arrays calculating one 4032x2268 thresholded image takes about 16 seconds. For testing my code is setting laser line center to green pixels on output2.png. output2.png (img_org)

How can I make laser detection more accurate and center of line calculation way faster?
I'm fairly new to opencv.

答:
difference

gaussian blur to suppress noise, and smooth over saturated sections

np.argmax to find maximum for each row

I would also recommend

some more reduction in exposure

PNG instead of JPEG for real processing. JPEG saves space, okay for viewing on the web.

Gamma curves don't necessarily matter here. Just make sure the environment is darker than the laser. Exact calculation depends on what color space it is exactly, and the 2.2 exponent is a good approximation of the actual curve

im0 = cv.imread("background.jpeg")
im1 = cv.imread("foreground.jpeg")
(height, width) = im0.shape[:2]

# gamma stuff, make values linear
#im0 = (im0 / np.float32(255)) ** 2.2
#im1 = (im1 / np.float32(255)) ** 2.2

diff = cv.absdiff(im1, im0)
diff = cv.GaussianBlur(diff, ksize=None, sigmaX=3.0)
plane = diff[:,:,2] # red
indices = np.argmax(plane, axis=1) # horizontally, for each row

out = diff.copy() # "drawing" 3 pixels thick
out[np.arange(height), indices-1] = (0,255,0)
out[np.arange(height), indices  ] = (0,255,0)
out[np.arange(height), indices+1] = (0,255,0)
cv.imwrite("out.jpeg", out)
```

Body:
How can I detect laser line using 2 images, first with laser turned off and second with turned on and then calculate its center?
These are my images:
img1.jpg
img2.jpg

This is my code:

import cv2
import time

img1 = cv2.imread("img1.jpg")
img2 = cv2.imread("img2.jpg")
img_org = img1
img1 = img1[:,:,2]
img2 = img2[:,:,2]

diff = cv2.absdiff(img1, img2)
diff = cv2.medianBlur(diff,5)
ret, diff = cv2.threshold(diff ,0 ,255 ,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

cv2.imwrite("output1.png", diff)

count = 0

height, width = diff.shape[:2]

start = time.time() # time start

for y in range(height):
    for x in range(width):
        if diff[y,x] == 255:
            count += 1
        elif not count == 0:
            img_org[y, round(x - count/2)] = [0, 255, 0]
            count = 0

end = time.time() # time stop
print(end - start)

cv2.imwrite("output2.png", img_org)

cv2.waitKey(0)

This code takes red channel from both images, compare them to detect difference, then blur and treshold the difference image. This doesnt work good enought because on the top is some white that shouldn't be there. output1.png (diff)

For detecting center of thresholded line I have tried looping through every row and pixel of the threshold image, counting white pixels. It works correcly but because of slow python loops and arrays calculating one 4032x2268 thresholded image takes about 16 seconds. For testing my code is setting laser line center to green pixels on output2.png. output2.png (img_org)

How can I make laser detection more accurate and center of line calculation way faster?
I'm fairly new to opencv.


问:
Why my segmentation using HSV space isn't giving me a good result?
I am attending a class on image processing with Matlab and I found a problem on the internet and I tried to solve it but it is hard, because I am new to this subject.

The problem has to be solved with Matlab and it is new for me as well.

Problem:

'Think of RGB and HSV spaces as 3-dimensional spaces. Define a
neighborhood distance (we can use ecludien distance) and set to 0 all
the pixels whose value in RGB or HSV space is far (in the sense of
this distance) from your reference value. See if you can easily
achieve the same type of segmentation in both cases. Try for example
to segment only the helmets of the warriors of the image
bilibinWar.jpg.'

I tried to code it but i don't know if the result is good.

```<code>%%
% 4) 8 - Segmentatiion dans l’’espace HSV et RVB..
clear all; close all;
ImagebilibinWar = imread("bilibinWar.jpg");
[lin, col, pla] = size(ImagebilibinWar);
figure(1);imshow(ImagebilibinWar);
Image_bilibinWar_HSV= rgb2hsv(ImagebilibinWar);
[lo,co] = ginput(1);
lo = round(lo);
co = round(co);
RIOH = Image_bilibinWar_HSV(lo,co,1);

%%
% Im going to use this first  section so ican isolate the helmets inside a circle ARROUND THE HELMETS and get rid of REST background Circle_Image_bilibinWar_HSV = Image_bilibinWar_HSV;
for i= 1:lin
    for j = 1:col
        d(i,j) = ((i-lo)^2 + (j-co)^2)^0.5;
        if d(i,j,:) > 90
            Circle_Image_bilibinWar_HSV(i,j,:) = 0;
        end
    end
end
Circle_Image_bilibinWar_RGB = hsv2rgb(Circle_Image_bilibinWar_HSV);
figure(2);imshow(Circle_Image_bilibinWar_RGB); % i have isolated the circle

%% here im going to isolate the helmets inside the circle
figure(3); imshow(Circle_Image_bilibinWar_HSV); % as u can see here i will try to isolate the helmets from the rest
New_Circle_Image_bilibinWar_HSV = Circle_Image_bilibinWar_HSV % assinging a new image so as i can work on it seperatly;
valueH = New_Circle_Image_bilibinWar_HSV(lo,co,1);

for i=1:lin
    for j=1:col
        if (New_Circle_Image_bilibinWar_HSV(i,j,1) > valueH + 0.19)
            New_Circle_Image_bilibinWar_HSV(i,j,:) = 0;
        end
    end
end

Circle_Image_bilibinWar_HSV = Circle_Image_bilibinWar_HSV - New_Circle_Image_bilibinWar_HSV;
NEW_Image_bilibinWar_RGB = hsv2rgb(Circle_Image_bilibinWar_HSV);
figure(4); subplot(1,2,1);imshow(ImagebilibinWar);
subplot(1,2,2);imshow(NEW_Image_bilibinWar_RGB);
</code>```

So can some one help me with it? i don't know if its good and if not how can i make it good ?

答:
I don't think there is anything wrong with your code. The answer is that segmenting using euclidean distance in colors simply does not work for RGB or HSV spaces. The entire purpose of the L*a*b color space was indeed this, creating a color space where similar colors would have the little euclidean distance.

Here a less cluttered version of it:

```<code>clear all; close all;
ImagebilibinWar = imread("https://i.stack.imgur.com/wnBDu.jpg");
[lin, col, pla] = size(ImagebilibinWar);
figure;imshow(ImagebilibinWar);
ImagebilibinWarHSV= rgb2hsv(ImagebilibinWar);
[lo,co] = ginput(1);
lo = round(lo);
co = round(co);
RIOH = ImagebilibinWarHSV(lo,co,1);
RIOS = ImagebilibinWarHSV(lo,co,2);
RIOV = ImagebilibinWarHSV(lo,co,3);
%reference value that i have to choose
for a=0:0.05:1

    d = ((ImagebilibinWarHSV(:,:,1)-RIOH).^2 + (ImagebilibinWarHSV(:,:,2)-RIOS).^2+(ImagebilibinWarHSV(:,:,3)-RIOV).^2).^0.5;

    ImagebilibinWarRGB = hsv2rgb(ImagebilibinWarHSV.*double(d<a));
    figure;imshow(ImagebilibinWarRGB);
end
</code>```

Body:
I am attending a class on image processing with Matlab and I found a problem on the internet and I tried to solve it but it is hard, because I am new to this subject.

The problem has to be solved with Matlab and it is new for me as well.

Problem:

'Think of RGB and HSV spaces as 3-dimensional spaces. Define a
neighborhood distance (we can use ecludien distance) and set to 0 all
the pixels whose value in RGB or HSV space is far (in the sense of
this distance) from your reference value. See if you can easily
achieve the same type of segmentation in both cases. Try for example
to segment only the helmets of the warriors of the image
bilibinWar.jpg.'

I tried to code it but i don't know if the result is good.

%%
% 4) 8 - Segmentatiion dans l’’espace HSV et RVB..
clear all; close all;
ImagebilibinWar = imread("bilibinWar.jpg");
[lin, col, pla] = size(ImagebilibinWar);
figure(1);imshow(ImagebilibinWar);
Image_bilibinWar_HSV= rgb2hsv(ImagebilibinWar);
[lo,co] = ginput(1);
lo = round(lo);
co = round(co);
RIOH = Image_bilibinWar_HSV(lo,co,1);

%%
% Im going to use this first  section so ican isolate the helmets inside a circle ARROUND THE HELMETS and get rid of REST background Circle_Image_bilibinWar_HSV = Image_bilibinWar_HSV;
for i= 1:lin
    for j = 1:col
        d(i,j) = ((i-lo)^2 + (j-co)^2)^0.5;
        if d(i,j,:) > 90
            Circle_Image_bilibinWar_HSV(i,j,:) = 0;
        end
    end
end
Circle_Image_bilibinWar_RGB = hsv2rgb(Circle_Image_bilibinWar_HSV);
figure(2);imshow(Circle_Image_bilibinWar_RGB); % i have isolated the circle

%% here im going to isolate the helmets inside the circle
figure(3); imshow(Circle_Image_bilibinWar_HSV); % as u can see here i will try to isolate the helmets from the rest
New_Circle_Image_bilibinWar_HSV = Circle_Image_bilibinWar_HSV % assinging a new image so as i can work on it seperatly;
valueH = New_Circle_Image_bilibinWar_HSV(lo,co,1);

for i=1:lin
    for j=1:col
        if (New_Circle_Image_bilibinWar_HSV(i,j,1) > valueH + 0.19)
            New_Circle_Image_bilibinWar_HSV(i,j,:) = 0;
        end
    end
end

Circle_Image_bilibinWar_HSV = Circle_Image_bilibinWar_HSV - New_Circle_Image_bilibinWar_HSV;
NEW_Image_bilibinWar_RGB = hsv2rgb(Circle_Image_bilibinWar_HSV);
figure(4); subplot(1,2,1);imshow(ImagebilibinWar);
subplot(1,2,2);imshow(NEW_Image_bilibinWar_RGB);

So can some one help me with it? i don't know if its good and if not how can i make it good ?

Body:
I don't think there is anything wrong with your code. The answer is that segmenting using euclidean distance in colors simply does not work for RGB or HSV spaces. The entire purpose of the L*a*b color space was indeed this, creating a color space where similar colors would have the little euclidean distance.

Here a less cluttered version of it:

clear all; close all;
ImagebilibinWar = imread("https://i.stack.imgur.com/wnBDu.jpg");
[lin, col, pla] = size(ImagebilibinWar);
figure;imshow(ImagebilibinWar);
ImagebilibinWarHSV= rgb2hsv(ImagebilibinWar);
[lo,co] = ginput(1);
lo = round(lo);
co = round(co);
RIOH = ImagebilibinWarHSV(lo,co,1);
RIOS = ImagebilibinWarHSV(lo,co,2);
RIOV = ImagebilibinWarHSV(lo,co,3);
%reference value that i have to choose
for a=0:0.05:1

    d = ((ImagebilibinWarHSV(:,:,1)-RIOH).^2 + (ImagebilibinWarHSV(:,:,2)-RIOS).^2+(ImagebilibinWarHSV(:,:,3)-RIOV).^2).^0.5;

    ImagebilibinWarRGB = hsv2rgb(ImagebilibinWarHSV.*double(d<a));
    figure;imshow(ImagebilibinWarRGB);
end