问:
NextJS not updating data from getStaticProps
I have a NextJS web app and NestJS backend. Locally with npm run dev or npm run build && npm start all works fine.

But deployed app (front and back in docker on different servers) not updating data on groups page.

When I build my app it generates a page with data from backend. Then I can add a new group (just new data), return to the group's page and can not see my mewGroup in the list.

My getStaticProps (not working):

export const getStaticProps: GetStaticProps<GroupProps> = async () => {
  const { getGroups, getUsers, getModules } = useHttp();
  const { data: groups } = await getGroups();

  const { data: users } = await getUsers();

  const { data: modules } = await getModules();

  return {
    props: { groups, users, modules },
    revalidate: 5
  };
};
```
<p>My post request (working):</p>
<pre class="lang-js prettyprint-override"><code>createGroup(body)
      .then(() => {
        push(routes.groups);
      })
      .catch((error) => {
        throwError && throwError(error);
      });
</code>```

Again, it works fine locally even with the production backend.
But production web does not update any info, just can push some.

It's my first NextJS app, but I worked with react.

In my production logs I see the error, but have no idea how to handle it:

Error: getaddrinfo EAI_AGAIN {{MY_BACK_SERVER}}
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:71:26) {
  errno: -3001,
  code: 'EAI_AGAIN',
  syscall: 'getaddrinfo',
  hostname: '{{MY_BACK_SERVER}}',
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/0.24.0'
    },
    method: 'get',
    url: 'http://{{MY_BACK_SERVER}}:5000/groups',
    data: undefined
  },
  request: <ref *1> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: 10485760,
      protocol: 'http:',
      path: '/groups',
      method: 'GET',
      headers: [Object],
      agent: undefined,
      agents: [Object],
      auth: undefined,
      hostname: '{{MY_BACK_SERVER}}',
      port: '5000',
      nativeProtocols: [Object],
      pathname: '/groups'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [Socket],
      _header: 'GET /groups HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'User-Agent: axios/0.24.0\r\n' +
        'Host: {{MY_BACK_SERVER}}:5000\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/groups',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: '{{MY_BACK_SERVER}}',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    _currentUrl: 'http://{{MY_BACK_SERVER}}:5000/groups',
    [Symbol(kCapture)]: false
  },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function: toJSON]
}
```

答:
so when you first open the group page it showed you the information from the static file,

there are two cases -

now if there is a modification in the data (ie befor opening the group page for the first time) it will show you the old data (as it works with stale
while revalidate cache) and update the data (in background) for group page
(getStaticProps ). so when you again visit the group page again it
will show you the updated data.

Now the second case is (the one related to you) you opened the group page it checks there is no need to update the page in the
background as there is no new data in the server, it shows you the
data and then you in the same session updated the group info (added a
new data), next js will not show those newly created data because from
here it is serving you pages from the local cache. just because it
doesn't see any update of data in the first render.

You will have to do a full refresh to see the newly created data.

recommendation - use full page refresh occasionally (programmatically) when you think there may be a new data created or user server side rendering.

Thanks

Body:
I have a NextJS web app and NestJS backend. Locally with npm run dev or npm run build && npm start all works fine.

But deployed app (front and back in docker on different servers) not updating data on groups page.

When I build my app it generates a page with data from backend. Then I can add a new group (just new data), return to the group's page and can not see my mewGroup in the list.

My getStaticProps (not working):

export const getStaticProps: GetStaticProps<GroupProps> = async () => {
  const { getGroups, getUsers, getModules } = useHttp();
  const { data: groups } = await getGroups();

  const { data: users } = await getUsers();

  const { data: modules } = await getModules();

  return {
    props: { groups, users, modules },
    revalidate: 5
  };
};

My post request (working):

createGroup(body)
      .then(() => {
        push(routes.groups);
      })
      .catch((error) => {
        throwError && throwError(error);
      });

Again, it works fine locally even with the production backend.
But production web does not update any info, just can push some.

It's my first NextJS app, but I worked with react.

In my production logs I see the error, but have no idea how to handle it:

Error: getaddrinfo EAI_AGAIN {{MY_BACK_SERVER}}
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:71:26) {
  errno: -3001,
  code: 'EAI_AGAIN',
  syscall: 'getaddrinfo',
  hostname: '{{MY_BACK_SERVER}}',
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/0.24.0'
    },
    method: 'get',
    url: 'http://{{MY_BACK_SERVER}}:5000/groups',
    data: undefined
  },
  request: <ref *1> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: 10485760,
      protocol: 'http:',
      path: '/groups',
      method: 'GET',
      headers: [Object],
      agent: undefined,
      agents: [Object],
      auth: undefined,
      hostname: '{{MY_BACK_SERVER}}',
      port: '5000',
      nativeProtocols: [Object],
      pathname: '/groups'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [Socket],
      _header: 'GET /groups HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'User-Agent: axios/0.24.0\r\n' +
        'Host: {{MY_BACK_SERVER}}:5000\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/groups',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: '{{MY_BACK_SERVER}}',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    _currentUrl: 'http://{{MY_BACK_SERVER}}:5000/groups',
    [Symbol(kCapture)]: false
  },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function: toJSON]
}


来源: stackexchange

问:
How can i get my sale price to have a different color then my regular price?
He everyone,
I was wondering how I can get the sale price to have a different color than the regular color. And have the regular price a stripe through it. Here is the link for the site: http://www.peachandhoney.nl/product/classic-chair/ but I also want it to show up in the product gallery list http://www.peachandhoney.nl/shop/. If had tried editing this with this code but it is not working it changes both the prices. Any advice on how I can achieve this?</p>

```<code>    .product .summary .price .amount {
    color: #e78484 !important; }
}
</code>```

答:
You can achieve that using only CSS like this example:</p>
```<code>.sale .price ins {
    color: #ea1000 !important;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
He everyone,
I was wondering how I can get the sale price to have a different color than the regular color. And have the regular price a stripe through it. Here is the link for the site: http://www.peachandhoney.nl/product/classic-chair/ but I also want it to show up in the product gallery list http://www.peachandhoney.nl/shop/. If had tried editing this with this code but it is not working it changes both the prices. Any advice on how I can achieve this?

    .product .summary .price .amount {
    color: #e78484 !important; }
}

Body:
You can achieve that using only CSS like this example:

.sale .price ins {
    color: #ea1000 !important;
}


问:
Is there a simpler way to check radio buttons?
I'm new to coding and learning HTML as well as JavaScript. I wrote a set of radio buttons in HTML so that you could toggle an option and click the submit button, and it would use JS to display the option you chose below. The code works fine, however:

The code is quite clunky, I'm positive there must be a much more effective way of writing this code.

I didn't use the form tag, should I? I'm still not entirely sure what form does other than I know it's used to collect data somehow

var x;

function displayText() {
  if (document.getElementById("lsd").checked === true) {
    x = document.getElementById("lsd").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("shrooms").checked === true) {
    x = document.getElementById("shrooms").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("dmt").checked === true) {
    x = document.getElementById("dmt").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("peyote").checked === true) {
    x = document.getElementById("peyote").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("toad").checked === true) {
    x = document.getElementById("toad").value;
    document.getElementById("output").innerHTML = x;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>What's your preferred psychedelic substance?</p>
<input type="radio" id="lsd" name="drugs" value="lsd">
<label for="lsd">LSD</label>
<br>
<input type="radio" id="shrooms" name="drugs" value="shrooms">
<label for="shrooms">Magic Mushrooms/psilocybin</label>
<br>
<input type="radio" id="dmt" name="drugs" value="dmt">
<label for="dmt">DMT</label>
<br>
<input type="radio" id="peyote" name="drugs" value="peyote">
<label for="peyote">Peyote</label>
<br>
<input type="radio" id="toad" name="drugs" value="toad">
<label for="toad">The Toad/5-MeO-DMT</label>
<br>
<button onclick="displayText()">Submit!</button>
<p>
  User's favorite drug is: <span id="output"></span>
</p></code>```

答:
A more powerful selector can select the element you want without manually checking each

function displayText() {
  const selected = document.querySelector("[name='drugs']:checked");

  const value = selected ? selected.value :null;

  document.getElementById("output").innerText = value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>What's your preferred psychedelic substance?</p>
<input type="radio" id="lsd" name="drugs" value="lsd">
<label for="lsd">LSD</label>
<br>
<input type="radio" id="shrooms" name="drugs" value="shrooms">
<label for="shrooms">Magic Mushrooms/psilocybin</label>
<br>
<input type="radio" id="dmt" name="drugs" value="dmt">
<label for="dmt">DMT</label>
<br>
<input type="radio" id="peyote" name="drugs" value="peyote">
<label for="peyote">Peyote</label>
<br>
<input type="radio" id="toad" name="drugs" value="toad">
<label for="toad">The Toad/5-MeO-DMT</label>
<br>
<button onclick="displayText()">Submit!</button>
<p>
  User's favorite drug is: <span id="output"></span>
</p></code>```

Body:
I'm new to coding and learning HTML as well as JavaScript. I wrote a set of radio buttons in HTML so that you could toggle an option and click the submit button, and it would use JS to display the option you chose below. The code works fine, however:

The code is quite clunky, I'm positive there must be a much more effective way of writing this code.

I didn't use the form tag, should I? I'm still not entirely sure what form does other than I know it's used to collect data somehow

var x;

function displayText() {
  if (document.getElementById("lsd").checked === true) {
    x = document.getElementById("lsd").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("shrooms").checked === true) {
    x = document.getElementById("shrooms").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("dmt").checked === true) {
    x = document.getElementById("dmt").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("peyote").checked === true) {
    x = document.getElementById("peyote").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("toad").checked === true) {
    x = document.getElementById("toad").value;
    document.getElementById("output").innerHTML = x;
  }
}

What's your preferred psychedelic substance?

<input type="radio" id="lsd" name="drugs" value="lsd">
LSD

<input type="radio" id="shrooms" name="drugs" value="shrooms">
Magic Mushrooms/psilocybin

<input type="radio" id="dmt" name="drugs" value="dmt">
DMT

<input type="radio" id="peyote" name="drugs" value="peyote">
Peyote

<input type="radio" id="toad" name="drugs" value="toad">
The Toad/5-MeO-DMT

<button onclick="displayText()">Submit!</button>

  User's favorite drug is:

Body:
A more powerful selector can select the element you want without manually checking each

function displayText() {
  const selected = document.querySelector("[name='drugs']:checked");

  const value = selected ? selected.value :null;

  document.getElementById("output").innerText = value;
}

<p>What's your preferred psychedelic substance?</p>
<input type="radio" id="lsd" name="drugs" value="lsd">
<label for="lsd">LSD</label>
<br>
<input type="radio" id="shrooms" name="drugs" value="shrooms">
<label for="shrooms">Magic Mushrooms/psilocybin</label>
<br>
<input type="radio" id="dmt" name="drugs" value="dmt">
<label for="dmt">DMT</label>
<br>
<input type="radio" id="peyote" name="drugs" value="peyote">
<label for="peyote">Peyote</label>
<br>
<input type="radio" id="toad" name="drugs" value="toad">
<label for="toad">The Toad/5-MeO-DMT</label>
<br>
<button onclick="displayText()">Submit!</button>
<p>
  User's favorite drug is: <span id="output"></span>
</p>


问:
How to place a button at the same height as a title to the right?
I would like to put my button at the top right at the same height as the title.

Here is an example:

enter image description here

My result for now

enter image description here

I think I have a problem with my divs? The button does not want to be placed at the top right.

<!DOCTYPE html>

<title>HTML CSS JS</title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Signalétique de SOLVAY BE (Euronext Brussels)

    <button type="button" (click)="goBack()" class="btn btn-primary mb-2 mr-5 ">Retour</button>

```

答:
You could use position:absolute  or float:right to make it in the right corner:

button{
position: absolute;
right:20px;
top:90px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>HTML CSS JS</title>
</head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body>
<div class="home-content container">

    <h1 class="text-start ps-3 pt-5 pb-3">Signalétique de SOLVAY BE (Euronext Brussels)</h1>
    <button type="button" (click)="goBack()" class="btn btn-primary mb-2 mr-5 ">Retour</button>
    <hr class="ms-2 mt-1 mb-5" style="width: 97%">
  </div>
</body>
</html></code>```

or use float:right:

button{
float: right
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>HTML CSS JS</title>
</head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body>
<div class="home-content container">

    <h1 class="text-start ps-3 pt-5 pb-3">Signalétique de SOLVAY BE (Euronext Brussels)</h1>
    <button type="button" (click)="goBack()" class="btn btn-primary mb-2 mr-5 ">Retour</button>
    <hr class="ms-2 mt-1 mb-5" style="width: 97%">
  </div>
</body>
</html></code>```

Body:
You could use position:absolute  or float:right to make it in the right corner:

button{
position: absolute;
right:20px;
top:90px;
}

<!DOCTYPE html>
<html>
<head>
<title>HTML CSS JS</title>
</head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body>
<div class="home-content container">

    <h1 class="text-start ps-3 pt-5 pb-3">Signalétique de SOLVAY BE (Euronext Brussels)</h1>
    <button type="button" (click)="goBack()" class="btn btn-primary mb-2 mr-5 ">Retour</button>
    <hr class="ms-2 mt-1 mb-5" style="width: 97%">
  </div>
</body>
</html>

or use float:right:

button{
float: right
}

<!DOCTYPE html>
<html>
<head>
<title>HTML CSS JS</title>
</head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body>
<div class="home-content container">

    <h1 class="text-start ps-3 pt-5 pb-3">Signalétique de SOLVAY BE (Euronext Brussels)</h1>
    <button type="button" (click)="goBack()" class="btn btn-primary mb-2 mr-5 ">Retour</button>
    <hr class="ms-2 mt-1 mb-5" style="width: 97%">
  </div>
</body>
</html>


问:
How to replace outliers of 2d array with estimated background values?
I have one 2D array called no2 which is related to the other two 2d arrays sza and vza.

Test data (test.npz, 450 KB) can be downloaded from Google Drive.

Here's the overview:

```<code>import numpy as np
import matplotlib.pyplot as plt

data = np.load('test.npz')
sza = data['sza']
vza = data['vza']
no2 = data['no2']

fig, axs = plt.subplots(2, 2, figsize=(8, 6))

ax1, ax2, ax3, ax4 = axs.flat

m = ax1.pcolormesh(no2)
plt.colorbar(m, ax=ax1)
ax1.set_title('no2')

m = ax2.pcolormesh(sza)
plt.colorbar(m, ax=ax2)
ax2.set_title('sza')

m = ax3.pcolormesh(vza)
plt.colorbar(m, ax=ax3)
ax3.set_title('vza')

s = ax4.scatter(sza, no2, c=vza, s=1)
plt.colorbar(s, ax=ax4, label='vza')
ax4.set_xlabel('sza')
ax4.set_ylabel('no2')

plt.tight_layout()
</code>```

I wanna replace the two high no2 regions based on the surrounding background or low no2 values to get something like this:

Because it seems the no2 relies on the sza linearly as shown in the last subplot, I come up with three ideas:

Curve fit

Using the fitting between no2 and sza with several vza bins to calculate the background no2 for replacing the high no2 values:

```<code>fig, axs = plt.subplots(3, 4, figsize=(12, 6))
ax = axs.flat

for index,bin in enumerate(range(5, 65, 5)):
    mask = (vza>bin)&(vza<bin+5)
    # print(index)
    s = ax[index].scatter(sza[mask], no2[mask], c=vza[mask], s=1)
    plt.colorbar(s, ax=ax[index], label='vza')
    ax[index].set_title(str(bin)+'<vza<'+str(bin+5))

for ax in axs.flat:
    ax.set_xlabel('sza')
    ax.set_ylabel('no2')

plt.tight_layout()
</code>```

I tried to fit the curve for one bin (45<sza<50):

```<code>from scipy.optimize import curve_fit

def func(x, a, b, c):
    return a * np.exp(-b * x) + c

xdata = sza[(vza>45)&(vza<50)]
ydata = no2[(vza>45)&(vza<50)]
popt, pcov = curve_fit(func, xdata, ydata, p0=(1, 1e-5, 1))

plt.plot(xdata, ydata, 'b-', label='data')

plt.plot(xdata, func(xdata, *popt), 'r-',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.legend()
</code>```

However, it failed to get what I want:

Is it possible to meet both conditions below?

- Fit curve and get the background values for high values

- Add random noise to the fitted background values (this can run several times to get more real values like the surrounding background values)

Or any other better methods?

Gradient

I checked the gradient and hoped it can make the high values more significant:

```<code># https://stackoverflow.com/questions/34003993/generating-gradient-map-of-2d-array
grad = np.gradient(no2)
fulgrad = np.sqrt(grad[0]**2 + grad[1]**2)

fig, axs = plt.subplots(1, 2, figsize=(6, 3))

ax1, ax2  = axs.flat

m = ax1.pcolormesh(no2)
plt.colorbar(m, ax=ax1)
ax1.set_title('no2')

m = ax2.pcolormesh(fulgrad)
plt.colorbar(m, ax=ax2)
ax2.set_title('no2 gradient')

plt.tight_layout()
</code>```

However, it can only show some outlines:

Image processing

I can't figure out how to replace the high values only and keep the background unchanged using the scikit-learn.

答:
Finally, I figure out how to replace the high values with estimated background values.

Just use dual-tree complex wavelet transform from scikit-ued.

```<code>import numpy as np
import matplotlib.pyplot as plt
from skued import baseline_dt

data = np.load('../data/test.npz')

baseline = baseline_dt(data['no2'], wavelet = 'qshift3', level = 6, max_iter = 150)

fig, axs = plt.subplots(1, 3, figsize=(12, 4))

ax1, ax2, ax3 = axs.flat

m = ax1.imshow(data['no2'], vmin=0, vmax=7e-4)
plt.colorbar(m, ax=ax1)
ax1.set_title('no2')

m = ax2.imshow(baseline, vmin=0, vmax=7e-4)
plt.colorbar(m, ax=ax2)
ax2.set_title('baseline')

m = ax3.imshow(data['no2']-baseline, vmin=0, vmax=7e-4)
plt.colorbar(m, ax=ax3)
ax3.set_title('no2 - baseline')
</code>```

Body:
I have one 2D array called no2 which is related to the other two 2d arrays sza and vza.

Test data (test.npz, 450 KB) can be downloaded from Google Drive.

Here's the overview:

import numpy as np
import matplotlib.pyplot as plt

data = np.load('test.npz')
sza = data['sza']
vza = data['vza']
no2 = data['no2']

fig, axs = plt.subplots(2, 2, figsize=(8, 6))

ax1, ax2, ax3, ax4 = axs.flat

m = ax1.pcolormesh(no2)
plt.colorbar(m, ax=ax1)
ax1.set_title('no2')

m = ax2.pcolormesh(sza)
plt.colorbar(m, ax=ax2)
ax2.set_title('sza')

m = ax3.pcolormesh(vza)
plt.colorbar(m, ax=ax3)
ax3.set_title('vza')

s = ax4.scatter(sza, no2, c=vza, s=1)
plt.colorbar(s, ax=ax4, label='vza')
ax4.set_xlabel('sza')
ax4.set_ylabel('no2')

plt.tight_layout()

I wanna replace the two high no2 regions based on the surrounding background or low no2 values to get something like this:

Because it seems the no2 relies on the sza linearly as shown in the last subplot, I come up with three ideas:

Curve fit

Using the fitting between no2 and sza with several vza bins to calculate the background no2 for replacing the high no2 values:

fig, axs = plt.subplots(3, 4, figsize=(12, 6))
ax = axs.flat

for index,bin in enumerate(range(5, 65, 5)):
    mask = (vza>bin)&(vza<bin+5)
    # print(index)
    s = ax[index].scatter(sza[mask], no2[mask], c=vza[mask], s=1)
    plt.colorbar(s, ax=ax[index], label='vza')
    ax[index].set_title(str(bin)+'<vza<'+str(bin+5))

for ax in axs.flat:
    ax.set_xlabel('sza')
    ax.set_ylabel('no2')

plt.tight_layout()

I tried to fit the curve for one bin (45<sza<50):

from scipy.optimize import curve_fit

def func(x, a, b, c):
    return a * np.exp(-b * x) + c

xdata = sza[(vza>45)&(vza<50)]
ydata = no2[(vza>45)&(vza<50)]
popt, pcov = curve_fit(func, xdata, ydata, p0=(1, 1e-5, 1))

plt.plot(xdata, ydata, 'b-', label='data')

plt.plot(xdata, func(xdata, *popt), 'r-',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.legend()

However, it failed to get what I want:

Is it possible to meet both conditions below?

- Fit curve and get the background values for high values

- Add random noise to the fitted background values (this can run several times to get more real values like the surrounding background values)

Or any other better methods?

Gradient

I checked the gradient and hoped it can make the high values more significant:

# https://stackoverflow.com/questions/34003993/generating-gradient-map-of-2d-array
grad = np.gradient(no2)
fulgrad = np.sqrt(grad[0]**2 + grad[1]**2)

fig, axs = plt.subplots(1, 2, figsize=(6, 3))

ax1, ax2  = axs.flat

m = ax1.pcolormesh(no2)
plt.colorbar(m, ax=ax1)
ax1.set_title('no2')

m = ax2.pcolormesh(fulgrad)
plt.colorbar(m, ax=ax2)
ax2.set_title('no2 gradient')

plt.tight_layout()

However, it can only show some outlines:

Image processing

I can't figure out how to replace the high values only and keep the background unchanged using the scikit-learn.

Body:
Finally, I figure out how to replace the high values with estimated background values.

Just use dual-tree complex wavelet transform from scikit-ued.

import numpy as np
import matplotlib.pyplot as plt
from skued import baseline_dt

data = np.load('../data/test.npz')

baseline = baseline_dt(data['no2'], wavelet = 'qshift3', level = 6, max_iter = 150)

fig, axs = plt.subplots(1, 3, figsize=(12, 4))

ax1, ax2, ax3 = axs.flat

m = ax1.imshow(data['no2'], vmin=0, vmax=7e-4)
plt.colorbar(m, ax=ax1)
ax1.set_title('no2')

m = ax2.imshow(baseline, vmin=0, vmax=7e-4)
plt.colorbar(m, ax=ax2)
ax2.set_title('baseline')

m = ax3.imshow(data['no2']-baseline, vmin=0, vmax=7e-4)
plt.colorbar(m, ax=ax3)
ax3.set_title('no2 - baseline')


问:
Group by time that spans 2 days
I am trying to get the month sales for a business where the time they are open is from 11am-2am the next day.  I tried doing the following by grouping each day assuming that just for worse case they do sales until 3am.  Assuming this is 16 hours of sales.  I haven't checked if the total is correct yet but I do notice that it only gives me back 29 days where there are 31 days in January.  a_invoices is the master invoice for each and a_tabs is the details for each invoice.

Am I doing this correctly?  I know basic MySql and this is a bit out of my pay grade.  Thanks for any help.

```<code>SELECT DATE(a_invoices.startdate - INTERVAL 16 HOUR) as day , sum(a_tabs.Total)
FROM a_invoices
Right JOIN a_tabs on a_invoices.TabId = a_tabs.TabId
WHERE a_invoices.closedate BETWEEN '2022-01-01 11:00:00' and '2022-01-30 03:00:00'
AND a_invoices.status='c' and a_tabs.status<>'v'
GROUP BY day
</code>```

答:
You have written from the 1st to the 30th. Try from the 1st to the 1st. It will also be easier to update the query each month</p>
```<code>SELECT DATE(a_invoices.startdate - INTERVAL 16 HOUR) as day , sum(a_tabs.Total)
FROM a_invoices
Right JOIN a_tabs on a_invoices.TabId = a_tabs.TabId
WHERE a_invoices.closedate BETWEEN '2022-01-01 11:00:00' and '2022-02-01 03:00:00'
AND a_invoices.status='c' and a_tabs.status<>'v'
GROUP BY day
</code>```

Title: Group by time that spans 2 days

Body:
I am trying to get the month sales for a business where the time they are open is from 11am-2am the next day.  I tried doing the following by grouping each day assuming that just for worse case they do sales until 3am.  Assuming this is 16 hours of sales.  I haven't checked if the total is correct yet but I do notice that it only gives me back 29 days where there are 31 days in January.  a_invoices is the master invoice for each and a_tabs is the details for each invoice.

Am I doing this correctly?  I know basic MySql and this is a bit out of my pay grade.  Thanks for any help.

SELECT DATE(a_invoices.startdate - INTERVAL 16 HOUR) as day , sum(a_tabs.Total)
FROM a_invoices
Right JOIN a_tabs on a_invoices.TabId = a_tabs.TabId
WHERE a_invoices.closedate BETWEEN '2022-01-01 11:00:00' and '2022-01-30 03:00:00'
AND a_invoices.status='c' and a_tabs.status<>'v'
GROUP BY day

Body:
You have written from the 1st to the 30th. Try from the 1st to the 1st. It will also be easier to update the query each month

SELECT DATE(a_invoices.startdate - INTERVAL 16 HOUR) as day , sum(a_tabs.Total)
FROM a_invoices
Right JOIN a_tabs on a_invoices.TabId = a_tabs.TabId
WHERE a_invoices.closedate BETWEEN '2022-01-01 11:00:00' and '2022-02-01 03:00:00'
AND a_invoices.status='c' and a_tabs.status<>'v'
GROUP BY day


问:
No subject alternative names matching IP address with Strimzi
I have configured a Kafka Cluster with Strimzi. I have enabled tls authentication and I have exposed the service with NodePort.

After that I have exported my ca and my password to generate a JKS to connect with Kafka. But the problem is that I'm having the next error:

java.security.cert.CertificateException: No subject alternative names
matching IP address 172.26.195.44 found

To export password and ca:

```<code>kubectl get secret kafka-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 --decode > ca.crt
kubectl get secret kafka-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.password}' | base64 --decode > ca.password
</code>```

To generate the jks I have made these steps:

```<code>keytool -genkey -alias kafka -keyalg RSA -keystore kafka.jks -keysize 2048
keytool -importkeystore -srckeystore kafka.jks -destkeystore kafka.jks -deststoretype pkcs12

export CERT_FILE_PATH=ca.crt
export CERT_PASSWORD_FILE_PATH=ca.password
export KEYSTORE_LOCATION=kafka.jks
export PASSWORD=`cat $CERT_PASSWORD_FILE_PATH`
export CA_CERT_ALIAS=strimzi-kafka-cert

sudo keytool -importcert -alias $CA_CERT_ALIAS -file $CERT_FILE_PATH -keystore $KEYSTORE_LOCATION -keypass $PASSWORD
sudo keytool -list -alias $CA_CERT_ALIAS -keystore $KEYSTORE_LOCATION
</code>```

Also I have tried adding -ext SAN=dns:test.abc.com,ip:172.26.195.44

Any idea about this?

答:
As described in the docs, when using node ports listeners, you have to by default disable the hostname verification in your client. The reason is that the node address is not known upfront to add it to the certificates and including all nodes would often not work because the worker nodes might come and go.

If you know the node addresses upfront because of your cluster configuration, you can have them added to the certificates using the alternativeNames option in the Kafka CR.

Body:
I have configured a Kafka Cluster with Strimzi. I have enabled tls authentication and I have exposed the service with NodePort.

After that I have exported my ca and my password to generate a JKS to connect with Kafka. But the problem is that I'm having the next error:

java.security.cert.CertificateException: No subject alternative names
matching IP address 172.26.195.44 found

To export password and ca:

kubectl get secret kafka-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.crt}' | base64 --decode > ca.crt
kubectl get secret kafka-cluster-cluster-ca-cert -o jsonpath='{.data.ca\.password}' | base64 --decode > ca.password

To generate the jks I have made these steps:

keytool -genkey -alias kafka -keyalg RSA -keystore kafka.jks -keysize 2048
keytool -importkeystore -srckeystore kafka.jks -destkeystore kafka.jks -deststoretype pkcs12

export CERT_FILE_PATH=ca.crt
export CERT_PASSWORD_FILE_PATH=ca.password
export KEYSTORE_LOCATION=kafka.jks
export PASSWORD=`cat $CERT_PASSWORD_FILE_PATH`
export CA_CERT_ALIAS=strimzi-kafka-cert

sudo keytool -importcert -alias $CA_CERT_ALIAS -file $CERT_FILE_PATH -keystore $KEYSTORE_LOCATION -keypass $PASSWORD
sudo keytool -list -alias $CA_CERT_ALIAS -keystore $KEYSTORE_LOCATION

Also I have tried adding -ext SAN=dns:test.abc.com,ip:172.26.195.44

Any idea about this?


问:
When do custom table view cells dealloc?
I was under the impression that table view cells never got dealloced until the app crash because you are able to resuse them. But when I was profiling my table view, I realized that something was calling dealloc on my custom cell. What exactly dealloc's custom cells and can I stop it?</p>

答:
Using the common "reuse" pattern:

```<code>- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"Foo";
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId]
                autorelease];
    }
    // update the cell content
    return cell;
}
</code>```

The table view creates as many cells as required to fill the its frame height.

When disappearing from screen they are removed from the view and put in the reuse queue, thus not deallocated.

All the cells are dealloc'd when the tableView is dealloc'd and some cells may be dealloc'd when you number of rows changes (say you had 20 cells before and only 2 after update).

You might be tempted to get rid of cells reuse but you would lose all the magic done behind to keep a low memory footprint and to have a smooth scrolling experience.

ContentLicense: CC BY-SA 3.0

Body:
Using the common "reuse" pattern:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"Foo";
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId]
                autorelease];
    }
    // update the cell content
    return cell;
}

The table view creates as many cells as required to fill the its frame height.

When disappearing from screen they are removed from the view and put in the reuse queue, thus not deallocated.

All the cells are dealloc'd when the tableView is dealloc'd and some cells may be dealloc'd when you number of rows changes (say you had 20 cells before and only 2 after update).

You might be tempted to get rid of cells reuse but you would lose all the magic done behind to keep a low memory footprint and to have a smooth scrolling experience.


问:
Idiomatic graphs in APL
APL is great for array type problems but I'm curious as to how best work with graphs in APL. I'm playing around with leet questions, for example question 662. Maximum Width of Binary Tree, the exercise works with Node objects with a value/left/right pointer style, however the test-case uses a basic array like [1,3,null,5,3]. The notation is compressed; uncompressed would be [[1], [3,null], [5,3,null,null]]. Reading layer-by-layer give [[1], [3], [5,3]] (so 2 is the widest layer).

Another example,

[5,4,7,3,null,2,null,-1,null,9] gives the answer 2

So I'm not sure the idiomatic way to work with trees. Do I use classes? Or are arrays best? In either case how do I convert the input?

I came up with a couple of solutions, but both feel inelegant. (Apologies for lack of comments)

```<code> convert←{
     prev ← {(-⌈2÷⍨≢⍵)↑⍵}
     nxt←{
         ⍵≡⍬:⍺
         m←2/×prev ⍺
         cnt←+/m
         (⍺,(m\cnt↑⍵))nxt(cnt↓⍵)
     }

     (1↑⍵)nxt(1↓⍵)
 }
</code>```

Alternatively,

```<code>convert ← {
     total←(+/×⍵)
     nxt←{
         double←×1,2↓2/0,⍵
         (((+/double)↑⍺)@⊢)double
     }
     ⍵ nxt⍣{(+/×⍺)=total}1
 }

</code>```

Both solutions are limited in they assume that 0 is null.

Once I've decompressed the input it's simply just a matter of stratifying by it's order

```<code>⌈/(1+⌈/-⌊/)∘⍸¨×nodes⊆⍨⍸2*¯1+⍳⌈2⍟≢nodes
</code>```

In Python though I could use other methods to traverse i.e. keep track of the left/right-most node on a per-depth basis.

NOTE: This may be two questions, one to decompress and the other how to traverse graphs in general, but one depends on the other

Any ideas?

答:
The work of Co-dfns compiler has given lots of insights on working tree/graph like data structures with APL.

Thesis: A Data Parallel Compiler Hosted on the GPU

GitHub repo: github.com/Co-dfns/Co-dfns (Many related goodies in project README file)

However the thesis is quite lengthy so for this particular exercise I would give a brief explanation on how to approach it.

the exercise works with Node objects with a value/left/right pointer style, however the test-case uses a basic array like [1,3,null,5,3].

Do we really actually build the tree with Node type objects to get an answer to the question? You can write the solution in something like Python and translate to APL, but that would be, losing the whole point of writing it in APL...

Notice the input is already an array! It is a bfs traverse of the binary tree. (The co-dfns compiler uses dfs traverse order, though)

so, actually what we need to do is just built a matrix like below for the input like [1,3,2,5,3,null,9] (⍬ is a placeholder value for for null):

```<code>1 ⍬ ⍬ ⍬ ⍝ level 0
3 2 ⍬ ⍬ ⍝ level 1
5 3 ⍬ 9 ⍝ level 2
</code>```

For this problem we don't need to know which node's parent is which.
We can even do something like, by abusing the fact that input has no negative value (even the number could be negative, actually we only care about if it is null), and change ⍬ to ¯1 or 0 and make it easier to compute the answer.

So the problem has became: "compute the matrix representation of the tree as variable tree from the input array, then calculate the width of each level <s>by +/0<tree, then the output is just 2*level</s> (notice the first level is level-0)" This is using wrong definition for the width. I'll show how to correct it below

And it is actually very easy to do the conversion from input to matrix, hint: ↑.

```<code>      1 (3 2) 5
┌─┬───┬─┐
│1│3 2│5│
└─┴───┴─┘
      ↑1 (3 2) 5
1 0
3 2
5 0
</code>```

Thanks for pointing out that my original solution has problem on constructing the tree matrix.

This is the corrected method for constructing the tree. To distinguish from 0 for null and the padding, I add one to the input array so 2 is for non-null and 1 is for null.

```<code> buildmatrix←{
     ⎕IO←0
     in←1+(⊂⊂'null')(≢⍤1 0)⎕JSON ⍵
     ⍝ Build the matrix
     loop←{
         (n acc)←⍺
         0=≢⍵:acc
         cur←n↑⍵
         (2×+/2=cur)(acc,⊂cur)∇ n↓⍵
     }
     ↑1 ⍬ loop in
 }
</code>```

However since the definition for width here is:

The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation.

We can just compute the width while attempting to reconstructing the tree (compute each level's width using \ and / with patterns from previous level):

If last level is 1011 and next level is 100010

```<code> 1   0   1   1
1 0 0 0 0 0 1 0
</code>```
```<code>      (2/1 0 1 1)\1 0 0 0 1 0
1 0 0 0 0 0 1 0
</code>```

So the it isn't needed to construct the complete matrix, and the answer for the exercise is just:

```<code> width←{
     ⎕IO←0
     in←(⊂⊂'null')(≢⍤1 0)⎕JSON ⍵
     ⍝ strip leading trailing zero
     strip←(⌽⍳∘1↓⊢)⍣2
     ⍝ Build the matrix
     loop←{
         (prev mw)←⍺
         0=≢⍵:mw
         cur←⍵↑⍨n←2×+/prev
         ((⊢,⍥⊂mw⌈≢)strip cur\⍨2/prev)∇ n↓⍵
     }
     (,1)1 loop 1↓in
 }
</code>```
```<code>      width '[1,null,2,3,null,4,5,6]'
2
</code>```

And the interesting fact is, you can probably do the same in other non-array based languages like Haskell. So instead of translating existing algorithms between similar looking languages, by thinking in the APL way you find new algorithms for problems!

Title: Idiomatic graphs in APL

Body:
APL is great for array type problems but I'm curious as to how best work with graphs in APL. I'm playing around with leet questions, for example question 662. Maximum Width of Binary Tree, the exercise works with Node objects with a value/left/right pointer style, however the test-case uses a basic array like [1,3,null,5,3]. The notation is compressed; uncompressed would be [[1], [3,null], [5,3,null,null]]. Reading layer-by-layer give [[1], [3], [5,3]] (so 2 is the widest layer).

Another example,

[5,4,7,3,null,2,null,-1,null,9] gives the answer 2

So I'm not sure the idiomatic way to work with trees. Do I use classes? Or are arrays best? In either case how do I convert the input?

I came up with a couple of solutions, but both feel inelegant. (Apologies for lack of comments)

 convert←{
     prev ← {(-⌈2÷⍨≢⍵)↑⍵}
     nxt←{
         ⍵≡⍬:⍺
         m←2/×prev ⍺
         cnt←+/m
         (⍺,(m\cnt↑⍵))nxt(cnt↓⍵)
     }

     (1↑⍵)nxt(1↓⍵)
 }

Alternatively,

convert ← {
     total←(+/×⍵)
     nxt←{
         double←×1,2↓2/0,⍵
         (((+/double)↑⍺)@⊢)double
     }
     ⍵ nxt⍣{(+/×⍺)=total}1
 }

Both solutions are limited in they assume that 0 is null.

Once I've decompressed the input it's simply just a matter of stratifying by it's order

⌈/(1+⌈/-⌊/)∘⍸¨×nodes⊆⍨⍸2*¯1+⍳⌈2⍟≢nodes

In Python though I could use other methods to traverse i.e. keep track of the left/right-most node on a per-depth basis.

NOTE: This may be two questions, one to decompress and the other how to traverse graphs in general, but one depends on the other

Any ideas?

Body:
The work of Co-dfns compiler has given lots of insights on working tree/graph like data structures with APL.

Thesis: A Data Parallel Compiler Hosted on the GPU

GitHub repo: github.com/Co-dfns/Co-dfns (Many related goodies in project README file)

However the thesis is quite lengthy so for this particular exercise I would give a brief explanation on how to approach it.

the exercise works with Node objects with a value/left/right pointer style, however the test-case uses a basic array like [1,3,null,5,3].

Do we really actually build the tree with Node type objects to get an answer to the question? You can write the solution in something like Python and translate to APL, but that would be, losing the whole point of writing it in APL...

Notice the input is already an array! It is a bfs traverse of the binary tree. (The co-dfns compiler uses dfs traverse order, though)

so, actually what we need to do is just built a matrix like below for the input like [1,3,2,5,3,null,9] (⍬ is a placeholder value for for null):

1 ⍬ ⍬ ⍬ ⍝ level 0
3 2 ⍬ ⍬ ⍝ level 1
5 3 ⍬ 9 ⍝ level 2

For this problem we don't need to know which node's parent is which.
We can even do something like, by abusing the fact that input has no negative value (even the number could be negative, actually we only care about if it is null), and change ⍬ to ¯1 or 0 and make it easier to compute the answer.

So the problem has became: "compute the matrix representation of the tree as variable tree from the input array, then calculate the width of each level <s>by +/0<tree, then the output is just 2*level</s> (notice the first level is level-0)" This is using wrong definition for the width. I'll show how to correct it below

And it is actually very easy to do the conversion from input to matrix, hint: ↑.

      1 (3 2) 5
┌─┬───┬─┐
│1│3 2│5│
└─┴───┴─┘
      ↑1 (3 2) 5
1 0
3 2
5 0

Thanks for pointing out that my original solution has problem on constructing the tree matrix.

This is the corrected method for constructing the tree. To distinguish from 0 for null and the padding, I add one to the input array so 2 is for non-null and 1 is for null.

 buildmatrix←{
     ⎕IO←0
     in←1+(⊂⊂'null')(≢⍤1 0)⎕JSON ⍵
     ⍝ Build the matrix
     loop←{
         (n acc)←⍺
         0=≢⍵:acc
         cur←n↑⍵
         (2×+/2=cur)(acc,⊂cur)∇ n↓⍵
     }
     ↑1 ⍬ loop in
 }

However since the definition for width here is:

The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation.

We can just compute the width while attempting to reconstructing the tree (compute each level's width using \ and / with patterns from previous level):

If last level is 1011 and next level is 100010

 1   0   1   1
1 0 0 0 0 0 1 0

      (2/1 0 1 1)\1 0 0 0 1 0
1 0 0 0 0 0 1 0

So the it isn't needed to construct the complete matrix, and the answer for the exercise is just:

 width←{
     ⎕IO←0
     in←(⊂⊂'null')(≢⍤1 0)⎕JSON ⍵
     ⍝ strip leading trailing zero
     strip←(⌽⍳∘1↓⊢)⍣2
     ⍝ Build the matrix
     loop←{
         (prev mw)←⍺
         0=≢⍵:mw
         cur←⍵↑⍨n←2×+/prev
         ((⊢,⍥⊂mw⌈≢)strip cur\⍨2/prev)∇ n↓⍵
     }
     (,1)1 loop 1↓in
 }

      width '[1,null,2,3,null,4,5,6]'
2

And the interesting fact is, you can probably do the same in other non-array based languages like Haskell. So instead of translating existing algorithms between similar looking languages, by thinking in the APL way you find new algorithms for problems!


问:
where after select using linq
I would like to add where condition  after my select but it wont let me. compiler complains and says a antonymous type for c inside the Where as it doesnt know if its clients or clientLogin

here is my code:

```<code>                    clientsLogin = (from c in db.Clients
                    join cl in db.clientLogin
                        on c.id equals cl.clientid
                    where c.active == true && cl.is_active == true
                    select new { cl, c }).ToList().
Where( c =>  DateTime.UtcNow < c.createdon.Value.AddHours(+48) && DateTime.UtcNow > c.createdon.Value.AddHours(+24)).ToList();
</code>```

答:
Apparently you have an enumerable sequence of Clients, where every Client has a DateTime property Client.CreatedOn. Furthermore every Client has a primary key Id. A Client also has a Boolean property Client.Active.

You also have an enumerable sequence of ClientLogins, where every ClientLogin has a foreign key to the Client in Client.ClientId. A ClientLogin has a Boolean property ClientLogin.IsActive.

You have the current time. From this you can create a start time and a stop time. You want all Active Clients that were Created between StartTime and StopTime, each Client with its zero or more Active ClientLogins.

Well, in fact you didn't ask for this, you wanted only combinations of [Client, ClientLogin].

The difference is that in the first Solution if Client [32] has 2000 Logins, you will only send the data of Client [32] once. The second solution will send the data of Client [32] 2000 times, the same Client data each with a different ClientLogin.

It's up to you to decide whether you want the "Clients with their Logins", or the combinations [Client, ClientLogin]

Clients with their Logins

```<code>DateTime now = DateTime.UtcNow;
DateTime startTime = now.AddHours(...);
DateTime stopTime = now.AddHours(...);      // something with your 24 and 48

var activeClientsWithTheirActiveLogins = dbContext.Clients.
    .Where(client => client.Active
                  && startTime <= client.CreatedOn
                  && client.CreatedOn <= stopTime)
</code>```

I'm not sure about your condition, whether it should be inside or outside your StartTime and StopTime, but hey, if you wanted a complete answer, next time give us a requirement in words. I guess you'll get the gist. By the way, did you notice that because of this, I'll calculate now and the time limits only once?

Continuing the LINQ: GroupJoin with Active ClientLogins

```<code>    .GroupJoin(dbContext.ClientLogins.Where(login => login.IsActive),
        client => client.Id,        // from every Client take the primary key
        login => login.ClientId,    // from every ClientLogin take the foreign key

        // parameter resultSelector: for every Clients, each with its zero or more ClientLogins
        // make one new:
        (client, loginsOfThisClient) => new
        {
            // Select only the properties of the Client that you plan to use
            Id = client.Id,
            Name = client.Name,
            ...

            // do not select, you already know that it is true
            // Active = client.Active,

            Logins = loginsOfThisClient.Select(login => new
            {
                // Select only the properties of the ClientLogin that you plan to use
                Id = login.Id,
                ...

                // do not select the foreign key, you already know the value
                // ClientId = login.ClientId,
            })
            .ToList(),
        });
</code>```

Database management systems are extremely optimized for selecting data. One of the slower parts of your queries is the transport of data from the DBMS to your local process, hence it is wise to limit the transported data as much as possible. Only select properties that you plan to use.

Query [Client, Login] combinations

Your query will be similar. Instead of a GroupJoin use a Join:

```<code>var result = dbContext.Clients.
    .Where(client => client.Active
                  && startTime <= client.CreatedOn
                  && client.CreatedOn <= stopTime)
    .Join(dbContext.ClientLogins.Where(login => login.IsActive),
        client => client.Id,        // from every Client take the primary key
        login => login.ClientId,    // from every ClientLogin take the foreign key

        // Parameter resultSelector: for every [Client, Login] combination,
        // make one new
        (client, login) => new
        {
            Client = new
            {
                Id = client.Id,
                Name = client.Name,
                ...
            },
            Login = new
            {
                Id = login.Id,
                ...
            },
        });
</code>```

There is a difference!

Apart from the fact that GroupJoin will be more efficient, there is a difference in data that you get. The GroupJoin will also return you "Clients without active ClientLogins". The Join won't have them.

If you don't want Clients without Logins, add an extra Where:

```<code>.Where(client => client.Logins.Any());
</code>```

Title: where after select using linq

Body:
I would like to add where condition  after my select but it wont let me. compiler complains and says a antonymous type for c inside the Where as it doesnt know if its clients or clientLogin

here is my code:

                    clientsLogin = (from c in db.Clients
                    join cl in db.clientLogin
                        on c.id equals cl.clientid
                    where c.active == true && cl.is_active == true
                    select new { cl, c }).ToList().
Where( c =>  DateTime.UtcNow < c.createdon.Value.AddHours(+48) && DateTime.UtcNow > c.createdon.Value.AddHours(+24)).ToList();

Body:
Apparently you have an enumerable sequence of Clients, where every Client has a DateTime property Client.CreatedOn. Furthermore every Client has a primary key Id. A Client also has a Boolean property Client.Active.

You also have an enumerable sequence of ClientLogins, where every ClientLogin has a foreign key to the Client in Client.ClientId. A ClientLogin has a Boolean property ClientLogin.IsActive.

You have the current time. From this you can create a start time and a stop time. You want all Active Clients that were Created between StartTime and StopTime, each Client with its zero or more Active ClientLogins.

Well, in fact you didn't ask for this, you wanted only combinations of [Client, ClientLogin].

The difference is that in the first Solution if Client [32] has 2000 Logins, you will only send the data of Client [32] once. The second solution will send the data of Client [32] 2000 times, the same Client data each with a different ClientLogin.

It's up to you to decide whether you want the "Clients with their Logins", or the combinations [Client, ClientLogin]

Clients with their Logins

DateTime now = DateTime.UtcNow;
DateTime startTime = now.AddHours(...);
DateTime stopTime = now.AddHours(...);      // something with your 24 and 48

var activeClientsWithTheirActiveLogins = dbContext.Clients.
    .Where(client => client.Active
                  && startTime <= client.CreatedOn
                  && client.CreatedOn <= stopTime)

I'm not sure about your condition, whether it should be inside or outside your StartTime and StopTime, but hey, if you wanted a complete answer, next time give us a requirement in words. I guess you'll get the gist. By the way, did you notice that because of this, I'll calculate now and the time limits only once?

Continuing the LINQ: GroupJoin with Active ClientLogins

    .GroupJoin(dbContext.ClientLogins.Where(login => login.IsActive),
        client => client.Id,        // from every Client take the primary key
        login => login.ClientId,    // from every ClientLogin take the foreign key

        // parameter resultSelector: for every Clients, each with its zero or more ClientLogins
        // make one new:
        (client, loginsOfThisClient) => new
        {
            // Select only the properties of the Client that you plan to use
            Id = client.Id,
            Name = client.Name,
            ...

            // do not select, you already know that it is true
            // Active = client.Active,

            Logins = loginsOfThisClient.Select(login => new
            {
                // Select only the properties of the ClientLogin that you plan to use
                Id = login.Id,
                ...

                // do not select the foreign key, you already know the value
                // ClientId = login.ClientId,
            })
            .ToList(),
        });

Database management systems are extremely optimized for selecting data. One of the slower parts of your queries is the transport of data from the DBMS to your local process, hence it is wise to limit the transported data as much as possible. Only select properties that you plan to use.

Query [Client, Login] combinations

Your query will be similar. Instead of a GroupJoin use a Join:

var result = dbContext.Clients.
    .Where(client => client.Active
                  && startTime <= client.CreatedOn
                  && client.CreatedOn <= stopTime)
    .Join(dbContext.ClientLogins.Where(login => login.IsActive),
        client => client.Id,        // from every Client take the primary key
        login => login.ClientId,    // from every ClientLogin take the foreign key

        // Parameter resultSelector: for every [Client, Login] combination,
        // make one new
        (client, login) => new
        {
            Client = new
            {
                Id = client.Id,
                Name = client.Name,
                ...
            },
            Login = new
            {
                Id = login.Id,
                ...
            },
        });

There is a difference!

Apart from the fact that GroupJoin will be more efficient, there is a difference in data that you get. The GroupJoin will also return you "Clients without active ClientLogins". The Join won't have them.

If you don't want Clients without Logins, add an extra Where:

.Where(client => client.Logins.Any());


问:
Java Recursive Function will not return a value
I am creating this binary search function that finds the correct point to return but never actually returns a value.

'''

```<code>class Test {

static int binarySearch(int[] arr, int start, int end, int key) {
    int mid = (end - start) / 2 + start;
    while (end - start >= 1) {
        System.out.println(start + " " + mid + " " + end);
        if (arr[mid] == key) {
            System.out.println("returning " + mid);
            return mid;
        } else if (arr[mid] > key) {
            binarySearch(arr, start, mid, key);
        }else if (arr[mid] < key) {
            binarySearch(arr, mid, end, key);
        }
    }
    return -1;
}

public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 6};
    int x = binarySearch(arr, 0, arr.length, 6);
    System.out.println(x);

}

}
</code>```

'''

Mid becomes 5 and it prints returning 5 but then skips the return statement and continues to loop. Why doesn't this just return 5?

答:
If you want to return a value from a nested call, you have to write code to do that.

You wrote:

```<code> binarySearch(arr, start, mid, key);
</code>```

which means (1) the return value from this is ignored, and (2) you will likely eventually fall through to the final 'return -1'.  The net effect is that the nested call is completely ineffective.

You presumably (I have not analyzed the code in detail) wanted:

```<code>return binarySearch(arr, start, mid, key);
</code>```

It occurs to me that perhaps you don't realize that 'return' only terminates the current execution of the method in which it is executed.  It does not somehow unwind all of the nested calls and return from the outermost invocation.

So, 'return 5' returns 5 from the innermost level, and you're popped back into the loop at the next level out, and will carry on looping (and ignoring the 5).

But as a commenter observed, there's no need for the recursion with the loop, or else there's no need for the loop with the recursion.

Body:
I am creating this binary search function that finds the correct point to return but never actually returns a value.

'''

class Test {

static int binarySearch(int[] arr, int start, int end, int key) {
    int mid = (end - start) / 2 + start;
    while (end - start >= 1) {
        System.out.println(start + " " + mid + " " + end);
        if (arr[mid] == key) {
            System.out.println("returning " + mid);
            return mid;
        } else if (arr[mid] > key) {
            binarySearch(arr, start, mid, key);
        }else if (arr[mid] < key) {
            binarySearch(arr, mid, end, key);
        }
    }
    return -1;
}

public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 6};
    int x = binarySearch(arr, 0, arr.length, 6);
    System.out.println(x);

}

}

'''

Mid becomes 5 and it prints returning 5 but then skips the return statement and continues to loop. Why doesn't this just return 5?

Body:
If you want to return a value from a nested call, you have to write code to do that.

You wrote:

 binarySearch(arr, start, mid, key);

which means (1) the return value from this is ignored, and (2) you will likely eventually fall through to the final 'return -1'.  The net effect is that the nested call is completely ineffective.

You presumably (I have not analyzed the code in detail) wanted:

return binarySearch(arr, start, mid, key);

It occurs to me that perhaps you don't realize that 'return' only terminates the current execution of the method in which it is executed.  It does not somehow unwind all of the nested calls and return from the outermost invocation.

So, 'return 5' returns 5 from the innermost level, and you're popped back into the loop at the next level out, and will carry on looping (and ignoring the 5).

But as a commenter observed, there's no need for the recursion with the loop, or else there's no need for the loop with the recursion.


问:
Propagating details of an error upwards in Rust
I would like to have the details of an error be propagated upwards. I used error-chain previously, but that has not been maintained or kept compatible with the rest of the ecosystem as far as i can tell.

For example, in this example:

```<code>use std::str::FromStr;
use anyhow::Result;

fn fail() -> Result<u64> {
  Ok(u64::from_str("Some String")?)
}

fn main() {

  if let Err(e) = fail(){
    println!("{:?}", e);
  }
</code>```

The error i am getting is:

```<code>invalid digit found in string
</code>```

I would need the error message to have the key details, including at the point of failure, for example:

```<code>- main: invalid digit found in string
- fail: "Some String" is not a valid digit
</code>```

What's the best way of doing this?

答:
This is a tricky thing to accomplish and I'm not sure that there is a simple and non-invasive way to capture all of the details of any possible error without knowledge of the particular function being invoked.  For example, we may want to display some arguments to the function call that failed, but evaluating other arguments might be problematic -- they may not even be able to be turned into strings.

Maybe the argument is another function call, too, so should we capture its arguments or only its return value?

I whipped up this example quickly to show that we can at least fairly trivially capture the exact source expression.  It provides a detail_error! macro that takes an expression that produces Result<T, E> and emits an expression that procudes Result<T, DetailError<E>>.  The DetailError wraps the original error value and additionally contains a reference to a string of the original source code fed to the macro.

```<code>use std::error::Error;
use std::str::FromStr;

#[derive(Debug)]
struct DetailError<T: Error> {
    expr: &'static str,
    cause: T,
}

impl<T: Error> DetailError<T> {
    pub fn new(expr: &'static str, cause: T) -> DetailError<T> {
        DetailError { expr, cause }
    }

    // Some getters we don't use in this example, but should be present to have
    // a complete API.
    #[allow(dead_code)]
    pub fn cause(&self) -> &T {
        &self.cause
    }

    #[allow(dead_code)]
    pub fn expr(&self) -> &'static str {
        self.expr
    }
}

impl<T: Error> Error for DetailError<T> { }

impl<T: Error> std::fmt::Display for DetailError<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        write!(f, "While evaluating ({}): ", self.expr)?;
        std::fmt::Display::fmt(&self.cause, f)
    }
}

macro_rules! detail_error {
    ($e:expr) => {
        ($e).map_err(|err| DetailError::new(stringify!($e), err))
    }
}

fn main() {
    match detail_error!(u64::from_str("Some String")) {
        Ok(_) => {},
        Err(e) => { println!("{}", e); }
    };
}
</code>```

This produces the runtime output:

```<code>While evaluating (u64::from_str("Some String")): invalid digit found in string
</code>```

Note that this only shows the string because it's a literal in the source. If you pass a variable/parameter instead, you will see that identifier in the error message instead of the string.

Body:
I would like to have the details of an error be propagated upwards. I used error-chain previously, but that has not been maintained or kept compatible with the rest of the ecosystem as far as i can tell.

For example, in this example:

use std::str::FromStr;
use anyhow::Result;

fn fail() -> Result<u64> {
  Ok(u64::from_str("Some String")?)
}

fn main() {

  if let Err(e) = fail(){
    println!("{:?}", e);
  }

The error i am getting is:

invalid digit found in string

I would need the error message to have the key details, including at the point of failure, for example:

- main: invalid digit found in string
- fail: "Some String" is not a valid digit

What's the best way of doing this?

Body:
This is a tricky thing to accomplish and I'm not sure that there is a simple and non-invasive way to capture all of the details of any possible error without knowledge of the particular function being invoked.  For example, we may want to display some arguments to the function call that failed, but evaluating other arguments might be problematic -- they may not even be able to be turned into strings.

Maybe the argument is another function call, too, so should we capture its arguments or only its return value?

I whipped up this example quickly to show that we can at least fairly trivially capture the exact source expression.  It provides a detail_error! macro that takes an expression that produces Result<T, E> and emits an expression that procudes Result<T, DetailError<E>>.  The DetailError wraps the original error value and additionally contains a reference to a string of the original source code fed to the macro.

use std::error::Error;
use std::str::FromStr;

#[derive(Debug)]
struct DetailError<T: Error> {
    expr: &'static str,
    cause: T,
}

impl<T: Error> DetailError<T> {
    pub fn new(expr: &'static str, cause: T) -> DetailError<T> {
        DetailError { expr, cause }
    }

    // Some getters we don't use in this example, but should be present to have
    // a complete API.
    #[allow(dead_code)]
    pub fn cause(&self) -> &T {
        &self.cause
    }

    #[allow(dead_code)]
    pub fn expr(&self) -> &'static str {
        self.expr
    }
}

impl<T: Error> Error for DetailError<T> { }

impl<T: Error> std::fmt::Display for DetailError<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        write!(f, "While evaluating ({}): ", self.expr)?;
        std::fmt::Display::fmt(&self.cause, f)
    }
}

macro_rules! detail_error {
    ($e:expr) => {
        ($e).map_err(|err| DetailError::new(stringify!($e), err))
    }
}

fn main() {
    match detail_error!(u64::from_str("Some String")) {
        Ok(_) => {},
        Err(e) => { println!("{}", e); }
    };
}

This produces the runtime output:

While evaluating (u64::from_str("Some String")): invalid digit found in string

Note that this only shows the string because it's a literal in the source. If you pass a variable/parameter instead, you will see that identifier in the error message instead of the string.


问:
What is the best way to stop people hacking the PHP-based highscore table of a Flash game
I'm talking about an action game with no upper score limit and no way to verify the score on the server by replaying moves etc.

What I really need is the strongest encryption possible in Flash/PHP, and a way to prevent people calling the PHP page other than through my Flash file. I have tried some simple methods in the past of making multiple calls for a single score and completing a checksum / fibonacci sequence etc, and also obfuscating the SWF with Amayeta SWF Encrypt, but they were all hacked eventually.

Thanks to StackOverflow responses I have now found some more info from Adobe - http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html and https://github.com/mikechambers/as3corelib - which I think I can use for the encryption. Not sure this will get me around CheatEngine though.

I need to know the best solutions for both AS2 and AS3, if they are different.

The main problems seem to be things like TamperData and LiveHTTP headers, but I understand there are more advanced hacking tools as well - like CheatEngine (thanks Mark Webster)

答:
In the accepted answer tqbf mentions that you can just do a memory search for the score variable ("My score is 666 so I look for the number 666 in memory").

There's a way around this. I have a class here: http://divillysausages.com/blog/safenumber_and_safeint

Basically, you have an object to store your score. In the setter it multiplies the value that you pass it with a random number (+ and -), and in the getter you divide the saved value by the random multiplicator to get the original back. It's simple, but helps stop memory search.

Also, check out the video from some of the guys behind the PushButton engine who talk about some of the different ways you can combat hacking: http://zaa.tv/2010/12/the-art-of-hacking-flash-games/. They were the inspiration behind the class.

OwnerDisplayName: Iain


问:
Angular elements web component creating memory leak
I created two pages first one is listing & the second one is details page with mat-tabs. One of the tab contains web component(ViewComponent) created using angular/elements.

Following is the html for the details page.

<mat-tab-group>
<-- other tabs -->

    <mat-tab *ngIf="tabName === viewComp">
      <ng-template mat-tab-label>
        {{ label }}
      </ng-template>
      <ng-container
        *ngIf="loadedTabs.viewComp && apiSuccess"
      >

          <-- ViewComponent is web component created using angular/elements -->
          <view-component
            [data]="viewCompData"
          ></view-component>

      </ng-container>
    </mat-tab>
</mat-tab-group>
```

Now if I go back to listing page from details. ViewComponent still persist in memory following is screenshot of memory snapshot after garbage collection.

Now if I remove the div element with testCondition then in the retainers window its showing nameSpacesByHostElement instead of collectedLeaveElements.

Clicking on the top __ngContext__ in Detached HTMLElement@236587 jumps to following source - constructor of NgElementImpl.

Please let me know how can I remove ViewComponent permanently from memory.
Using Angular(v10.2) / material components(v10.2).

答:
The single most annoying cause of memory leaks on angular (or maybe rxjs) are orphaned Observable subscriptions. And, by looking at your shared code you should also use the matTabContent directive.

Component subscriptions

To resolve it you need to unsubscribe every time the component which contains the subscription is destroyed. This blog has good info about this issue.

One way to do it is to never call .subscribe in the component, as angular async pipe handles the view subscription/unsubscription. This can be hard at times, and might require sizeable refactoring on established apps.

Another way (my preference to be honest when it is hard enough to avoid subscribe from the component) is to use .pipe(takeuntil(this.unsubscribed$)). This is somewhat described on that blog I attached earlier.

My take has been to create a base component:

```<code>import { Injectable, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export abstract class BaseComponent implements OnDestroy {
    private unsubscribed$: Subject<void>;
    redirectTo: string;

    get destroy$() {
        if (!this.unsubscribed$) {
            this.unsubscribed$ = new Subject();
        }
        return this.unsubscribed$;
    }

    ngOnDestroy() {
        if (this.unsubscribed$) {
            this.unsubscribed$.next();
            this.unsubscribed$.complete();
        }
    }
}
</code>```

and than from your component's body:

```<code>(...)
export class YourComponent extends BaseComponent (...)

  constructor(...) {
    super()
  }

</code>```

using the following pattern when you need a subscription:

```<code>this.user$.pipe(takeUntil(this.destroy$)).subscribe(user => {
</code>```

Directive matTabContent on <mat-tab tag

using the matTabContent on <mat-tab tags, only the visible tab is loaded. to use it, change your mat-tab contents to be contarned by a <ng-template matTabContent>:

```<code><mat-tab>
  <ng-template matTabContent>
     (your contents here)
  </ng-template matTabContent>
</mat-tab>
</code>```

I cannot tell what else might be causing your memory leaks, but this should get you started.

Body:
I created two pages first one is listing & the second one is details page with mat-tabs. One of the tab contains web component(ViewComponent) created using angular/elements.

Following is the html for the details page.

<mat-tab-group>
<-- other tabs -->

    <mat-tab *ngIf="tabName === viewComp">
      <ng-template mat-tab-label>
        {{ label }}
      </ng-template>
      <ng-container
        *ngIf="loadedTabs.viewComp && apiSuccess"
      >

          <-- ViewComponent is web component created using angular/elements -->
          <view-component
            [data]="viewCompData"
          ></view-component>

      </ng-container>
    </mat-tab>
</mat-tab-group>

Now if I go back to listing page from details. ViewComponent still persist in memory following is screenshot of memory snapshot after garbage collection.

Now if I remove the div element with testCondition then in the retainers window its showing nameSpacesByHostElement instead of collectedLeaveElements.

Clicking on the top __ngContext__ in Detached HTMLElement@236587 jumps to following source - constructor of NgElementImpl.

Please let me know how can I remove ViewComponent permanently from memory.
Using Angular(v10.2) / material components(v10.2).

Body:
The single most annoying cause of memory leaks on angular (or maybe rxjs) are orphaned Observable subscriptions. And, by looking at your shared code you should also use the matTabContent directive.

Component subscriptions

To resolve it you need to unsubscribe every time the component which contains the subscription is destroyed. This blog has good info about this issue.

One way to do it is to never call .subscribe in the component, as angular async pipe handles the view subscription/unsubscription. This can be hard at times, and might require sizeable refactoring on established apps.

Another way (my preference to be honest when it is hard enough to avoid subscribe from the component) is to use .pipe(takeuntil(this.unsubscribed$)). This is somewhat described on that blog I attached earlier.

My take has been to create a base component:

import { Injectable, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export abstract class BaseComponent implements OnDestroy {
    private unsubscribed$: Subject<void>;
    redirectTo: string;

    get destroy$() {
        if (!this.unsubscribed$) {
            this.unsubscribed$ = new Subject();
        }
        return this.unsubscribed$;
    }

    ngOnDestroy() {
        if (this.unsubscribed$) {
            this.unsubscribed$.next();
            this.unsubscribed$.complete();
        }
    }
}

and than from your component's body:

(...)
export class YourComponent extends BaseComponent (...)

  constructor(...) {
    super()
  }

using the following pattern when you need a subscription:

this.user$.pipe(takeUntil(this.destroy$)).subscribe(user => {

Directive matTabContent on <mat-tab tag

using the matTabContent on <mat-tab tags, only the visible tab is loaded. to use it, change your mat-tab contents to be contarned by a <ng-template matTabContent>:

<mat-tab>
  <ng-template matTabContent>
     (your contents here)
  </ng-template matTabContent>
</mat-tab>

I cannot tell what else might be causing your memory leaks, but this should get you started.


问:
Linq - Join collection with child collection of other collection
I have a collection of users, each with a child collection of memberships. And then I also have a club collection. The child collection of each user is populated with memberships containing a club ID only. What I want is for each membership to also contain the club entity matching the club ID.

My entities:

public class User
{
    public string Name { get; set; }
    public IEnumerable<Membership> Memberships { get; set; }
}
public class Membership
{
    public Guid ClubId { get; set; }
    public Club Club { get; set; }
}
public class Club
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}
```
<p>Populated with data:</p>
<pre class="lang-cs prettyprint-override"><code>var club1Id = new Guid("FFEB77B9-1616-463B-B36E-F95F7E255FDE");
var club2Id = new Guid("7A6ECD38-5AEB-418B-9DD5-FBD777CE190C");

var users = new List<User>
{
    new User
    {
        Name = "Patrick Stewart",
        Memberships = new List<Membership>
        {
            new Membership { ClubId = club1Id },
            new Membership { ClubId = club2Id }
        }
    },
    new User
    {
        Name = "Brent Spiner",
        Memberships = new List<Membership>
        {
            new Membership { ClubId = club1Id }
        }
    },
    new User
    {
        Name = "Wesley Crusher",
        Memberships = null
    }
};

var clubs = new List<Club>
{
    new Club
    {
        Id = club1Id,
        Name = "Officers Club"
    },
    new Club
    {
        Id = club2Id,
        Name = "Captains Club"
    }
};

</code>```

And then I need a LINQ query that adds the matched Club objects to the Membership objects.

So that when I print out users like this:

foreach (var user in users)
{
    Console.WriteLine($"User: {user.Name}");
    if (user.Memberships != null)
    {
        foreach (var membership in user.Memberships)
        {
            Console.WriteLine($"  Membership: {membership.Club?.Name}");
        }
    }
}
```
<p>It will look like this:</p>
```User: Patrick Stewart
  Membership: Officers Club
  Membership: Captains Club
User: Brent Spiner
  Membership: Officers Club
User: Wesley Crusher
```

I want to do it in one go with a LINQ expression, so that I don't have to involve for-loops.

答:
I ended up solving it with this LINQ expression:

users = users.Select(user => new {
        user,
        Memberships = user.Memberships?
        .GroupJoin(clubs, membership => membership.ClubId, club => club.Id, (membership, club) => new { membership, club})
        .SelectMany(mc => mc.club.DefaultIfEmpty(), (mc, club) =>
        {
            mc.membership.Club = club;
            return mc.membership;
        })
    })
    .Select(x =>
    {
        x.user.Memberships = x.Memberships;
        return x.user;
    })
    .ToList();
```

Body:
I have a collection of users, each with a child collection of memberships. And then I also have a club collection. The child collection of each user is populated with memberships containing a club ID only. What I want is for each membership to also contain the club entity matching the club ID.

My entities:

public class User
{
    public string Name { get; set; }
    public IEnumerable<Membership> Memberships { get; set; }
}
public class Membership
{
    public Guid ClubId { get; set; }
    public Club Club { get; set; }
}
public class Club
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

Populated with data:

var club1Id = new Guid("FFEB77B9-1616-463B-B36E-F95F7E255FDE");
var club2Id = new Guid("7A6ECD38-5AEB-418B-9DD5-FBD777CE190C");

var users = new List<User>
{
    new User
    {
        Name = "Patrick Stewart",
        Memberships = new List<Membership>
        {
            new Membership { ClubId = club1Id },
            new Membership { ClubId = club2Id }
        }
    },
    new User
    {
        Name = "Brent Spiner",
        Memberships = new List<Membership>
        {
            new Membership { ClubId = club1Id }
        }
    },
    new User
    {
        Name = "Wesley Crusher",
        Memberships = null
    }
};

var clubs = new List<Club>
{
    new Club
    {
        Id = club1Id,
        Name = "Officers Club"
    },
    new Club
    {
        Id = club2Id,
        Name = "Captains Club"
    }
};

And then I need a LINQ query that adds the matched Club objects to the Membership objects.

So that when I print out users like this:

foreach (var user in users)
{
    Console.WriteLine($"User: {user.Name}");
    if (user.Memberships != null)
    {
        foreach (var membership in user.Memberships)
        {
            Console.WriteLine($"  Membership: {membership.Club?.Name}");
        }
    }
}

It will look like this:

User: Patrick Stewart
  Membership: Officers Club
  Membership: Captains Club
User: Brent Spiner
  Membership: Officers Club
User: Wesley Crusher

I want to do it in one go with a LINQ expression, so that I don't have to involve for-loops.


问:
Ignoring invalid configuration option passed to Connection: root
I am getting started with mysql database for my NODEJS application
const mysql = require('mysql2');

```<code>const pool = mysql.createPool({
  host: 'localhost',
  root: 'root',
  database:'node-complete',
  password: 'Pratik@123'
})
</code>```

My root password is the one coded above.

I am getting this error:-

Ignoring invalid configuration option passed to Connection: root.
This is currently a warning, but in future versions of MySQL2, an error will be thrown if you pass an invalid configuration option to a Connection

Can some help me to fix this issue?

```<code>module.exports = pool.promise()
</code>```

答:
I was getting the same problem, i used

```<code>const pool = mysql.createPool({
    host: 'localhost',
    username: 'root',
    database: 'node-complete',
    password: '24GM@L@PM+AU',
    port: '3306'
});
</code>```

its not supposed to say "username" but instead just "user" like below

```<code>const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    database: 'node-complete',
    password: '24GM@L@PM+AU',
    port: '3306'
});
</code>```

Body:
I am getting started with mysql database for my NODEJS application
const mysql = require('mysql2');

const pool = mysql.createPool({
  host: 'localhost',
  root: 'root',
  database:'node-complete',
  password: 'Pratik@123'
})

My root password is the one coded above.

I am getting this error:-

Ignoring invalid configuration option passed to Connection: root.
This is currently a warning, but in future versions of MySQL2, an error will be thrown if you pass an invalid configuration option to a Connection

Can some help me to fix this issue?

module.exports = pool.promise()

Body:
I was getting the same problem, i used

const pool = mysql.createPool({
    host: 'localhost',
    username: 'root',
    database: 'node-complete',
    password: '24GM@L@PM+AU',
    port: '3306'
});

its not supposed to say "username" but instead just "user" like below

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    database: 'node-complete',
    password: '24GM@L@PM+AU',
    port: '3306'
});


问:
ReferenceError: ResizeObserver is not defined with nivo and NextJS
I want to use nivo with Next but when I load the page containing a pie chart made with nivo, I get this error: ReferenceError: ResizeObserver is not defined.

My Pie.js component:

import { ResponsivePie } from "@nivo/pie";

export const data = [
  {
    id: "c",
    label: "c",
    value: 80,
    color: "hsl(8, 70%, 50%)",
  },
  {
    id: "lisp",
    label: "lisp",
    value: 188,
    color: "hsl(122, 70%, 50%)",
  },

  {
    id: "go",
    label: "go",
    value: 161,
    color: "hsl(111, 70%, 50%)",
  },
];

export default function MyPie({ data }) {

    return (
        <ResponsivePie
            data={data}
            margin={{ top: 40, right: 80, bottom: 80, left: 80 }}
            innerRadius={0.5}
            padAngle={0.7}
            cornerRadius={3}
            activeOuterRadiusOffset={8}
            borderWidth={1}
            borderColor={{ from: "color", modifiers: [["darker", 0.2]] }}
            arcLinkLabelsSkipAngle={10}
            arcLinkLabelsTextColor="#333333"
            arcLinkLabelsThickness={2}
            arcLinkLabelsColor={{ from: "color" }}
            arcLabelsSkipAngle={10}
            arcLabelsTextColor={{ from: "color", modifiers: [["darker", 2]] }}
            defs={[
            {
                id: "dots",
                type: "patternDots",
                background: "inherit",
                color: "rgba(255, 255, 255, 0.3)",
                size: 4,
                padding: 1,
                stagger: true,
            },
            {
                id: "lines",
                type: "patternLines",
                background: "inherit",
                color: "rgba(255, 255, 255, 0.3)",
                rotation: -45,
                lineWidth: 6,
                spacing: 10,
            },
            ]}
        />
    )
};
```
<p>My <code>chart.js</code> page:</p>
<pre class="lang-js prettyprint-override"><code>import MyPie, { data } from "../components/Pie";

import homeStyles from "../styles/Home.module.css";

function Chart() {
  return (
    <div className={homeStyles.divchart}>
      <MyPie data={data}/>
    </div>
  );
};
export default Chart;
</code>```

This error only appears when using ResponsivePie and not Pie. I also tried to make it work with a React project but though I don't get this error, Nothing seems to be displayed.

Edit:

After some investigations, it looks like there is something wrong with @nivo/core 0.79.0 dependency. We should open an issue on the GitHub repo. I made some changes to check whether it is caused by my version of Next.js but the bug occurs only with @nivo/core 0.79.0.

答:
It turns out this was the result of a bug introduced in version 0.79.0, which was fixed in https://github.com/plouc/nivo/pull/1886.

You should update @nivo/core to 0.79.1.

It looks like @nivo/pie is not compatible with Next.js server-side rendering as it utilizes Web APIs (ResizeObserver).

To avoid importing MyPie (and subsequently ResponsivePie) on the server, you can dynamically import it on the client-side only using next/dynamic with ssr: false.

import dynamic from "next/dynamic";
import { data } from "../components/Pie";
import homeStyles from "../styles/Home.module.css";

const MyPie = dynamic(() => import("../components/Pie"), {
    ssr: false
})

function Chart() {
    return (

            <MyPie data={data}/>

    );
};

export default Chart;
```

Body:
I want to use nivo with Next but when I load the page containing a pie chart made with nivo, I get this error: ReferenceError: ResizeObserver is not defined.

My Pie.js component:

import { ResponsivePie } from "@nivo/pie";

export const data = [
  {
    id: "c",
    label: "c",
    value: 80,
    color: "hsl(8, 70%, 50%)",
  },
  {
    id: "lisp",
    label: "lisp",
    value: 188,
    color: "hsl(122, 70%, 50%)",
  },

  {
    id: "go",
    label: "go",
    value: 161,
    color: "hsl(111, 70%, 50%)",
  },
];

export default function MyPie({ data }) {

    return (
        <ResponsivePie
            data={data}
            margin={{ top: 40, right: 80, bottom: 80, left: 80 }}
            innerRadius={0.5}
            padAngle={0.7}
            cornerRadius={3}
            activeOuterRadiusOffset={8}
            borderWidth={1}
            borderColor={{ from: "color", modifiers: [["darker", 0.2]] }}
            arcLinkLabelsSkipAngle={10}
            arcLinkLabelsTextColor="#333333"
            arcLinkLabelsThickness={2}
            arcLinkLabelsColor={{ from: "color" }}
            arcLabelsSkipAngle={10}
            arcLabelsTextColor={{ from: "color", modifiers: [["darker", 2]] }}
            defs={[
            {
                id: "dots",
                type: "patternDots",
                background: "inherit",
                color: "rgba(255, 255, 255, 0.3)",
                size: 4,
                padding: 1,
                stagger: true,
            },
            {
                id: "lines",
                type: "patternLines",
                background: "inherit",
                color: "rgba(255, 255, 255, 0.3)",
                rotation: -45,
                lineWidth: 6,
                spacing: 10,
            },
            ]}
        />
    )
};

My chart.js page:

import MyPie, { data } from "../components/Pie";

import homeStyles from "../styles/Home.module.css";

function Chart() {
  return (

      <MyPie data={data}/>

  );
};
export default Chart;

This error only appears when using ResponsivePie and not Pie. I also tried to make it work with a React project but though I don't get this error, Nothing seems to be displayed.

Edit:

After some investigations, it looks like there is something wrong with @nivo/core 0.79.0 dependency. We should open an issue on the GitHub repo. I made some changes to check whether it is caused by my version of Next.js but the bug occurs only with @nivo/core 0.79.0.

Body:
It turns out this was the result of a bug introduced in version 0.79.0, which was fixed in https://github.com/plouc/nivo/pull/1886.

You should update @nivo/core to 0.79.1.

It looks like @nivo/pie is not compatible with Next.js server-side rendering as it utilizes Web APIs (ResizeObserver).

To avoid importing MyPie (and subsequently ResponsivePie) on the server, you can dynamically import it on the client-side only using next/dynamic with ssr: false.

import dynamic from "next/dynamic";
import { data } from "../components/Pie";
import homeStyles from "../styles/Home.module.css";

const MyPie = dynamic(() => import("../components/Pie"), {
    ssr: false
})

function Chart() {
    return (
        <div className={homeStyles.divchart}>
            <MyPie data={data}/>
        </div>
    );
};

export default Chart;


问:
Hover effect causing footer to adjust with size
I have managed to apply the social media icons, Facebook, Linkedin and Gihub with a hover glow effect, which is what I want.

The issue I am having when you hover over the images it sizes up, but the sizing up also extends the bottom of the footer which is not what I want.

The end result should be that when I hover over the images the image size increases with the glow effect, but does not affect the bottom of the footer from expanding with the size as well.

Please see the code for the footer only as that is what I am focusing on fixing:

HTML

```<code>  <footer class="footer">
        <h2 id="contact">Social Media</h2>
        <div id="social-icons">
            <ul>
                <a href="https://www.linkedin.com/in/sheldon-aldridge-bb05a1b0/" target="_blank">

                    <img src="images/linkedin.png" alt="Sheldon Aldridge linkedin">
                </a>
                <a  href="https://www.facebook.com/sheldon.aldridge.5/" target="_blank">

                    <img src="images/Facebook.svg" alt="Sheldon Aldridge linkedin">
                </a>
                <a href="https://github.com/SheldonAldridge" target="_blank">

                    <img class="icons" src="images/github.svg" alt="Sheldon Aldridge Github icon">
                </a>
            </ul>
        </div>
    </footer>
</code>```

CSS

```<code>footer {
  box-shadow: 0px -10px 20px 0px black;
  background-image: linear-gradient(to right, #457B9D, #1D3557);
  text-align: center;
  margin-top: 16px;
  padding-bottom: 5rem;
}

.footer img {
  margin-right: 38px;
}

.footer h2 {
  background-color: #1D3557;
  margin: -11px;
  padding: 39px;
  margin-top: 0px;
  margin-right: 19px;
  color: white;
}

.footer img {
  width: 50px;
  border-radius: 100%;
}

#social-icons
{
 display: inline-flex;
 flex-direction: column;
}

#social-icons img
{
 width:3rem;
}

#social-icons img:hover {
  width: 60px;
  box-shadow: 0 0 20px 5px #4d97ff;
  border-radius: 100%;
}
</code>```

If you need the rest of the code, I will edit the post and update it.

答:
Because you increase the width of image on hover, this creates an increase on height, and as a result this extends the bottom.

I would suggest to use transform: scale(..) instead of width.

For example,

#social-icons img:hover {
  transform: scale(1.3);
  box-shadow: 0 0 20px 5px #4d97ff;
  border-radius: 100%;
}
```

Fiddle: https://jsfiddle.net/kongallis/ykbsjpwd/18/

Body:
I have managed to apply the social media icons, Facebook, Linkedin and Gihub with a hover glow effect, which is what I want.

The issue I am having when you hover over the images it sizes up, but the sizing up also extends the bottom of the footer which is not what I want.

The end result should be that when I hover over the images the image size increases with the glow effect, but does not affect the bottom of the footer from expanding with the size as well.

Please see the code for the footer only as that is what I am focusing on fixing:

HTML

Social Media

CSS

footer {
  box-shadow: 0px -10px 20px 0px black;
  background-image: linear-gradient(to right, #457B9D, #1D3557);
  text-align: center;
  margin-top: 16px;
  padding-bottom: 5rem;
}

.footer img {
  margin-right: 38px;
}

.footer h2 {
  background-color: #1D3557;
  margin: -11px;
  padding: 39px;
  margin-top: 0px;
  margin-right: 19px;
  color: white;
}

.footer img {
  width: 50px;
  border-radius: 100%;
}

#social-icons
{
 display: inline-flex;
 flex-direction: column;
}

#social-icons img
{
 width:3rem;
}

#social-icons img:hover {
  width: 60px;
  box-shadow: 0 0 20px 5px #4d97ff;
  border-radius: 100%;
}

If you need the rest of the code, I will edit the post and update it.

Body:
Because you increase the width of image on hover, this creates an increase on height, and as a result this extends the bottom.

I would suggest to use transform: scale(..) instead of width.

For example,

#social-icons img:hover {
  transform: scale(1.3);
  box-shadow: 0 0 20px 5px #4d97ff;
  border-radius: 100%;
}

Fiddle: https://jsfiddle.net/kongallis/ykbsjpwd/18/


问:
Is there a UnivMap equivilant in Rust?
In OCaml, there is a construct called univ_map.t. The idea is you can create unique ids, that are genericed over a type 'a. Then, the univ_map allows you to map from those keys to values also of type 'as. Here is an example.

The thing that makes these univ_maps special is that they allow you to store values with many different types in the same dictionary, where you retain type safety because the key of the dictionary tells you what type you're getting out.

Is there a construct that would allow me to do something similar in Rust? I know in OCaml they are implemented with open variants, which I don't believe Rust has.

答:
I'm not familiar with OCaml, but looking at the docs:

Univ_map: Universal/heterogeneous maps [...] useful for storing values of arbitrary type in a single map [...] built on top of Univ.

Univ: An extensible universal variant type. Every type id corresponds to one branch of the variant type.

The closest thing that Rust has that sounds like Univ is the Any trait, which is designed to represent any type (with exceptions). However, there is no standard type for storing a collection of Anys that is accessed by its TypeId. From looking how popular crates handle this, its usually a bespoke wrapper around HashMap<TypeId, Box<dyn Any>> or similar. I hope I've understood correctly.

Title: Is there a UnivMap equivilant in Rust?