问:
String formatting to remove \n in Python test
I've a json object in my python program that looks like this, the whole key is in a single line string with \n identifying new lines:

```<code>{
  "key": {
    "id":"2605c6c7-59e3-45cb-8483-a7a34ce6e008",
    "value":"-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAymUpP05OvlSykZBv9WDyexlREK7tzmAg56ivNmUJwT8ID0ig\na/Kiq9U5hDurfkQlD1gIJ7y8GA6IQnRxbha/LKm9TK878VIzAOtpdlVGeEa6SD5X\nG2DPH8V+Q6cbhliN4NqvuiJqCDVR5W1CCQBNNotpbZirm9kX8NAlwOdtpoFGziX4\nTgiNPcGbwaDDCpLiu4xfU6Uywv1e/EOvhZLqJpxuoKM7rdMaSM4/GIEBBQFlWPw+\nNJtbnyqdPtw73xy8WFlSamzYrMazyrtlDiMPoWc0Un+dttwWix0awwtuLc4MAxBx\n4wcxJLWctUCCNi+uf0qchhUwIsrSUA/9vC/6PQIDAQABAoIBABhzIgl4v0B04OF+\nzleZL5G5XDakuyucJz10/j2W9Re4MpQOFPsVY5tYdctIng3x03xICSwru5k4YDOO\n94jyDIQruSeDX71mTa0Fw0a9RHcRLD2/8ivnhP30kK1BiaywE+ue322f7KkzL8KE\ncV6+/5TgQIsxz0FTd3Xq3zSvgGqFqnK+oWFl/vdM2KQW6qdpDcVr26gVwDyCbzNg\nkeFhs783Ek5nkscutx9BZyYwtRqcqwf/1h9VFVbIFa2dcQSvkE8hiIEkMh3tPTpM\nTVs96OBSla9zEq5VcGIRCXYIgaD4AoR2RdsDC2ogFTeWWvwV4b8jBo7/KFKyfb+J\n15m03CECgYEA6KHaZHhk7d4lyqsgHpmhJN/qR2vR9VflmUZf/5zfiSmz1s40g21T\nl4g8sZxushSG9zDuZlG/BLgIgi9oaZ81FbhdWSU+zC9HPmepk6CU/MyzRqc8xEzz\niNDlj2dzO9hh+Q/MwAJv5TbPnE8V2vGWrLu30EDoEEH1UqVFrOfcjQkCgYEA3rnC\nqj35PDDj1Gun+Hh0oTnGFItlrUppjuAox5zKXX+VBXTK94pWHIpsB8pkhykSnNPK\nxoyEsEhR6j5VwtqUObqZ+gZDxRbrEOc9at/idyDF+Kl1SdS9r5lA55OJNDGbK80M\n+RIh1yDHRZNJ1rCaPbadQIxCQveKHDwN9QLfxJUCgYAxPZEskw9KCiuVqoMx9vLV\nC1BbrcbTV7eRqgPH5zypm9olLaCP8SQwfvXZ4nLL3uxyhjjwD32PUiT66W4AbWKf\nJlcb93ZDYf6Chw6t4N+oYuvPmLaUFnW2EAGHSS5rDHIwddexDNMCgYeQXm0R2vE5\nvsI5ooN8bXmv9Ku63ZkhgQKBgHONKnqKdpEMyFa/l8CoNdIjmCm2fITgU02F7IJL\nTQ4fD+BpzJeK1Mwv4IZWMbuRyo9ErjI+WuTeUGlX98SFBFvC/PmjYGuTTVdSsSGO\nj/7AKRWuTSSF0/eTagH7IDbM+bVKx8085AOphNkK5kcVDqCv6nu/iO0XYjbtzUvt\nNszVAoGALOD/MPI4G+THe5xn6DSYaRyt7LMafbxSsJCGgNkACfJy1Q37RZJv7c6K\nskk8kaUfwWKQG7Qey4uedqfllf02DiSY7Y4BuGJraRZ5O4V53EyzpNkEk/6D8F2h\nrWhfLZz9Uuu7E5zRv11MRbqVARwv4c1qQPAxJGwpAXLmQPpqwy4=\n-----END RSA PRIVATE KEY-----\n"
   }
}
</code>```

If I was to create it without the\n(see below) character I would get a formatting error.

```<code>{
  "key": {
    "id":"2605c6c7-59e3-45cb-8483-a7a34ce6e008",
    "value":"-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAymUpP05OvlSykZBv9WDyexlREK7tzmAg56ivNmUJwT8ID0ig
a/Kiq9U5hDurfkQlD1gIJ7y8GA6IQnRxbha/LKm9TK878VIzAOtpdlVGeEa6SD5X
G2DPH8V+Q6cbhliN4NqvuiJqCDVR5W1CCQBNNotpbZirm9kX8NAlwOdtpoFGziX4
TgiNPcGbwaDDCpLiu4xfU6Uywv1e/EOvhZLqJpxuoKM7rdMaSM4/GIEBBQFlWPw+
NJtbnyqdPtw73xy8WFlSamzYrMazyrtlDiMPoWc0Un+dttwWix0awwtuLc4MAxBx
4wcxJLWctUCCNi+uf0qchhUwIsrSUA/9vC/6PQIDAQABAoIBABhzIgl4v0B04OF+
zleZL5G5XDakuyucJz10/j2W9Re4MpQOFPsVY5tYdctIng3x03xICSwru5k4YDOO
94jyDIQruSeDX71mTa0Fw0a9RHcRLD2/8ivnhP30kK1BiaywE+ue322f7KkzL8KE
cV6+/5TgQIsxz0FTd3Xq3zSvgGqFqnK+oWFl/vdM2KQW6qdpDcVr26gVwDyCbzNg
keFhs783Ek5nkscutx9BZyYwtRqcqwf/1h9VFVbIFa2dcQSvkE8hiIEkMh3tPTpM
TVs96OBSla9zEq5VcGIRCXYIgaD4AoR2RdsDC2ogFTeWWvwV4b8jBo7/KFKyfb+J
15m03CECgYEA6KHaZHhk7d4lyqsgHpmhJN/qR2vR9VflmUZf/5zfiSmz1s40g21T
l4g8sZxushSG9zDuZlG/BLgIgi9oaZ81FbhdWSU+zC9HPmepk6CU/MyzRqc8xEzz
iNDlj2dzO9hh+Q/MwAJv5TbPnE8V2vGWrLu30EDoEEH1UqVFrOfcjQkCgYEA3rnC
qj35PDDj1Gun+Hh0oTnGFItlrUppjuAox5zKXX+VBXTK94pWHIpsB8pkhykSnNPK
xoyEsEhR6j5VwtqUObqZ+gZDxRbrEOc9at/idyDF+Kl1SdS9r5lA55OJNDGbK80M
+RIh1yDHRZNJ1rCaPbadQIxCQveKHDwN9QLfxJUCgYAxPZEskw9KCiuVqoMx9vLV
C1BbrcbTV7eRqgPH5zypm9olLaCP8SQwfvXZ4nLL3uxyhjjwD32PUiT66W4AbWKf
Jlcb93ZDYf6Chw6t4N+oYuvPmLaUFnW2EAGHSS5rDHIwddexDNMCgYeQXm0R2vE5
vsI5ooN8bXmv9Ku63ZkhgQKBgHONKnqKdpEMyFa/l8CoNdIjmCm2fITgU02F7IJL
TQ4fD+BpzJeK1Mwv4IZWMbuRyo9ErjI+WuTeUGlX98SFBFvC/PmjYGuTTVdSsSGO
j/7AKRWuTSSF0/eTagH7IDbM+bVKx8085AOphNkK5kcVDqCv6nu/iO0XYjbtzUvt
NszVAoGALOD/MPI4G+THe5xn6DSYaRyt7LMafbxSsJCGgNkACfJy1Q37RZJv7c6K
skk8kaUfwWKQG7Qey4uedqfllf02DiSY7Y4BuGJraRZ5O4V53EyzpNkEk/6D8F2h
rWhfLZz9Uuu7E5zRv11MRbqVARwv4c1qQPAxJGwpAXLmQPpqwy4=
-----END RSA PRIVATE KEY-----"
   }
}
</code>```

I'm trying to write a test for this. I'll read the key from a file and it will already be in the format containing \n. How can I be sure it's been reformatted? If I print the top value to console it appears as the bottom.

答:
Use triple quotes (""") instead, it will resolve the problem. You see only Python take new line with triple quotes.

{
  "key": {
    "id":"2605c6c7-59e3-45cb-8483-a7a34ce6e008",
    "value":"""-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAymUpP05OvlSykZBv9WDyexlREK7tzmAg56ivNmUJwT8ID0ig
a/Kiq9U5hDurfkQlD1gIJ7y8GA6IQnRxbha/LKm9TK878VIzAOtpdlVGeEa6SD5X
G2DPH8V+Q6cbhliN4NqvuiJqCDVR5W1CCQBNNotpbZirm9kX8NAlwOdtpoFGziX4
TgiNPcGbwaDDCpLiu4xfU6Uywv1e/EOvhZLqJpxuoKM7rdMaSM4/GIEBBQFlWPw+
NJtbnyqdPtw73xy8WFlSamzYrMazyrtlDiMPoWc0Un+dttwWix0awwtuLc4MAxBx
4wcxJLWctUCCNi+uf0qchhUwIsrSUA/9vC/6PQIDAQABAoIBABhzIgl4v0B04OF+
zleZL5G5XDakuyucJz10/j2W9Re4MpQOFPsVY5tYdctIng3x03xICSwru5k4YDOO
94jyDIQruSeDX71mTa0Fw0a9RHcRLD2/8ivnhP30kK1BiaywE+ue322f7KkzL8KE
cV6+/5TgQIsxz0FTd3Xq3zSvgGqFqnK+oWFl/vdM2KQW6qdpDcVr26gVwDyCbzNg
keFhs783Ek5nkscutx9BZyYwtRqcqwf/1h9VFVbIFa2dcQSvkE8hiIEkMh3tPTpM
TVs96OBSla9zEq5VcGIRCXYIgaD4AoR2RdsDC2ogFTeWWvwV4b8jBo7/KFKyfb+J
15m03CECgYEA6KHaZHhk7d4lyqsgHpmhJN/qR2vR9VflmUZf/5zfiSmz1s40g21T
l4g8sZxushSG9zDuZlG/BLgIgi9oaZ81FbhdWSU+zC9HPmepk6CU/MyzRqc8xEzz
iNDlj2dzO9hh+Q/MwAJv5TbPnE8V2vGWrLu30EDoEEH1UqVFrOfcjQkCgYEA3rnC
qj35PDDj1Gun+Hh0oTnGFItlrUppjuAox5zKXX+VBXTK94pWHIpsB8pkhykSnNPK
xoyEsEhR6j5VwtqUObqZ+gZDxRbrEOc9at/idyDF+Kl1SdS9r5lA55OJNDGbK80M
+RIh1yDHRZNJ1rCaPbadQIxCQveKHDwN9QLfxJUCgYAxPZEskw9KCiuVqoMx9vLV
C1BbrcbTV7eRqgPH5zypm9olLaCP8SQwfvXZ4nLL3uxyhjjwD32PUiT66W4AbWKf
Jlcb93ZDYf6Chw6t4N+oYuvPmLaUFnW2EAGHSS5rDHIwddexDNMCgYeQXm0R2vE5
vsI5ooN8bXmv9Ku63ZkhgQKBgHONKnqKdpEMyFa/l8CoNdIjmCm2fITgU02F7IJL
TQ4fD+BpzJeK1Mwv4IZWMbuRyo9ErjI+WuTeUGlX98SFBFvC/PmjYGuTTVdSsSGO
j/7AKRWuTSSF0/eTagH7IDbM+bVKx8085AOphNkK5kcVDqCv6nu/iO0XYjbtzUvt
NszVAoGALOD/MPI4G+THe5xn6DSYaRyt7LMafbxSsJCGgNkACfJy1Q37RZJv7c6K
skk8kaUfwWKQG7Qey4uedqfllf02DiSY7Y4BuGJraRZ5O4V53EyzpNkEk/6D8F2h
rWhfLZz9Uuu7E5zRv11MRbqVARwv4c1qQPAxJGwpAXLmQPpqwy4=
-----END RSA PRIVATE KEY-----"""
   }
}
```

Body:
I've a json object in my python program that looks like this, the whole key is in a single line string with \n identifying new lines:

{
  "key": {
    "id":"2605c6c7-59e3-45cb-8483-a7a34ce6e008",
    "value":"-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAymUpP05OvlSykZBv9WDyexlREK7tzmAg56ivNmUJwT8ID0ig\na/Kiq9U5hDurfkQlD1gIJ7y8GA6IQnRxbha/LKm9TK878VIzAOtpdlVGeEa6SD5X\nG2DPH8V+Q6cbhliN4NqvuiJqCDVR5W1CCQBNNotpbZirm9kX8NAlwOdtpoFGziX4\nTgiNPcGbwaDDCpLiu4xfU6Uywv1e/EOvhZLqJpxuoKM7rdMaSM4/GIEBBQFlWPw+\nNJtbnyqdPtw73xy8WFlSamzYrMazyrtlDiMPoWc0Un+dttwWix0awwtuLc4MAxBx\n4wcxJLWctUCCNi+uf0qchhUwIsrSUA/9vC/6PQIDAQABAoIBABhzIgl4v0B04OF+\nzleZL5G5XDakuyucJz10/j2W9Re4MpQOFPsVY5tYdctIng3x03xICSwru5k4YDOO\n94jyDIQruSeDX71mTa0Fw0a9RHcRLD2/8ivnhP30kK1BiaywE+ue322f7KkzL8KE\ncV6+/5TgQIsxz0FTd3Xq3zSvgGqFqnK+oWFl/vdM2KQW6qdpDcVr26gVwDyCbzNg\nkeFhs783Ek5nkscutx9BZyYwtRqcqwf/1h9VFVbIFa2dcQSvkE8hiIEkMh3tPTpM\nTVs96OBSla9zEq5VcGIRCXYIgaD4AoR2RdsDC2ogFTeWWvwV4b8jBo7/KFKyfb+J\n15m03CECgYEA6KHaZHhk7d4lyqsgHpmhJN/qR2vR9VflmUZf/5zfiSmz1s40g21T\nl4g8sZxushSG9zDuZlG/BLgIgi9oaZ81FbhdWSU+zC9HPmepk6CU/MyzRqc8xEzz\niNDlj2dzO9hh+Q/MwAJv5TbPnE8V2vGWrLu30EDoEEH1UqVFrOfcjQkCgYEA3rnC\nqj35PDDj1Gun+Hh0oTnGFItlrUppjuAox5zKXX+VBXTK94pWHIpsB8pkhykSnNPK\nxoyEsEhR6j5VwtqUObqZ+gZDxRbrEOc9at/idyDF+Kl1SdS9r5lA55OJNDGbK80M\n+RIh1yDHRZNJ1rCaPbadQIxCQveKHDwN9QLfxJUCgYAxPZEskw9KCiuVqoMx9vLV\nC1BbrcbTV7eRqgPH5zypm9olLaCP8SQwfvXZ4nLL3uxyhjjwD32PUiT66W4AbWKf\nJlcb93ZDYf6Chw6t4N+oYuvPmLaUFnW2EAGHSS5rDHIwddexDNMCgYeQXm0R2vE5\nvsI5ooN8bXmv9Ku63ZkhgQKBgHONKnqKdpEMyFa/l8CoNdIjmCm2fITgU02F7IJL\nTQ4fD+BpzJeK1Mwv4IZWMbuRyo9ErjI+WuTeUGlX98SFBFvC/PmjYGuTTVdSsSGO\nj/7AKRWuTSSF0/eTagH7IDbM+bVKx8085AOphNkK5kcVDqCv6nu/iO0XYjbtzUvt\nNszVAoGALOD/MPI4G+THe5xn6DSYaRyt7LMafbxSsJCGgNkACfJy1Q37RZJv7c6K\nskk8kaUfwWKQG7Qey4uedqfllf02DiSY7Y4BuGJraRZ5O4V53EyzpNkEk/6D8F2h\nrWhfLZz9Uuu7E5zRv11MRbqVARwv4c1qQPAxJGwpAXLmQPpqwy4=\n-----END RSA PRIVATE KEY-----\n"
   }
}

If I was to create it without the\n(see below) character I would get a formatting error.

{
  "key": {
    "id":"2605c6c7-59e3-45cb-8483-a7a34ce6e008",
    "value":"-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAymUpP05OvlSykZBv9WDyexlREK7tzmAg56ivNmUJwT8ID0ig
a/Kiq9U5hDurfkQlD1gIJ7y8GA6IQnRxbha/LKm9TK878VIzAOtpdlVGeEa6SD5X
G2DPH8V+Q6cbhliN4NqvuiJqCDVR5W1CCQBNNotpbZirm9kX8NAlwOdtpoFGziX4
TgiNPcGbwaDDCpLiu4xfU6Uywv1e/EOvhZLqJpxuoKM7rdMaSM4/GIEBBQFlWPw+
NJtbnyqdPtw73xy8WFlSamzYrMazyrtlDiMPoWc0Un+dttwWix0awwtuLc4MAxBx
4wcxJLWctUCCNi+uf0qchhUwIsrSUA/9vC/6PQIDAQABAoIBABhzIgl4v0B04OF+
zleZL5G5XDakuyucJz10/j2W9Re4MpQOFPsVY5tYdctIng3x03xICSwru5k4YDOO
94jyDIQruSeDX71mTa0Fw0a9RHcRLD2/8ivnhP30kK1BiaywE+ue322f7KkzL8KE
cV6+/5TgQIsxz0FTd3Xq3zSvgGqFqnK+oWFl/vdM2KQW6qdpDcVr26gVwDyCbzNg
keFhs783Ek5nkscutx9BZyYwtRqcqwf/1h9VFVbIFa2dcQSvkE8hiIEkMh3tPTpM
TVs96OBSla9zEq5VcGIRCXYIgaD4AoR2RdsDC2ogFTeWWvwV4b8jBo7/KFKyfb+J
15m03CECgYEA6KHaZHhk7d4lyqsgHpmhJN/qR2vR9VflmUZf/5zfiSmz1s40g21T
l4g8sZxushSG9zDuZlG/BLgIgi9oaZ81FbhdWSU+zC9HPmepk6CU/MyzRqc8xEzz
iNDlj2dzO9hh+Q/MwAJv5TbPnE8V2vGWrLu30EDoEEH1UqVFrOfcjQkCgYEA3rnC
qj35PDDj1Gun+Hh0oTnGFItlrUppjuAox5zKXX+VBXTK94pWHIpsB8pkhykSnNPK
xoyEsEhR6j5VwtqUObqZ+gZDxRbrEOc9at/idyDF+Kl1SdS9r5lA55OJNDGbK80M
+RIh1yDHRZNJ1rCaPbadQIxCQveKHDwN9QLfxJUCgYAxPZEskw9KCiuVqoMx9vLV
C1BbrcbTV7eRqgPH5zypm9olLaCP8SQwfvXZ4nLL3uxyhjjwD32PUiT66W4AbWKf
Jlcb93ZDYf6Chw6t4N+oYuvPmLaUFnW2EAGHSS5rDHIwddexDNMCgYeQXm0R2vE5
vsI5ooN8bXmv9Ku63ZkhgQKBgHONKnqKdpEMyFa/l8CoNdIjmCm2fITgU02F7IJL
TQ4fD+BpzJeK1Mwv4IZWMbuRyo9ErjI+WuTeUGlX98SFBFvC/PmjYGuTTVdSsSGO
j/7AKRWuTSSF0/eTagH7IDbM+bVKx8085AOphNkK5kcVDqCv6nu/iO0XYjbtzUvt
NszVAoGALOD/MPI4G+THe5xn6DSYaRyt7LMafbxSsJCGgNkACfJy1Q37RZJv7c6K
skk8kaUfwWKQG7Qey4uedqfllf02DiSY7Y4BuGJraRZ5O4V53EyzpNkEk/6D8F2h
rWhfLZz9Uuu7E5zRv11MRbqVARwv4c1qQPAxJGwpAXLmQPpqwy4=
-----END RSA PRIVATE KEY-----"
   }
}

I'm trying to write a test for this. I'll read the key from a file and it will already be in the format containing \n. How can I be sure it's been reformatted? If I print the top value to console it appears as the bottom.


来源: stackexchange

问:
Dark theme / with hooks
Hello I have a custom hook to define my theme

code:

```<code>export default function App() {
  const [theme, setTheme] = usePersistedState('light');
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? 'dark' : 'light');
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <button onClick={toggleTheme}>a</button>
      </div>
    </ThemeProvider>
  );
</code>```

and here is my hook:

```<code>import { darkTheme, lightTheme } from '../themes/index';

function usePersistedState(key) {
  const [state, setState] = useState(() => {
    switch (key) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  });
  console.log(state);
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(state.type));
  }, [key, state]);

  return [state, setState];
}

export default usePersistedState;
</code>```

basically every time my state changes I save it to local storage, but for some reason it only works the first time

when I try to change my theme the second time I do not enter my switch

edit:

as i show in the gif the first time i get an object because i enter my switch, but when i try to change the theme i get only a text cuz i dont enter my switch

答:
The argument you provide to useState will apply only on the first render.

On the next renders, what you provide to setState function will be applied (you provide 'light' or 'dark', so state value will be 'light' or 'dark')

For your use case, in which you want the switch case to run every state change, useReducer is a better option than useState (in my opinion).

```<code>import { useReducer } from 'react';
import { darkTheme, lightTheme } from '../themes/index';

function usePersistedState(key) {
  const [state, dispatch] = useReducer(reducer, null, getTheme(key)); // first argument is the reducer function. second argument is the initial state. third argument is an init function (for complex initialization)

  const reducer = (state, action) => { // this will run on every state change (on every dispatch call)
    return getTheme(action.type)();
  }

  const getTheme = (themeType) => () => {
    switch (themeType) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  }

  console.log(state);
  useEffect(() => {
    localStorage.setItem('themeType', JSON.stringify(state));
  }, [state]);

  return [state, dispatch];
}

export default usePersistedState;
</code>```

And from your component you call dispatch like so:

```<code>export default function App() {
  const [theme, setTheme] = usePersistedState('light');
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? {type: 'dark'} : {type: 'light'});
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <button onClick={toggleTheme}>a</button>
      </div>
    </ThemeProvider>
  );
</code>```

ContentLicense: CC BY-SA 4.0

Title: Dark theme / with hooks

Body:
Hello I have a custom hook to define my theme

code:

export default function App() {
  const [theme, setTheme] = usePersistedState('light');
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? 'dark' : 'light');
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />

        <button onClick={toggleTheme}>a</button>

    </ThemeProvider>
  );

and here is my hook:

import { darkTheme, lightTheme } from '../themes/index';

function usePersistedState(key) {
  const [state, setState] = useState(() => {
    switch (key) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  });
  console.log(state);
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(state.type));
  }, [key, state]);

  return [state, setState];
}

export default usePersistedState;

basically every time my state changes I save it to local storage, but for some reason it only works the first time

when I try to change my theme the second time I do not enter my switch

edit:

as i show in the gif the first time i get an object because i enter my switch, but when i try to change the theme i get only a text cuz i dont enter my switch

Body:
The argument you provide to useState will apply only on the first render.

On the next renders, what you provide to setState function will be applied (you provide 'light' or 'dark', so state value will be 'light' or 'dark')

For your use case, in which you want the switch case to run every state change, useReducer is a better option than useState (in my opinion).

import { useReducer } from 'react';
import { darkTheme, lightTheme } from '../themes/index';

function usePersistedState(key) {
  const [state, dispatch] = useReducer(reducer, null, getTheme(key)); // first argument is the reducer function. second argument is the initial state. third argument is an init function (for complex initialization)

  const reducer = (state, action) => { // this will run on every state change (on every dispatch call)
    return getTheme(action.type)();
  }

  const getTheme = (themeType) => () => {
    switch (themeType) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  }

  console.log(state);
  useEffect(() => {
    localStorage.setItem('themeType', JSON.stringify(state));
  }, [state]);

  return [state, dispatch];
}

export default usePersistedState;

And from your component you call dispatch like so:

export default function App() {
  const [theme, setTheme] = usePersistedState('light');
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? {type: 'dark'} : {type: 'light'});
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <button onClick={toggleTheme}>a</button>
      </div>
    </ThemeProvider>
  );


问:
How to make mongoose's model.findByIdAndUpdate() trigger model.save()?
I have a mongoose model for users in my database. I have an update controller which calls the findByIdAndUpdate method on my model. Now, when I store passwords in my database I'd like to hash them first, so I have:

```<code>userSchema.pre("save", async function(next) {
  // if password is modified then hash it
  next();
});
</code>```

Now when my update controller calls findByIdAndUpdate it seems to me that model.save() does not get called, so the hashing never happens.

Is there a way to overload the original behavior of findByAndUpdate, or what is a neat solution to this problem?

答:
findByIdAndUpdate triggers the findOneAndUpdate() middleware.  Pre and post save() hooks are not executed on findOneAndUpdate().

You cannot access the document being updated in pre('findOneAndUpdate') middleware.
If you need to access the document that will be updated, you need to execute an explicit query for the document.

Sample schema with findOneAndUpdate middleware:

const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const schema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  }
});

schema.pre("save", async function(next) {
  if (!this.isModified("password")) return next();
  this.password = await bcrypt.hash(this.password, 12);
  next();
});

schema.pre("findOneAndUpdate", async function() {
  const docToUpdate = await this.model.findOne(this.getQuery());

  // add your hashing logic to here
  let newPassword = await bcrypt.hash(docToUpdate.password, 12);

  this.set({ password: newPassword });
});

module.exports = mongoose.model("User", schema);
```

<p>Sample route to test:</p>

<pre class="lang-js prettyprint-override"><code>router.put("/users/:id", async (req, res) => {
  let result = await User.findByIdAndUpdate(req.params.id, {}, { new: true });

  res.send(result);
});
</code>```

Note that I used {} inside findByIdAndUpdate, because our password will be hashed in findOneAndUpdate middleware.

Body:
I have a mongoose model for users in my database. I have an update controller which calls the findByIdAndUpdate method on my model. Now, when I store passwords in my database I'd like to hash them first, so I have:

userSchema.pre("save", async function(next) {
  // if password is modified then hash it
  next();
});

Now when my update controller calls findByIdAndUpdate it seems to me that model.save() does not get called, so the hashing never happens.

Is there a way to overload the original behavior of findByAndUpdate, or what is a neat solution to this problem?

Body:
findByIdAndUpdate triggers the findOneAndUpdate() middleware.  Pre and post save() hooks are not executed on findOneAndUpdate().

You cannot access the document being updated in pre('findOneAndUpdate') middleware.
If you need to access the document that will be updated, you need to execute an explicit query for the document.

Sample schema with findOneAndUpdate middleware:

const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const schema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  }
});

schema.pre("save", async function(next) {
  if (!this.isModified("password")) return next();
  this.password = await bcrypt.hash(this.password, 12);
  next();
});

schema.pre("findOneAndUpdate", async function() {
  const docToUpdate = await this.model.findOne(this.getQuery());

  // add your hashing logic to here
  let newPassword = await bcrypt.hash(docToUpdate.password, 12);

  this.set({ password: newPassword });
});

module.exports = mongoose.model("User", schema);

Sample route to test:

router.put("/users/:id", async (req, res) => {
  let result = await User.findByIdAndUpdate(req.params.id, {}, { new: true });

  res.send(result);
});

Note that I used {} inside findByIdAndUpdate, because our password will be hashed in findOneAndUpdate middleware.


问:
How would you design a good search UI?
I want to provide my users with an 'advanced' search engine.
I basically have a lot of search criteria to chose from :

some are very simple/common and will be largely use (ie time period, item id)

some are a bit less mainstream

and some won't be used a lot, but I still want to provide them

Overall, I have around 30+ criteria to chose from

The result is a dataset which I display in a grid.

I've search for inspiration on internet, and even google doesn't seem to have a nice solution for advanced search.

I've designed this kind of tools in the past, and I wasn't really pleased by the result, although the user were eventually able to use it quite effectively.

Do you think the search panel should be visible all the time (ie displayed on top of my result grid) or available in a separate form (which would let me use more place for all the controls)

Do you think it's better to display all the search criteria, or to let the user click on 'advanced' if he wants to see/use more criteria

How would you organize the criteria? by usage frequency, or rather by area (ie. criteria related to user, to location, to time, etc.)

Where should I put the 'Search' button? next to the more common search controls, or at the bottom, or both?

And more generally, do you have tips you want to share on how to design a nice search UI ?
What kind of functionalities do you usually miss in this kind of 'advanced' search engines?

答:
Please find my answers(in normal text) against each of the questions(in italics) asked.

"1) Do you think the search panel should be visible all the time (ie displayed on top of my result grid) or available in a separate form (which would let me use more place for all the controls)"

Display on top of result grid as this leaves extra horizontal space to display search results and thereby to display more columns of search data without scrolling horizontally.

"2) Do you think it's better to display all the search criteria, or to let the user click on 'advanced' if he wants to see/use more criteria"

Display all available criteria but in a tabbed fashion. i.e. categorize input search fields into categories and have a tab for each category.

"3) How would you organize the criteria? by usage frequency, or rather by area (ie. criteria related to user, to location, to time, etc.)"

Organize 'by area' because different people like using different criteria.
Each criteria would have tab of it's own. But organize the tabs in the order of 'more popular' to 'less popular' as you think. In your case tabs may be 'By Name'(containing fields first name, middle name, last name, mother maiden name, nick name, father's name etc), 'By Location' (place name, county name, district name, state name, country name etc)
and so on until the advanced tab(where you'd put least used fields).

"4) Where should I put the 'Search' button? next to the more common search controls, or at the bottom, or both?"

Put the input fields of search as discussed above in a tabbed fashion categorizing them based on 'type of field'(I'll refer to this area as search grid). Then put action buttons such as 'Search', 'Clear/Reset' just below the search grid aligning to the center(I'll refer to this area as button grid).Then put the search result pane below the button grid as more horizontal area is available for display so that maximum columns can be displayed at once.

OwnerDisplayName: Brann

ContentLicense: CC BY-SA 2.5

Title: How would you design a good search UI?

LastEditorDisplayName: onnodb

OwnerDisplayName: Liv 1 - 0 Madrid

LastEditorDisplayName: Liv 1 - 0 Madrid


问:
Wordpress: Always expanded menus in dashboard / Remove minimize menu icons
Trying to modify the menu in the dashboard a bit.

I'm trying to remove the toggle option everywhere it's present, and find someway to force the menus to always be expanded, is this possible? (toggle button: http://dl.dropbox.com/u/3618143/toggle.png)

Also want to remove the minimize option (which lets you only show icons in the menu bar). I've been able to remove the actual icon, but the functionality is still there (invisible link). So removing the actual image is not the problem, I've managed to remove that, the functionality however is still there.
(http://dl.dropbox.com/u/3618143/minimize.png)

Thanks in advance

答:
Have the same need: remove the "un/fold" functionality from the WP admin menu bar, to remove clutter, but without tinkering with the source file.

I found out in wp-admin/menu.php that the separators are stored in index 4,59,99.

Here is the function to add to your functions.php

```<code>    function pxln_remove_menu_items() {

            global $menu;

//an array with menus to remove (use their title)
            $restricted = array(__('Posts'),__('Links'), __('Comments'), __('Media'), __('Separator'));

// keys of the unfolders
            unset($menu[4]);
            unset($menu[59]);
            unset($menu[99]);
            end ($menu);
            while (prev($menu)){
                $value = explode(' ',$menu[key($menu)][0]);
                if(in_array($value[0] != NULL?$value[0]:"" , $restricted)) {
                    unset($menu[key($menu)]);
                }
            }
    }

    add_action('admin_menu', 'pxln_remove_menu_items');
</code>```

Body:
Have the same need: remove the "un/fold" functionality from the WP admin menu bar, to remove clutter, but without tinkering with the source file.

I found out in wp-admin/menu.php that the separators are stored in index 4,59,99.

Here is the function to add to your functions.php

    function pxln_remove_menu_items() {

            global $menu;

//an array with menus to remove (use their title)
            $restricted = array(__('Posts'),__('Links'), __('Comments'), __('Media'), __('Separator'));

// keys of the unfolders
            unset($menu[4]);
            unset($menu[59]);
            unset($menu[99]);
            end ($menu);
            while (prev($menu)){
                $value = explode(' ',$menu[key($menu)][0]);
                if(in_array($value[0] != NULL?$value[0]:"" , $restricted)) {
                    unset($menu[key($menu)]);
                }
            }
    }

    add_action('admin_menu', 'pxln_remove_menu_items');

ContentLicense: CC BY-SA 3.0


答:
Since both minutes and months start with 'm', the format is case sensitive. For minutes, lower case 'm' is reserved and for month upper case 'M' is reserved. Simply edit your format to "dd/Mm/yyyy HH:mm a"

What's happening right now is the format is stating minutes twice and probably the 2nd position is getting precedence. The month is missing in the format altogether so by default 01 is imputed.

Title: Converting String Time Stamp to DateTime in pyspark

Body:
Parsing "06/02/2019 7:30 AM" timestamp to 24Hr clock timestamp IN pyspark

This is My Dataframe's schema:

    root
     |-- Customer_Site_ID: string (nullable = true)
     |-- ReceivedDate: string (nullable = true)
     |-- BattV: double (nullable = true)

converting into 24Hr DateTime

from pyspark.sql.functions import to_timestamp
# raw_data_10_sites=raw_data_10_sites.withColumn("ReceivedDate_New", to_timestamp('ReceivedDate', "dd/mm/yyyy hh:mm a"))
raw_data_10_sites.select(to_timestamp(raw_data_10_sites.ReceivedDate, "dd/mm/yyyy HH:mm a").alias('New_RD')).show(10)

Actual Column-
The below is my ReceivedDate column.

+-------------------+
|       ReceivedDate|
+-------------------+
| 06/02/2019 7:30 AM|
| 06/02/2019 8:01 AM|
| 06/02/2019 8:30 AM|
| 06/02/2019 8:49 AM|
| 06/02/2019 8:50 AM|
| 06/02/2019 8:52 AM|
| 06/02/2019 9:30 AM|
| 06/02/2019 9:46 AM|
| 06/02/2019 9:53 AM|
|06/02/2019 10:03 AM|
|06/02/2019 10:17 AM|
|06/02/2019 10:19 AM|
|06/02/2019 10:23 AM|
|06/02/2019 10:49 AM|
|06/02/2019 10:55 AM|
|06/02/2019 10:58 AM|
|06/02/2019 11:30 AM|
|06/02/2019 11:49 AM|
|06/02/2019 12:00 PM|
|06/02/2019 12:02 PM|
+-------------------+

But I got This-

+-------------------+
|             New_RD|
+-------------------+
|2019-01-06 07:30:00|
|2019-01-06 08:01:00|
|2019-01-06 08:30:00|
|2019-01-06 08:49:00|
|2019-01-06 08:50:00|
|2019-01-06 08:52:00|
|2019-01-06 09:30:00|
|2019-01-06 09:46:00|
|2019-01-06 09:53:00|
|2019-01-06 10:03:00|
+-------------------+

THE MONTH IS COMPLETELY WRONG, CAN ANYONE HELP ?
I have tried many functions but it didn't worked for me.
I have also gone through many blogs but this issue is unique. I just don't understand how is this possible?


答:
I think you forgot to add the object wrapper on the toogle with { type: ... }</p>

```<code>const toggleTheme = () => {
    setTheme({type: theme.type === 'light' ? 'dark' : 'light'});
};
</code>```

Title: Dark theme / with hooks

Body:
I think you forgot to add the object wrapper on the toogle with { type: ... }

const toggleTheme = () => {
    setTheme({type: theme.type === 'light' ? 'dark' : 'light'});
};


问:
Login Form is not rendering
I'm having an issue when i want to render a login form view those issues started when i began to use context api for React. the error that show me right now is:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
  Check the render method of LoginForm.

the error is there:

Index.js:

```<code>    // React
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { LoginPage } from '../src/views/Login';

// 1
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

// Context Provider
import AppProvider from './context/context';
import { LoginForm } from './components/Form';

// 2
const httpLink = createHttpLink({
  uri: 'http://localhost:3000/graphql'
});

// 3
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

// 4
export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
})

ReactDOM.render(

    <ApolloProvider client={client}>
    <BrowserRouter>
      <AppProvider>
        <App />
      </AppProvider>
    </BrowserRouter>
    </ApolloProvider>,
    document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();
</code>```

when i take the line out of the script, the one with Context.Consumer at the LoginForm component the error goes away. i tried to export the component with the default then wihout it with no success.

Login Form:

```<code>        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // import mutations
    import mutations from './mutations';

    // React bootstrap
    import { Container, Row, Form, Button } from 'react-bootstrap';

    // Import Style
    import './style.css';

    // Component
    import NavbarLayout from '../Navbar';

    // Context
    import Context from '../../context/context';

    export class LoginForm extends React.Component {

        render() {

            return(

                <Fragment>
                    <Context.Consumer>
                        {c => {
                            return(
                                <Container>
                                    <Form className="form-container">
                                        <h2 className="text-center pb-4">Ingreso</h2>
                                        <Form.Group controlId="formBasicEmail">
                                            <Form.Control name='email' onChange={e => c.get_data(e)} type="email" placeholder="Email" />
                                        </Form.Group>

                                        <Form.Group controlId="formBasicPassword">
                                            <Form.Control name='password' onChange={e => c.get_data(e)} type="password" placeholder="Contraseña" />
                                        </Form.Group>
                                        <div className="text-center">
                                            <Button className="button-login" variant="primary" onClick={e => c.submit(e)} type="submit">
                                                Ingresa
                                            </Button>
                                        </div>
                                    </Form>
                                </Container>
                            );
                        }}
                    </Context.Consumer>
                </Fragment>
            );
        }
    }
</code>```

This component is called into this view:

```<code>        // React
    import React, { Fragment } from 'react';

    // Component React
    import { LoginForm } from '../../components/Form';

    // React bootstrap
    import { Container, Row } from 'react-bootstrap';

    export const LoginPage = () => {
        return(
            <Fragment>
                <Container style={{marginTop: '2rem'}}>
                    <LoginForm />
                </Container>
            </Fragment>
        );
    }
</code>```

The context Api file is:

```<code>        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // Mutation
    import mutations from './mutations';

    // Context
    const Context = React.createContext();

    class AppProvider extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                // Login & logout states
                login_credentials: {},
                isLogged: false,
                get_data: this.get_data,
                submit: this.submit,
            }
        }

        // Actions

        // Login & Logout

        get_data = async(e) => {
            e.preventDefault();
            const { name, value } = e.target;
            const data = { [name]: value };
            const newData = { ...this.state.login_credentials, ...data };
            this.setState({
                login_credentials: newData
            });

        }

        submit = async(e) => {
            e.preventDefault();
            const { signinUser } = this.props;
            const { login_credentials, isLogged } = this.state;

            try {
                let variables = login_credentials;
                const response = await signinUser({variables});
                const get_token = response.data.signinUser.token;

                // setting localStorage
                localStorage.setItem('token', get_token);
                this.setState({
                    isLogged: true
                });

                this.props.history.push({pathname: '/home', state: {isLogged: this.state.isLogged}});

            } catch(error) {
                console.log(error);
            }

        }

        // END LOGIN & LOGOUT ACTIONS

        render() {
            return(
                <Context.Provider value={this.state}>
                    {this.props.children}
                </Context.Provider>
            );
        }
    }

    export default compose(
        withRouter,
        graphql(mutations.signinUser, { name: 'signinUser' }),
    )(AppProvider)
</code>```

答:
```<code>// Component React
import { LoginForm } from '../../components/Form';
</code>```

try removing the curly braces and import directly

```<code>// Component React
import  LoginForm  from '../../components/Form';
</code>```

you should import files using curly braces when you're importing it from an index file

else try checking your path
         '../../components/Form';
check for spelling both upper and lower case also not you went back twice in your directory ../../ try once ../

Title: Login Form is not rendering

Body:
I'm having an issue when i want to render a login form view those issues started when i began to use context api for React. the error that show me right now is:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
  Check the render method of LoginForm.

the error is there:

Index.js:

    // React
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { LoginPage } from '../src/views/Login';

// 1
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

// Context Provider
import AppProvider from './context/context';
import { LoginForm } from './components/Form';

// 2
const httpLink = createHttpLink({
  uri: 'http://localhost:3000/graphql'
});

// 3
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

// 4
export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
})

ReactDOM.render(

    <ApolloProvider client={client}>
    <BrowserRouter>
      <AppProvider>
        <App />
      </AppProvider>
    </BrowserRouter>
    </ApolloProvider>,
    document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();

when i take the line out of the script, the one with Context.Consumer at the LoginForm component the error goes away. i tried to export the component with the default then wihout it with no success.

Login Form:

        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // import mutations
    import mutations from './mutations';

    // React bootstrap
    import { Container, Row, Form, Button } from 'react-bootstrap';

    // Import Style
    import './style.css';

    // Component
    import NavbarLayout from '../Navbar';

    // Context
    import Context from '../../context/context';

    export class LoginForm extends React.Component {

        render() {

            return(

                <Fragment>
                    <Context.Consumer>
                        {c => {
                            return(
                                <Container>
                                    <Form className="form-container">

Ingreso

                                        <Form.Group controlId="formBasicEmail">
                                            <Form.Control name='email' onChange={e => c.get_data(e)} type="email" placeholder="Email" />
                                        </Form.Group>

                                        <Form.Group controlId="formBasicPassword">
                                            <Form.Control name='password' onChange={e => c.get_data(e)} type="password" placeholder="Contraseña" />
                                        </Form.Group>

                                            <Button className="button-login" variant="primary" onClick={e => c.submit(e)} type="submit">
                                                Ingresa
                                            </Button>

                                    </Form>
                                </Container>
                            );
                        }}
                    </Context.Consumer>
                </Fragment>
            );
        }
    }

This component is called into this view:

        // React
    import React, { Fragment } from 'react';

    // Component React
    import { LoginForm } from '../../components/Form';

    // React bootstrap
    import { Container, Row } from 'react-bootstrap';

    export const LoginPage = () => {
        return(
            <Fragment>
                <Container style={{marginTop: '2rem'}}>
                    <LoginForm />
                </Container>
            </Fragment>
        );
    }

The context Api file is:

        // React
    import React, { Fragment } from 'react';

    // React apollo
    import { graphql } from 'react-apollo';
    import * as compose from 'lodash.flowright';

    // React router
    import { withRouter, Redirect } from 'react-router-dom';

    // Mutation
    import mutations from './mutations';

    // Context
    const Context = React.createContext();

    class AppProvider extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                // Login & logout states
                login_credentials: {},
                isLogged: false,
                get_data: this.get_data,
                submit: this.submit,
            }
        }

        // Actions

        // Login & Logout

        get_data = async(e) => {
            e.preventDefault();
            const { name, value } = e.target;
            const data = { [name]: value };
            const newData = { ...this.state.login_credentials, ...data };
            this.setState({
                login_credentials: newData
            });

        }

        submit = async(e) => {
            e.preventDefault();
            const { signinUser } = this.props;
            const { login_credentials, isLogged } = this.state;

            try {
                let variables = login_credentials;
                const response = await signinUser({variables});
                const get_token = response.data.signinUser.token;

                // setting localStorage
                localStorage.setItem('token', get_token);
                this.setState({
                    isLogged: true
                });

                this.props.history.push({pathname: '/home', state: {isLogged: this.state.isLogged}});

            } catch(error) {
                console.log(error);
            }

        }

        // END LOGIN & LOGOUT ACTIONS

        render() {
            return(
                <Context.Provider value={this.state}>
                    {this.props.children}
                </Context.Provider>
            );
        }
    }

    export default compose(
        withRouter,
        graphql(mutations.signinUser, { name: 'signinUser' }),
    )(AppProvider)

Body:
// Component React
import { LoginForm } from '../../components/Form';

try removing the curly braces and import directly

// Component React
import  LoginForm  from '../../components/Form';

you should import files using curly braces when you're importing it from an index file

else try checking your path
         '../../components/Form';
check for spelling both upper and lower case also not you went back twice in your directory ../../ try once ../


问:
Pandas resampling from daily to weekly adds an extra week? Is this normal?
I have a dataframe with daily transaction amounts. Date is index ds and transaction amount is column y

```<code>ds          y
2017-08-16  10.0
2017-10-26  21.7
2017-11-04   5.0
2017-11-13  10.0
2017-11-27  14.0
</code>```

The data only goes up to December 2019 as confirmed by:

```<code>print(df.index.max())

Timestamp('2019-12-31 00:00:00')
</code>```

I want to resample it to a weekly transaction amount:

```<code># Resample from weekly to monthly
df= df.resample('W').mean()

# Backfill any missing values
df.fillna(method='bfill', inplace=True)
</code>```

And now the data goes up to Jan 2020:

```<code>print(df.index.max())

Timestamp('2020-01-05 00:00:00')
</code>```

It's not very far into the future, just a week. So I am not really worried. But I don't understand it. Why does my data now go into 2020 after resampling to week?

答:
The default behaviour of the resample function is to take the right edge of the bucket when using weekly offsets. If you'd like to switch that, you could do:

```<code>df_def = {
    'ds': ['2017-08-16','2017-10-26', '2017-11-04','2017-11-13','2017-11-27','2019-12-31'],
    'y': [10.0,21.7,5.0,10.0,14.0,999.0]
}

import pandas as pd
df = pd.DataFrame(df_def)
df['ds'] = pd.to_datetime(df.ds)
df = df.set_index('ds')

df.resample('W', label='left').mean().fillna(method='bfill')
</code>```

Body:
I have a dataframe with daily transaction amounts. Date is index ds and transaction amount is column y

ds          y
2017-08-16  10.0
2017-10-26  21.7
2017-11-04   5.0
2017-11-13  10.0
2017-11-27  14.0

The data only goes up to December 2019 as confirmed by:

print(df.index.max())

Timestamp('2019-12-31 00:00:00')

I want to resample it to a weekly transaction amount:

# Resample from weekly to monthly
df= df.resample('W').mean()

# Backfill any missing values
df.fillna(method='bfill', inplace=True)

And now the data goes up to Jan 2020:

print(df.index.max())

Timestamp('2020-01-05 00:00:00')

It's not very far into the future, just a week. So I am not really worried. But I don't understand it. Why does my data now go into 2020 after resampling to week?

Body:
The default behaviour of the resample function is to take the right edge of the bucket when using weekly offsets. If you'd like to switch that, you could do:

df_def = {
    'ds': ['2017-08-16','2017-10-26', '2017-11-04','2017-11-13','2017-11-27','2019-12-31'],
    'y': [10.0,21.7,5.0,10.0,14.0,999.0]
}

import pandas as pd
df = pd.DataFrame(df_def)
df['ds'] = pd.to_datetime(df.ds)
df = df.set_index('ds')

df.resample('W', label='left').mean().fillna(method='bfill')


问:
CheckBox animation doesn't work when inside a ReorderableListView
I'm trying to make a simple task list, which contains text and a checkbox and allows you to reorder tasks. All the logic of reordering them is working, but when selecting a task the checkbox updates without running the animation.

I've had a problem similar to a simple list (ListView), where by placing an ObjectKey the problem was solved. In this example, as you can see, there is also a Key, but the animation does not work. Any suggestion?

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      title: 'Flutter To Do',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomePage(),
    ));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List myItems = [];

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 10; i++) {
      Map<String, dynamic> newTask = Map();
      newTask['task'] = 'Task #$i';
      newTask['done'] = false;
      myItems.add(newTask);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter To Do'),
        ),
        body: ReorderableListView(
          children: [
            for (final item in myItems)
              Card(
                key: ObjectKey(item),
                margin: EdgeInsets.all(0),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(0)
                ),
                child: Container(
                  height: 56,
                  child: Row(
                    children: <Widget>[
                      IconButton(icon: Icon(Icons.reorder), onPressed: null),
                      Expanded(
                        child: Text(item['task']),
                      ),
                      Checkbox(
                        value: item['done'],
                        onChanged: (value) {
                          setState(() {
                            item['done'] = value;
                          });
                        },
                      )
                    ],
                  ),
                ),
              )
          ],
          onReorder: (oldIndex, newIndex) {
            setState(() {
              if (newIndex > oldIndex) {
                newIndex -= 1;
              }

              final item = myItems.removeAt(oldIndex);
              myItems.insert(newIndex, item);
            });
          },
        ));
  }
}

```

答:
Because setState updated ReorderableListView, it would re-render the whole list, so it wouldn't count as a change.

you should only update one listTile in the listView.
for that move your listTile widget to a Stateful widget with its own setState and replace your Card in HomePage:

class _HomePageState extends State<HomePage> {
  List myItems = [];

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 10; i++) {
      Map<String, dynamic> newTask = Map();
      newTask['task'] = 'Task #$i';
      newTask['done'] = false;
      myItems.add(newTask);
    }
  }

  bool a = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter To Do'),
      ),
      body: ReorderableListView(
        children: [
          for (var item in myItems)
            TaskListItem(
              key: ObjectKey(item),
              item: item,
            ),
        ],
        onReorder: (oldIndex, newIndex) {
          setState(() {
            if (newIndex > oldIndex) {
              newIndex -= 1;
            }

            final item = myItems.removeAt(oldIndex);
            myItems.insert(newIndex, item);
          });
        },
      ),
    );
  }
}
```

<pre class="lang-dart prettyprint-override"><code>class TaskListItem extends StatefulWidget {
  final item;

  const TaskListItem({Key key, this.item}) : super(key: key);

  @override
  _TaskListItemState createState() => _TaskListItemState();
}

class _TaskListItemState extends State<TaskListItem> {
  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.all(0),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(0)),
      child: Container(
        height: 56,
        child: Row(
          children: <Widget>[
            IconButton(icon: Icon(Icons.reorder), onPressed: null),
            Expanded(
              child: Text(widget.item['task']),
            ),
            Checkbox(
              value: widget.item['done'],
              onChanged: (value) {
                setState(() {
                  widget.item['done'] = value;
                });
              },
            )
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
Because setState updated ReorderableListView, it would re-render the whole list, so it wouldn't count as a change.

you should only update one listTile in the listView.
for that move your listTile widget to a Stateful widget with its own setState and replace your Card in HomePage:

class _HomePageState extends State<HomePage> {
  List myItems = [];

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 10; i++) {
      Map<String, dynamic> newTask = Map();
      newTask['task'] = 'Task #$i';
      newTask['done'] = false;
      myItems.add(newTask);
    }
  }

  bool a = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter To Do'),
      ),
      body: ReorderableListView(
        children: [
          for (var item in myItems)
            TaskListItem(
              key: ObjectKey(item),
              item: item,
            ),
        ],
        onReorder: (oldIndex, newIndex) {
          setState(() {
            if (newIndex > oldIndex) {
              newIndex -= 1;
            }

            final item = myItems.removeAt(oldIndex);
            myItems.insert(newIndex, item);
          });
        },
      ),
    );
  }
}

class TaskListItem extends StatefulWidget {
  final item;

  const TaskListItem({Key key, this.item}) : super(key: key);

  @override
  _TaskListItemState createState() => _TaskListItemState();
}

class _TaskListItemState extends State<TaskListItem> {
  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.all(0),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(0)),
      child: Container(
        height: 56,
        child: Row(
          children: <Widget>[
            IconButton(icon: Icon(Icons.reorder), onPressed: null),
            Expanded(
              child: Text(widget.item['task']),
            ),
            Checkbox(
              value: widget.item['done'],
              onChanged: (value) {
                setState(() {
                  widget.item['done'] = value;
                });
              },
            )
          ],
        ),
      ),
    );
  }
}


问:
Can't allocate 2-4 Gb of RAM with new[]/ C++/Linux/ x86_64
For this easy test, and the linux box with 4Gb or RAM, 0byte of swap and CPU in x86_64 mode, I can't allocate more than 1 Gb of array.

Source:

```<code>#include <cstdio>
int main()
{
 for(int i=0;i<33;i++) {
  char*a=new char[1<<i];
  *a=1;
  delete[]a;
  printf("%d\n",i);
  fflush(stdout);
 }
}
</code>```

Run:

```<code>$ file test
test: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV)
$ ./test
...
24
25
26
27
28
29
30
terminate called after throwing an instance of 'std::bad_alloc'
  what():  St9bad_alloc
Aborted
</code>```

There is no ulimit for memory:

```<code>virtual memory          (kbytes, -v) unlimited
data seg size           (kbytes, -d) unlimited
</code>```

Why the error?

Glibc is 2.3.4, kernel is 2.6.9

UPDATE: Compiler is gcc4.1

Thanks! The test definitely has a error, 1ull<<i gives me up to 31 (2gb). This error was unintended. But the real failed code is

```<code> for(j=0;j<2;j++)
  for(i=0;i<25;i++)
   some_array[j][i] = new int[1<<24];
</code>```

so there is no sign overflow in the real code.

Size of int is 4 byte:

```<code>$ echo 'main(){return sizeof(int);}'| gcc -x c - && ./a.out; echo $?
4
</code>```

the every request will be for 1<<24 * 4 = 1<<26; total memory required is 2*25*(1<<26) 3355443200 bytes + 50*sizeof(pointer) for some_array + 50*(size of new[] overhead).

答:
EDIT: I see in other answers that the issue is most probably related with the number passed to new[] becoming negative. I agree that that is most probably the case, I am leaving this answer only because I think that it contains information that might be relevant in some similar cases, where the issue is not with calling new[] with a negative number.

The first question that comes to mind is whether you have enough available memory. With 4Gb RAM and no swap the total amount of memory that can be allocated to all processes and the kernel is 4Gb.

Note that even if you had more than 1Gb of memory available for the process, malloc and free (that are called underneath by new[] and delete[] might not give the memory back to the system, and they might in fact keep each one of the acquired/released blocks, so that the memory footprint of your program might go as high as 2Gb (would have to check this with the malloc implementation in your kernel, as many implementations do give back big blocks).

Finally, when you request an array of 1Gb you are requesting 1Gb of contiguous memory, and it might just be the case that you have much more memory but none of the blocks is large enough for that particular request.

Body:
For this easy test, and the linux box with 4Gb or RAM, 0byte of swap and CPU in x86_64 mode, I can't allocate more than 1 Gb of array.

Source:

#include <cstdio>
int main()
{
 for(int i=0;i<33;i++) {
  char*a=new char[1<<i];
  *a=1;
  delete[]a;
  printf("%d\n",i);
  fflush(stdout);
 }
}

Run:

$ file test
test: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV)
$ ./test
...
24
25
26
27
28
29
30
terminate called after throwing an instance of 'std::bad_alloc'
  what():  St9bad_alloc
Aborted

There is no ulimit for memory:

virtual memory          (kbytes, -v) unlimited
data seg size           (kbytes, -d) unlimited

Why the error?

Glibc is 2.3.4, kernel is 2.6.9

UPDATE: Compiler is gcc4.1

Thanks! The test definitely has a error, 1ull<<i gives me up to 31 (2gb). This error was unintended. But the real failed code is

 for(j=0;j<2;j++)
  for(i=0;i<25;i++)
   some_array[j][i] = new int[1<<24];

so there is no sign overflow in the real code.

Size of int is 4 byte:

$ echo 'main(){return sizeof(int);}'| gcc -x c - && ./a.out; echo $?
4

the every request will be for 1<<24 * 4 = 1<<26; total memory required is 2*25*(1<<26) 3355443200 bytes + 50*sizeof(pointer) for some_array + 50*(size of new[] overhead).


问:
FlowListView one separate label with FlowColumnCount = "1"
After using FlowListView I got the following result:

But the Emergency should be an other colour with an other click event and the size of FlowColumnCount = "1"

this is the following code:

```<code><?xml version="1.0" encoding="utf-8" ?>
</code>```

```<code>            <flv:FlowListView.FlowColumnTemplate>
                <DataTemplate>
                    <Frame BackgroundColor="Purple" Margin="5">
                        <Label HorizontalOptions="Fill"
                        VerticalOptions="Fill"
                        TextColor="White"
                        XAlign="Center"
                        YAlign="Center"
                        Text="{Binding Text}"/>
                    </Frame>
                </DataTemplate>
            </flv:FlowListView.FlowColumnTemplate>
        </flv:FlowListView>
    </StackLayout>
</ContentPage.Content>
</code>```

This is the MockDataStore:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DLToolkit.Forms.Controls;
using EscapeHaarlem.Models;

namespace EscapeHaarlem.Services
{
public class MockDataStore : IDataStore<Item>
{
    List<Item> items;

    public MockDataStore()
    {
        FlowListView.Init();
        items = new List<Item>();
        //this.items.Add(new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 1", Description = "This is an item description." });
        //this.items.Add(new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 2", Description = "This is an item description." });

        var mockItems = new List<Item>
        {
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 1", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 2", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 3", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 4", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 5", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 6", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 7", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 8", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 9", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 10", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 11", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 12", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 13", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 14", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Emergency", Description="This is an item description."},
        };

        foreach (var item in mockItems)
        {
            items.Add(item);
        }
    }

    public async Task<bool> AddItemAsync(Item item)
    {
        items.Add(item);

        return await Task.FromResult(true);
    }

    public async Task<bool> UpdateItemAsync(Item item)
    {
        var oldItem = items.Where((Item arg) => arg.Id == item.Id).FirstOrDefault();
        items.Remove(oldItem);
        items.Add(item);

        return await Task.FromResult(true);
    }

    public async Task<bool> DeleteItemAsync(string id)
    {
        var oldItem = items.Where((Item arg) => arg.Id == id).FirstOrDefault();
        items.Remove(oldItem);

        return await Task.FromResult(true);
    }

    public async Task<Item> GetItemAsync(string id)
    {
        return await Task.FromResult(items.FirstOrDefault(s => s.Id == id));
    }

    public async Task<IEnumerable<Item>> GetItemsAsync(bool forceRefresh = false)
    {
        return await Task.FromResult(items);
    }
}
</code>```

}

How could I achieve so that the emergency button has other color size and clickevent?

Thanks in advance

答:
You need to use Property triggers as seen in the docs

pseudo code:

```<code>    <Label HorizontalOptions="Fill"
                            VerticalOptions="Fill"
                            TextColor="White"
                            XAlign="Center"
                            YAlign="Center"
                            Text="{Binding Text}">

                     <Label.Triggers>
       <Trigger TargetType="Label" //TargetType sets the element type
                 Property="Text" //Element property that will be watched
                  Value="Emergency">//Value that causes the trigger
            <Setter Property="BackgroundColor" Value="Yellow" />
     //The effects the trigger will have (can be several)
           </Trigger>
     </Label.Triggers>

    </Label>
</code>```

Body:
After using FlowListView I got the following result:

But the Emergency should be an other colour with an other click event and the size of FlowColumnCount = "1"

this is the following code:

<?xml version="1.0" encoding="utf-8" ?>

            <flv:FlowListView.FlowColumnTemplate>
                <DataTemplate>
                    <Frame BackgroundColor="Purple" Margin="5">

                    </Frame>
                </DataTemplate>
            </flv:FlowListView.FlowColumnTemplate>
        </flv:FlowListView>
    </StackLayout>
</ContentPage.Content>

This is the MockDataStore:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DLToolkit.Forms.Controls;
using EscapeHaarlem.Models;

namespace EscapeHaarlem.Services
{
public class MockDataStore : IDataStore<Item>
{
    List<Item> items;

    public MockDataStore()
    {
        FlowListView.Init();
        items = new List<Item>();
        //this.items.Add(new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 1", Description = "This is an item description." });
        //this.items.Add(new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 2", Description = "This is an item description." });

        var mockItems = new List<Item>
        {
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 1", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 2", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 3", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 4", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 5", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 6", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 7", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 8", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 9", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 10", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 11", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 12", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 13", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 14", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Emergency", Description="This is an item description."},
        };

        foreach (var item in mockItems)
        {
            items.Add(item);
        }
    }

    public async Task<bool> AddItemAsync(Item item)
    {
        items.Add(item);

        return await Task.FromResult(true);
    }

    public async Task<bool> UpdateItemAsync(Item item)
    {
        var oldItem = items.Where((Item arg) => arg.Id == item.Id).FirstOrDefault();
        items.Remove(oldItem);
        items.Add(item);

        return await Task.FromResult(true);
    }

    public async Task<bool> DeleteItemAsync(string id)
    {
        var oldItem = items.Where((Item arg) => arg.Id == id).FirstOrDefault();
        items.Remove(oldItem);

        return await Task.FromResult(true);
    }

    public async Task<Item> GetItemAsync(string id)
    {
        return await Task.FromResult(items.FirstOrDefault(s => s.Id == id));
    }

    public async Task<IEnumerable<Item>> GetItemsAsync(bool forceRefresh = false)
    {
        return await Task.FromResult(items);
    }
}

}

How could I achieve so that the emergency button has other color size and clickevent?

Thanks in advance

Body:
You need to use Property triggers as seen in the docs

pseudo code:

    <Label HorizontalOptions="Fill"
                            VerticalOptions="Fill"
                            TextColor="White"
                            XAlign="Center"
                            YAlign="Center"
                            Text="{Binding Text}">

                     <Label.Triggers>
       <Trigger TargetType="Label" //TargetType sets the element type
                 Property="Text" //Element property that will be watched
                  Value="Emergency">//Value that causes the trigger
            <Setter Property="BackgroundColor" Value="Yellow" />
     //The effects the trigger will have (can be several)
           </Trigger>
     </Label.Triggers>

    </Label>


问:
How to verify whether a super class method was called in Spock?
Imagine I had the following class structure:

class Parent {
  public void method() {
    // Some calculations
  }
}
```

<pre class="lang-java prettyprint-override"><code>class Child extends Parent {
  @Override
  public void method() {
    super.method();
    // Some additional logic
  }
}
</code>```

I am spock-testing the Child.method and want to verify if the Parent.method is called from the Child.method. I did some research and i haven't found any satisfying solution to solve my problem.

How can I verify in a Spock test that in the call of Child.method the superclass method (Parent.method) was called as well?

Known solution: In Child move the super.method() to a separate, package-private method.

I want to know whether there is a better solution.

答:
If you need to enforce that some functionality in Parent is called, you should enforce it via design not tests.

```<code>abstract class Parent {
  public final void method() {
    // Some calculations
    additionalLogic();
  }

  protected abstract void additionalLogic();
}

class Child extends Parent {
  @Override
  protected void additionalLogic() {
    super.method();
    // Some additional logic
  }
}
</code>```

You could of course not make it abstract and just add a no-op implementation for additionalLogic() instead.

Body:
Imagine I had the following class structure:

class Parent {
  public void method() {
    // Some calculations
  }
}

class Child extends Parent {
  @Override
  public void method() {
    super.method();
    // Some additional logic
  }
}

I am spock-testing the Child.method and want to verify if the Parent.method is called from the Child.method. I did some research and i haven't found any satisfying solution to solve my problem.

How can I verify in a Spock test that in the call of Child.method the superclass method (Parent.method) was called as well?

Known solution: In Child move the super.method() to a separate, package-private method.

I want to know whether there is a better solution.

Body:
If you need to enforce that some functionality in Parent is called, you should enforce it via design not tests.

abstract class Parent {
  public final void method() {
    // Some calculations
    additionalLogic();
  }

  protected abstract void additionalLogic();
}

class Child extends Parent {
  @Override
  protected void additionalLogic() {
    super.method();
    // Some additional logic
  }
}

You could of course not make it abstract and just add a no-op implementation for additionalLogic() instead.


问:
Failed to save data in mongoDB
when trying to save in my Mongo database, I can't record the data, to the point of connection with the DB is fine but then it doesn't save the data.
Today is my first day with Mongo, it may be that something is wrongly configured.

My controller

```<code>exports.nuevoCliente = async (req, res, next) => {
    // console.log(req.body);

    const paciente = new Paciente(req.body);
    try {
        await paciente.save();
        res.json({ mensaje : 'El cliente se agregó correctamente'});
        console.log(paciente);

    } catch (error) {
        console.log(error);
        next();
    }
}
</code>```

When I run:

```<code>console.log(paciente);
</code>```

Result = __v: 0

Model:

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const pacientesSchema = new Schema({
    nombre: {
        type: String,
        trim: true,
    },
    propietario: {
        type: String,
        trim: true
    },
    fecha: {
        type: String,
        trim: true
    },
    telefono: {
        type: String,
        trim: true
    },
    hora: {
        type: String,
        trim: true
    },
    sintomas: {
        type: String,
        trim: true
    }
});

module.exports = mongoose.model('Paciente', pacientesSchema);
</code>```

Routes

```<code>const express = require('express');
const router = express.Router();
// Importar el controlador
const pacienteController = require('../controllers/pacienteControllers');

module.exports = function() {

    // router.get('/', () => {
    //     console.log('en home');

    // });

    // Agrega nuevos pacientes via POST
    router.post('/pacientes',
        pacienteController.nuevoCliente
    );

    return router;
}
</code>```

And the index:

```<code>const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');
const bodyParser = require('body-parser');

// Crear el servidor
const app = express();

// Conectar con MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/veterinaria', {
    useNewUrlParser: true,
    useUnifiedTopology:true,
    useFindAndModify:false
});

// Habilitar el body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// Habilitar Routing
app.use('/', routes())

// Puerto y Arrancar
app.listen(4000, () => {
    console.log('Servidor funcionando')
})
</code>```

A screenshot of the configuration in atlas

Thanks friends.

答:
According to your code, you have connected your local mongo then
You can check via MongoDB log in your terminal or mongo shell.

```<code>logfile path is - /var/log/mongodb/mongod.log
</code>```

Title: Failed to save data in mongoDB

Body:
when trying to save in my Mongo database, I can't record the data, to the point of connection with the DB is fine but then it doesn't save the data.
Today is my first day with Mongo, it may be that something is wrongly configured.

My controller

exports.nuevoCliente = async (req, res, next) => {
    // console.log(req.body);

    const paciente = new Paciente(req.body);
    try {
        await paciente.save();
        res.json({ mensaje : 'El cliente se agregó correctamente'});
        console.log(paciente);

    } catch (error) {
        console.log(error);
        next();
    }
}

When I run:

console.log(paciente);

Result = __v: 0

Model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const pacientesSchema = new Schema({
    nombre: {
        type: String,
        trim: true,
    },
    propietario: {
        type: String,
        trim: true
    },
    fecha: {
        type: String,
        trim: true
    },
    telefono: {
        type: String,
        trim: true
    },
    hora: {
        type: String,
        trim: true
    },
    sintomas: {
        type: String,
        trim: true
    }
});

module.exports = mongoose.model('Paciente', pacientesSchema);

Routes

const express = require('express');
const router = express.Router();
// Importar el controlador
const pacienteController = require('../controllers/pacienteControllers');

module.exports = function() {

    // router.get('/', () => {
    //     console.log('en home');

    // });

    // Agrega nuevos pacientes via POST
    router.post('/pacientes',
        pacienteController.nuevoCliente
    );

    return router;
}

And the index:

const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');
const bodyParser = require('body-parser');

// Crear el servidor
const app = express();

// Conectar con MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/veterinaria', {
    useNewUrlParser: true,
    useUnifiedTopology:true,
    useFindAndModify:false
});

// Habilitar el body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// Habilitar Routing
app.use('/', routes())

// Puerto y Arrancar
app.listen(4000, () => {
    console.log('Servidor funcionando')
})

A screenshot of the configuration in atlas

Thanks friends.

Body:
According to your code, you have connected your local mongo then
You can check via MongoDB log in your terminal or mongo shell.

logfile path is - /var/log/mongodb/mongod.log


问:
Mysql: Selecting id, then * on id is much faster than selecting *. Why?
I have a MySQL database table (roughly 100K rows):

id BIGINT(indexed), external_barcode VARCHAR(indexed), other simple columns, and a LongText column.

The LongText column is a JSON data dump. I save the large JSON objects because I will need to extract more of the data in the future.

When I run this query it takes 29+ seconds:

```<code>SELECT * FROM scraper_data WHERE external_barcode = '032429257284'
</code>```

EXPLAIN

```<code>#id  select_type table          partitions type  possible_keys key  key_len ref  rows     filtered Extra
'1' 'SIMPLE'     'scraper_data' NULL       'ALL' NULL          NULL NULL    NULL '119902' '0.00'   'Using where'
</code>```

This more complex query takes 0.00 seconds:

```<code>SELECT * FROM scraper_data WHERE id = (
    SELECT id FROM scraper_data WHERE external_barcode = '032429257284'
)
</code>```

EXPLAIN

```<code># id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
'1', 'PRIMARY', 'scraper_data', NULL, 'const', 'PRIMARY,id_UNIQUE', 'PRIMARY', '8', 'const', '1', '100.00', NULL
'2', 'SUBQUERY', 'scraper_data', NULL, 'ALL', NULL, NULL, NULL, NULL, '119902', '0.00', 'Using where'
</code>```

Less than 6 rows are returned from these queries. Why is the LONGTEXT slowing down the first query given that its not being referenced in the where clause?

CREATE TABLE

```<code>CREATE TABLE `scraper_data` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `bzic` varchar(10) NOT NULL,
  `pzic` varchar(10) DEFAULT NULL,
  `internal_barcode` varchar(20) DEFAULT NULL,
  `external_barcode_type` enum('upc','isbn','ean','gtin') DEFAULT NULL,
  `external_barcode` varchar(15) DEFAULT NULL,
  `url` varchar(255) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `category` varchar(3) DEFAULT NULL,
  `description` text,
  `logo_image_url` varchar(255) DEFAULT NULL,
  `variant_image_urls` text,
  `parent_brand` varchar(10) DEFAULT NULL,
  `parent_brand_name` varchar(255) DEFAULT NULL,
  `manufacturer` varchar(10) DEFAULT NULL,
  `manufacturer_name` varchar(255) DEFAULT NULL,
  `manufacturer_part_number` varchar(255) DEFAULT NULL,
  `manufacturer_model_number` varchar(255) DEFAULT NULL,
  `contributors` text,
  `content_info` text,
  `content_rating` text,
  `release_date` timestamp NULL DEFAULT NULL,
  `reviews` int(11) DEFAULT NULL,
  `ratings` int(11) DEFAULT NULL,
  `internal_path` varchar(255) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `adult_product` tinyint(4) DEFAULT NULL,
  `height` varchar(255) DEFAULT NULL,
  `length` varchar(255) DEFAULT NULL,
  `width` varchar(255) DEFAULT NULL,
  `weight` varchar(255) DEFAULT NULL,
  `scraped` tinyint(4) NOT NULL DEFAULT '0',
  `scraped_timestamp` timestamp NULL DEFAULT NULL,
  `scrape_attempt_timestamp` timestamp NULL DEFAULT NULL,
  `processed` tinyint(4) NOT NULL DEFAULT '0',
  `processed_timestamp` timestamp NULL DEFAULT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `scrape_dump` longtext,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`),
  UNIQUE KEY `url_UNIQUE` (`url`),
  UNIQUE KEY `internal_barcode_UNIQUE` (`internal_barcode`),
  KEY `bzic` (`bzic`),
  KEY `pzic` (`pzic`),
  KEY `internal_barcode` (`internal_barcode`),
  KEY `external_barcode` (`external_barcode`,`external_barcode_type`) /*!80000 INVISIBLE */,
  KEY `scrape_attempt` (`bzic`,`scraped`,`scrape_attempt_timestamp`)
) ENGINE=InnoDB AUTO_INCREMENT=121674 DEFAULT CHARSET=latin1;

</code>```

答:
The second query could benefit from the cache that already contains the result of the first query.

In addition in the second subquery you just select use two column (id,  external_barcode ) in these two column are in a index  all the query result is obtained  only with the index  scan while in the first query for retrieve all the data the query must scan all the tables  row ..

For avoiding the long time for the first query, you should add a proper index on  external_barcode column

```<code>create index my_idx  on scraper_data (external_barcode, id)
</code>```

Body:
I have a MySQL database table (roughly 100K rows):

id BIGINT(indexed), external_barcode VARCHAR(indexed), other simple columns, and a LongText column.

The LongText column is a JSON data dump. I save the large JSON objects because I will need to extract more of the data in the future.

When I run this query it takes 29+ seconds:

SELECT * FROM scraper_data WHERE external_barcode = '032429257284'

EXPLAIN

#id  select_type table          partitions type  possible_keys key  key_len ref  rows     filtered Extra
'1' 'SIMPLE'     'scraper_data' NULL       'ALL' NULL          NULL NULL    NULL '119902' '0.00'   'Using where'

This more complex query takes 0.00 seconds:

SELECT * FROM scraper_data WHERE id = (
    SELECT id FROM scraper_data WHERE external_barcode = '032429257284'
)

EXPLAIN

# id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
'1', 'PRIMARY', 'scraper_data', NULL, 'const', 'PRIMARY,id_UNIQUE', 'PRIMARY', '8', 'const', '1', '100.00', NULL
'2', 'SUBQUERY', 'scraper_data', NULL, 'ALL', NULL, NULL, NULL, NULL, '119902', '0.00', 'Using where'

Less than 6 rows are returned from these queries. Why is the LONGTEXT slowing down the first query given that its not being referenced in the where clause?

CREATE TABLE

CREATE TABLE `scraper_data` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `bzic` varchar(10) NOT NULL,
  `pzic` varchar(10) DEFAULT NULL,
  `internal_barcode` varchar(20) DEFAULT NULL,
  `external_barcode_type` enum('upc','isbn','ean','gtin') DEFAULT NULL,
  `external_barcode` varchar(15) DEFAULT NULL,
  `url` varchar(255) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `category` varchar(3) DEFAULT NULL,
  `description` text,
  `logo_image_url` varchar(255) DEFAULT NULL,
  `variant_image_urls` text,
  `parent_brand` varchar(10) DEFAULT NULL,
  `parent_brand_name` varchar(255) DEFAULT NULL,
  `manufacturer` varchar(10) DEFAULT NULL,
  `manufacturer_name` varchar(255) DEFAULT NULL,
  `manufacturer_part_number` varchar(255) DEFAULT NULL,
  `manufacturer_model_number` varchar(255) DEFAULT NULL,
  `contributors` text,
  `content_info` text,
  `content_rating` text,
  `release_date` timestamp NULL DEFAULT NULL,
  `reviews` int(11) DEFAULT NULL,
  `ratings` int(11) DEFAULT NULL,
  `internal_path` varchar(255) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `adult_product` tinyint(4) DEFAULT NULL,
  `height` varchar(255) DEFAULT NULL,
  `length` varchar(255) DEFAULT NULL,
  `width` varchar(255) DEFAULT NULL,
  `weight` varchar(255) DEFAULT NULL,
  `scraped` tinyint(4) NOT NULL DEFAULT '0',
  `scraped_timestamp` timestamp NULL DEFAULT NULL,
  `scrape_attempt_timestamp` timestamp NULL DEFAULT NULL,
  `processed` tinyint(4) NOT NULL DEFAULT '0',
  `processed_timestamp` timestamp NULL DEFAULT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `scrape_dump` longtext,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`),
  UNIQUE KEY `url_UNIQUE` (`url`),
  UNIQUE KEY `internal_barcode_UNIQUE` (`internal_barcode`),
  KEY `bzic` (`bzic`),
  KEY `pzic` (`pzic`),
  KEY `internal_barcode` (`internal_barcode`),
  KEY `external_barcode` (`external_barcode`,`external_barcode_type`) /*!80000 INVISIBLE */,
  KEY `scrape_attempt` (`bzic`,`scraped`,`scrape_attempt_timestamp`)
) ENGINE=InnoDB AUTO_INCREMENT=121674 DEFAULT CHARSET=latin1;

Body:
The second query could benefit from the cache that already contains the result of the first query.

In addition in the second subquery you just select use two column (id,  external_barcode ) in these two column are in a index  all the query result is obtained  only with the index  scan while in the first query for retrieve all the data the query must scan all the tables  row ..

For avoiding the long time for the first query, you should add a proper index on  external_barcode column

create index my_idx  on scraper_data (external_barcode, id)


问:
How to store trip itinerary data into DynamoDB?
I am trying to figure out the best way to store trip itinerary data into DynamoDB. Just for your info, my code is written in Python3 and I am using Boto3 to interact with DynamoDB.

After researching on this resource - https://schema.org/Trip, this is what I think would be the data classes of the objects.

```<code>from marshmallow_dataclass import dataclass
from typing import List, Optional

@dataclass(frozen=True)
class Itinerary:
    id: str
    startTime: int
    endTime: int
    dayTripId: str
    placeName: str
    placeCategory: str
    estimatedCost: float

@dataclass(frozen=True)
class DayTrip:
    id: str
    day: str
    parentTripId: str
    date: Optional[str]
    itinerary: List[Itinerary]

@dataclass(frozen=True)
class UserTrip:
    tripId: str
    userId: str
    tripName: str
    subTrip: List[DayTrip]
</code>```

Essentially, the structure is as follows:

A person can have many UserTrips

A UserTrip can consist of one day or multiple day of DayTrip, e.g. Day 1, Day 2, Day 3

A DayTrip can have one or multiple places to visit (Itinerary)

An Itinerary is the lowest level that describes the place to visit

It wouldn't be good to store the UserTrip as is, with nested JSON structure consisting of DayTrip, then Itinerary, right? It would mean that the subTrip attribute of a particular UserTrip will be a huge chuck of JSON. So I think everyone here would agree this is a no, no. Is that correct?

Another alternative that I could think of was to store only the id of each entity. What I mean by this is, for example, a UserTrip will have its subTrip attribute containing a list of the DayTrip id. This means there will be another table to store DayTrip items and we can connect it to the corresponding UserTrip via the parentTripId attribute. And so on for the list of Itinerary.

Using this approach, I will have 3 x tables as follows:

user-trip-table to store UserTrip where subTrip will contain the list of DayTrip.ids

user-day-trip-table to store DayTrip where itinerary will contain the list of Itinerary.ids. The parentTripId will enable the mapping back to the original UserTrip

user-itinerary-table to store Itinerary where it can be mapped back to the original DayTrip via dayTripId attribute.

I am not sure if this is a good practice as there will be a lot of lookups happening and asynchronous operations are not possible here. This is because, to fetch the Itinerary, I need to wait for the completion of GetItem operation to get UserTrip, then, I will have the ids of the DayTrip and then, I will do another GetItem to fetch the DayTrip, then, finally, another GetItem to fetch the Itinerary.

Could the community here suggest a better, simpler solution?

Thanks!

答:
Regarding the data structure, I don't see an absolute need for DayTrip, as you can get all that data from Itinerary. So in UserTrip I would keep a list of Itineraries instead of a list of DayTrips.

It wouldn't be good to store the UserTrip as is, with nested JSON
  structure consisting of DayTrip, then Itinerary, right? It would mean
  that the subTrip attribute of a particular UserTrip will be a huge
  chuck of JSON. So I think everyone here would agree this is a no, no.
  Is that correct?

Actually this is recommended in NoSQL databases, to have all data denormalised/embedded in the object. You use more storage, but avoid joins/processing. But keep in mind DynamoDB's item size limitation (currently 400KB).

In general, in NoSQL, you need to create your schema based on the queries you will need. For example in your case, you want to fetch all Itineraries of a UserTrip. Simply add userTripId to the Itinerary table. Create a GSI on Itinerary
with userTripId as hash key so you can query it efficiently. This way you will get all itinerary objects of a user trip.

Body:
I am trying to figure out the best way to store trip itinerary data into DynamoDB. Just for your info, my code is written in Python3 and I am using Boto3 to interact with DynamoDB.

After researching on this resource - https://schema.org/Trip, this is what I think would be the data classes of the objects.

from marshmallow_dataclass import dataclass
from typing import List, Optional

@dataclass(frozen=True)
class Itinerary:
    id: str
    startTime: int
    endTime: int
    dayTripId: str
    placeName: str
    placeCategory: str
    estimatedCost: float

@dataclass(frozen=True)
class DayTrip:
    id: str
    day: str
    parentTripId: str
    date: Optional[str]
    itinerary: List[Itinerary]

@dataclass(frozen=True)
class UserTrip:
    tripId: str
    userId: str
    tripName: str
    subTrip: List[DayTrip]

Essentially, the structure is as follows:

A person can have many UserTrips

A UserTrip can consist of one day or multiple day of DayTrip, e.g. Day 1, Day 2, Day 3

A DayTrip can have one or multiple places to visit (Itinerary)

An Itinerary is the lowest level that describes the place to visit

It wouldn't be good to store the UserTrip as is, with nested JSON structure consisting of DayTrip, then Itinerary, right? It would mean that the subTrip attribute of a particular UserTrip will be a huge chuck of JSON. So I think everyone here would agree this is a no, no. Is that correct?

Another alternative that I could think of was to store only the id of each entity. What I mean by this is, for example, a UserTrip will have its subTrip attribute containing a list of the DayTrip id. This means there will be another table to store DayTrip items and we can connect it to the corresponding UserTrip via the parentTripId attribute. And so on for the list of Itinerary.

Using this approach, I will have 3 x tables as follows:

user-trip-table to store UserTrip where subTrip will contain the list of DayTrip.ids

user-day-trip-table to store DayTrip where itinerary will contain the list of Itinerary.ids. The parentTripId will enable the mapping back to the original UserTrip

user-itinerary-table to store Itinerary where it can be mapped back to the original DayTrip via dayTripId attribute.

I am not sure if this is a good practice as there will be a lot of lookups happening and asynchronous operations are not possible here. This is because, to fetch the Itinerary, I need to wait for the completion of GetItem operation to get UserTrip, then, I will have the ids of the DayTrip and then, I will do another GetItem to fetch the DayTrip, then, finally, another GetItem to fetch the Itinerary.

Could the community here suggest a better, simpler solution?

Thanks!