问:
Tailwind CSS classes is not working with React, error "You need to enable JavaScript to run this app..."
Talwind CSS is not working with React. I have installed Tailwind CSS as per the documentation (https://v1.tailwindcss.com/docs/installation) and my code is below.

Can someone help me?

Here is my browser pic of the inspect to understand my problem

Here is my package.json file

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "autoprefixer": "^10.4.2",
    "postcss-cli": "^9.1.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "tailwindcss": "^3.0.18",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "build:css": "postcss src/assets/css/tailwind.css -o src/assets/css/style.css",
    "start": "npm run build:css && react-scripts start ",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

```
<p>Below is my postcss.config.js</p>
<pre class="lang-js prettyprint-override"><code>  module.exports = {
    plugins: {
        tailwindcss: {},
        autoprefixer: {},
    },
  }
</code>```

Below is my tailwind.config.js

  module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  plugins: [
    // ...
    require('tailwindcss'),
    require('autoprefixer'),
    // ...
  ]
}

```
<p>Later, I edited my index.js</p>
```import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

//const App = require("./App");

ReactDOM.render(
    <App title="Heyy React Dev Tool"/>, document.getElementById("root")
);
```
<p>I also edited my App.js like below</p>
```  import React from "react";
  import "./assets/css/style.css"

    function App({title}) {
      return (

{title}

      );

    }
    export default App;
```
<p>Last but now least these is my style.css file is generated</p>
<p>Style.css</p>
<pre class="lang-css prettyprint-override"><code>/*
! tailwindcss v3.0.18 | MIT License | https://tailwindcss.com
*//*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/

*,
::before,
::after {
  box-sizing: border-box; /* 1 */
  border-width: 0; /* 2 */
  border-style: solid; /* 2 */
  border-color: #e5e7eb; /* 2 */
}

::before,
::after {
  --tw-content: '';
}

/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
*/

html {
  line-height: 1.5; /* 1 */
  -webkit-text-size-adjust: 100%; /* 2 */ /* 3 */
  tab-size: 4; /* 3 */
  font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 4 */
}

/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/

body {
  margin: 0; /* 1 */
  line-height: inherit; /* 2 */
}

/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/

hr {
  height: 0; /* 1 */
  color: inherit; /* 2 */
  border-top-width: 1px; /* 3 */
}

/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/

abbr:where([title]) {
  text-decoration: underline dotted;
}

/*
Remove the default font size and weight for headings.
*/

h1,
h2,
h3,
h4,
h5,
h6 {
  font-size: inherit;
  font-weight: inherit;
}

/*
Reset links to optimize for opt-in styling instead of opt-out.
*/

a {
  color: inherit;
  text-decoration: inherit;
}

/*
Add the correct font weight in Edge and Safari.
*/

b,
strong {
  font-weight: bolder;
}

/*
1. Use the user's configured `mono` font family by default.
2. Correct the odd `em` font sizing in all browsers.
*/

code,
kbd,
samp,
pre {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; /* 1 */
  font-size: 1em; /* 2 */
}

/*
Add the correct font size in all browsers.
*/

small {
  font-size: 80%;
}

/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/

sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -0.25em;
}

sup {
  top: -0.5em;
}

/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/

table {
  text-indent: 0; /* 1 */
  border-color: inherit; /* 2 */
  border-collapse: collapse; /* 3 */
}

/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/

button,
input,
optgroup,
select,
textarea {
  font-family: inherit; /* 1 */
  font-size: 100%; /* 1 */
  line-height: inherit; /* 1 */
  color: inherit; /* 1 */
  margin: 0; /* 2 */
  padding: 0; /* 3 */
}

/*
Remove the inheritance of text transform in Edge and Firefox.
*/

button,
select {
  text-transform: none;
}

/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/

button,
[type='button'],
[type='reset'],
[type='submit'] {
  -webkit-appearance: button; /* 1 */
  background-color: transparent; /* 2 */
  background-image: none; /* 2 */
}

/*
Use the modern Firefox focus style for all focusable elements.
*/

:-moz-focusring {
  outline: auto;
}

/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/

:-moz-ui-invalid {
  box-shadow: none;
}

/*
Add the correct vertical alignment in Chrome and Firefox.
*/

progress {
  vertical-align: baseline;
}

/*
Correct the cursor style of increment and decrement buttons in Safari.
*/

::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
  height: auto;
}

/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/

[type='search'] {
  -webkit-appearance: textfield; /* 1 */
  outline-offset: -2px; /* 2 */
}

/*
Remove the inner padding in Chrome and Safari on macOS.
*/

::-webkit-search-decoration {
  -webkit-appearance: none;
}

/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/

::-webkit-file-upload-button {
  -webkit-appearance: button; /* 1 */
  font: inherit; /* 2 */
}

/*
Add the correct display in Chrome and Safari.
*/

summary {
  display: list-item;
}

/*
Removes the default spacing and border for appropriate elements.
*/

blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
  margin: 0;
}

fieldset {
  margin: 0;
  padding: 0;
}

legend {
  padding: 0;
}

ol,
ul,
menu {
  list-style: none;
  margin: 0;
  padding: 0;
}

/*
Prevent resizing textareas horizontally by default.
*/

textarea {
  resize: vertical;
}

/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/

input::placeholder,
textarea::placeholder {
  opacity: 1; /* 1 */
  color: #9ca3af; /* 2 */
}

/*
Set the default cursor for buttons.
*/

button,
[role="button"] {
  cursor: pointer;
}

/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
  cursor: default;
}

/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
   This can trigger a poorly considered lint error in some tools but is included by design.
*/

img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
  display: block; /* 1 */
  vertical-align: middle; /* 2 */
}

/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/

img,
video {
  max-width: 100%;
  height: auto;
}

/*
Ensure the default browser behavior of the `hidden` attribute.
*/

[hidden] {
  display: none;
}

*, ::before, ::after {
  --tw-translate-x: 0;
  --tw-translate-y: 0;
  --tw-rotate: 0;
  --tw-skew-x: 0;
  --tw-skew-y: 0;
  --tw-scale-x: 1;
  --tw-scale-y: 1;
  --tw-pan-x:  ;
  --tw-pan-y:  ;
  --tw-pinch-zoom:  ;
  --tw-scroll-snap-strictness: proximity;
  --tw-ordinal:  ;
  --tw-slashed-zero:  ;
  --tw-numeric-figure:  ;
  --tw-numeric-spacing:  ;
  --tw-numeric-fraction:  ;
  --tw-ring-inset:  ;
  --tw-ring-offset-width: 0px;
  --tw-ring-offset-color: #fff;
  --tw-ring-color: rgb(59 130 246 / 0.5);
  --tw-ring-offset-shadow: 0 0 #0000;
  --tw-ring-shadow: 0 0 #0000;
  --tw-shadow: 0 0 #0000;
  --tw-shadow-colored: 0 0 #0000;
  --tw-blur:  ;
  --tw-brightness:  ;
  --tw-contrast:  ;
  --tw-grayscale:  ;
  --tw-hue-rotate:  ;
  --tw-invert:  ;
  --tw-saturate:  ;
  --tw-sepia:  ;
  --tw-drop-shadow:  ;
  --tw-backdrop-blur:  ;
  --tw-backdrop-brightness:  ;
  --tw-backdrop-contrast:  ;
  --tw-backdrop-grayscale:  ;
  --tw-backdrop-hue-rotate:  ;
  --tw-backdrop-invert:  ;
  --tw-backdrop-opacity:  ;
  --tw-backdrop-saturate:  ;
  --tw-backdrop-sepia:  ;
}

'```
```

答:
I've looked at your repo: and even though you said you followed the guide, you didn't. The issue boils down to not really following through the documentation properly.

This line is missing in your tailwind.config.js file, which causes tailwind to fail to detect class usage in all your .js file:

```<code>module.exports = {
  // You are missing this block that defines what files tailwind should scan for usage
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
</code>```

Once you add this line your CSS should build properly:

Other signs that you didn't follow the guide properly:

tailwindcss is listed as a dependency and not a devDependency

Your tailwind.config.js file appears outdated. Are you sure you ran npx tailwindcss init properly? Are you sure that you are indeed running v3 of Tailwind CSS?

Body:
Talwind CSS is not working with React. I have installed Tailwind CSS as per the documentation (https://v1.tailwindcss.com/docs/installation) and my code is below.

Can someone help me?

Here is my browser pic of the inspect to understand my problem

Here is my package.json file

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "autoprefixer": "^10.4.2",
    "postcss-cli": "^9.1.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "tailwindcss": "^3.0.18",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "build:css": "postcss src/assets/css/tailwind.css -o src/assets/css/style.css",
    "start": "npm run build:css && react-scripts start ",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Below is my postcss.config.js

  module.exports = {
    plugins: {
        tailwindcss: {},
        autoprefixer: {},
    },
  }

Below is my tailwind.config.js

  module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  plugins: [
    // ...
    require('tailwindcss'),
    require('autoprefixer'),
    // ...
  ]
}

Later, I edited my index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

//const App = require("./App");

ReactDOM.render(
    <App title="Heyy React Dev Tool"/>, document.getElementById("root")
);

I also edited my App.js like below

  import React from "react";
  import "./assets/css/style.css"

    function App({title}) {
      return (

{title}

      );

    }
    export default App;

Last but now least these is my style.css file is generated

Style.css

/*
! tailwindcss v3.0.18 | MIT License | https://tailwindcss.com
*//*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/

*,
::before,
::after {
  box-sizing: border-box; /* 1 */
  border-width: 0; /* 2 */
  border-style: solid; /* 2 */
  border-color: #e5e7eb; /* 2 */
}

::before,
::after {
  --tw-content: '';
}

/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
*/

html {
  line-height: 1.5; /* 1 */
  -webkit-text-size-adjust: 100%; /* 2 */ /* 3 */
  tab-size: 4; /* 3 */
  font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 4 */
}

/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/

body {
  margin: 0; /* 1 */
  line-height: inherit; /* 2 */
}

/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/

hr {
  height: 0; /* 1 */
  color: inherit; /* 2 */
  border-top-width: 1px; /* 3 */
}

/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/

abbr:where([title]) {
  text-decoration: underline dotted;
}

/*
Remove the default font size and weight for headings.
*/

h1,
h2,
h3,
h4,
h5,
h6 {
  font-size: inherit;
  font-weight: inherit;
}

/*
Reset links to optimize for opt-in styling instead of opt-out.
*/

a {
  color: inherit;
  text-decoration: inherit;
}

/*
Add the correct font weight in Edge and Safari.
*/

b,
strong {
  font-weight: bolder;
}

/*
1. Use the user's configured `mono` font family by default.
2. Correct the odd `em` font sizing in all browsers.
*/

code,
kbd,
samp,
pre {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; /* 1 */
  font-size: 1em; /* 2 */
}

/*
Add the correct font size in all browsers.
*/

small {
  font-size: 80%;
}

/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/

sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -0.25em;
}

sup {
  top: -0.5em;
}

/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/

table {
  text-indent: 0; /* 1 */
  border-color: inherit; /* 2 */
  border-collapse: collapse; /* 3 */
}

/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/

button,
input,
optgroup,
select,
textarea {
  font-family: inherit; /* 1 */
  font-size: 100%; /* 1 */
  line-height: inherit; /* 1 */
  color: inherit; /* 1 */
  margin: 0; /* 2 */
  padding: 0; /* 3 */
}

/*
Remove the inheritance of text transform in Edge and Firefox.
*/

button,
select {
  text-transform: none;
}

/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/

button,
[type='button'],
[type='reset'],
[type='submit'] {
  -webkit-appearance: button; /* 1 */
  background-color: transparent; /* 2 */
  background-image: none; /* 2 */
}

/*
Use the modern Firefox focus style for all focusable elements.
*/

:-moz-focusring {
  outline: auto;
}

/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/

:-moz-ui-invalid {
  box-shadow: none;
}

/*
Add the correct vertical alignment in Chrome and Firefox.
*/

progress {
  vertical-align: baseline;
}

/*
Correct the cursor style of increment and decrement buttons in Safari.
*/

::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
  height: auto;
}

/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/

[type='search'] {
  -webkit-appearance: textfield; /* 1 */
  outline-offset: -2px; /* 2 */
}

/*
Remove the inner padding in Chrome and Safari on macOS.
*/

::-webkit-search-decoration {
  -webkit-appearance: none;
}

/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/

::-webkit-file-upload-button {
  -webkit-appearance: button; /* 1 */
  font: inherit; /* 2 */
}

/*
Add the correct display in Chrome and Safari.
*/

summary {
  display: list-item;
}

/*
Removes the default spacing and border for appropriate elements.
*/

blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
  margin: 0;
}

fieldset {
  margin: 0;
  padding: 0;
}

legend {
  padding: 0;
}

ol,
ul,
menu {
  list-style: none;
  margin: 0;
  padding: 0;
}

/*
Prevent resizing textareas horizontally by default.
*/

textarea {
  resize: vertical;
}

/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/

input::placeholder,
textarea::placeholder {
  opacity: 1; /* 1 */
  color: #9ca3af; /* 2 */
}

/*
Set the default cursor for buttons.
*/

button,
[role="button"] {
  cursor: pointer;
}

/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
  cursor: default;
}

/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
   This can trigger a poorly considered lint error in some tools but is included by design.
*/

img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
  display: block; /* 1 */
  vertical-align: middle; /* 2 */
}

/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/

img,
video {
  max-width: 100%;
  height: auto;
}

/*
Ensure the default browser behavior of the `hidden` attribute.
*/

[hidden] {
  display: none;
}

*, ::before, ::after {
  --tw-translate-x: 0;
  --tw-translate-y: 0;
  --tw-rotate: 0;
  --tw-skew-x: 0;
  --tw-skew-y: 0;
  --tw-scale-x: 1;
  --tw-scale-y: 1;
  --tw-pan-x:  ;
  --tw-pan-y:  ;
  --tw-pinch-zoom:  ;
  --tw-scroll-snap-strictness: proximity;
  --tw-ordinal:  ;
  --tw-slashed-zero:  ;
  --tw-numeric-figure:  ;
  --tw-numeric-spacing:  ;
  --tw-numeric-fraction:  ;
  --tw-ring-inset:  ;
  --tw-ring-offset-width: 0px;
  --tw-ring-offset-color: #fff;
  --tw-ring-color: rgb(59 130 246 / 0.5);
  --tw-ring-offset-shadow: 0 0 #0000;
  --tw-ring-shadow: 0 0 #0000;
  --tw-shadow: 0 0 #0000;
  --tw-shadow-colored: 0 0 #0000;
  --tw-blur:  ;
  --tw-brightness:  ;
  --tw-contrast:  ;
  --tw-grayscale:  ;
  --tw-hue-rotate:  ;
  --tw-invert:  ;
  --tw-saturate:  ;
  --tw-sepia:  ;
  --tw-drop-shadow:  ;
  --tw-backdrop-blur:  ;
  --tw-backdrop-brightness:  ;
  --tw-backdrop-contrast:  ;
  --tw-backdrop-grayscale:  ;
  --tw-backdrop-hue-rotate:  ;
  --tw-backdrop-invert:  ;
  --tw-backdrop-opacity:  ;
  --tw-backdrop-saturate:  ;
  --tw-backdrop-sepia:  ;
}

'```

Body:
I've looked at your repo: and even though you said you followed the guide, you didn't. The issue boils down to not really following through the documentation properly.

This line is missing in your tailwind.config.js file, which causes tailwind to fail to detect class usage in all your .js file:

module.exports = {
  // You are missing this block that defines what files tailwind should scan for usage
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Once you add this line your CSS should build properly:

Other signs that you didn't follow the guide properly:

tailwindcss is listed as a dependency and not a devDependency

Your tailwind.config.js file appears outdated. Are you sure you ran npx tailwindcss init properly? Are you sure that you are indeed running v3 of Tailwind CSS?


来源: stackexchange

问:
Maplotlib and Basemap: cannot import name 'dedent'
I'm trying to draw a network on a basemap overlay.
I have packages:

basemap=1.3.0=py36ha7665c8_0

matplotlib=3.3.1=0

matplotlib-base=3.3.1=py36hba9282a_0

networkx=2.5=py_0

When I run only the line

from mpl_toolkits.basemap import Basemap

I get

    from matplotlib.cbook import dedent

ImportError: cannot import name 'dedent'

I've tried several different versions of the packages but cannot manage to find the right functioning combination.

Anyone have any ideas on combinations of matpltlib and basemap that work? Or another way to plot my network over a basemap?

答:
I tried to find a solution online that does not require altering any files. While in an Anaconda environment, use:

conda install matplotlib=3.2

Please note that support for Basemap is discontinued and should be avoided.

ContentLicense: CC BY-SA 4.0


问:
Calling an API that have username and password in Java
I'm trying to connect to an API that has a username and password with this code:

```<code>try {
    URL url = new URL("https://url?UserName=username&Password=password");
    Connection = (HttpURLConnection) url.openConnection();

    //Request setup
    Connection.setRequestMethod("GET");
    Connection.setConnectTimeout(5000);
    Connection.setReadTimeout(5000);
    int status = Connection.getResponseCode();
    System.out.println(status);

}
catch (MalformedURLException e) {
    e.printStackTrace();
}
catch (IOException e) {
    e.printStackTrace();
}
</code>```

But I get the error:

java.net.SocketException: Connection reset

I kept searching and I found another format for the URL which is:

```<code>URL url = new URL("Https:username:password@url);
</code>```

When I tried, it gave me the error:

java.net.MalformedURLException: For input string:password@url

I tried to separate the URL into three strings and made the password Integer.pharsInt("String"), but it also didn't work.
The password has words, numbers, and a special character!

What am I doing wrong?

答:
Try to encode your URL, this way:</p>
```<code>HttpURLConnection connection = (HttpURLConnection)
    new URL("https://url?UserName" +
            URLEncoder.encode(username, "UTF-8") +
            "&Password=" +
            URLEncoder.encode(password, "UTF-8"))
            .openConnection();

connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
InputStream is = connection.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));

// The rest of your code
</code>```

Body:
I'm trying to connect to an API that has a username and password with this code:

try {
    URL url = new URL("https://url?UserName=username&Password=password");
    Connection = (HttpURLConnection) url.openConnection();

    //Request setup
    Connection.setRequestMethod("GET");
    Connection.setConnectTimeout(5000);
    Connection.setReadTimeout(5000);
    int status = Connection.getResponseCode();
    System.out.println(status);

}
catch (MalformedURLException e) {
    e.printStackTrace();
}
catch (IOException e) {
    e.printStackTrace();
}

But I get the error:

java.net.SocketException: Connection reset

I kept searching and I found another format for the URL which is:

URL url = new URL("Https:username:password@url);

When I tried, it gave me the error:

java.net.MalformedURLException: For input string:password@url

I tried to separate the URL into three strings and made the password Integer.pharsInt("String"), but it also didn't work.
The password has words, numbers, and a special character!

What am I doing wrong?

Body:
Try to encode your URL, this way:

HttpURLConnection connection = (HttpURLConnection)
    new URL("https://url?UserName" +
            URLEncoder.encode(username, "UTF-8") +
            "&Password=" +
            URLEncoder.encode(password, "UTF-8"))
            .openConnection();

connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
InputStream is = connection.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));

// The rest of your code


问:
Search for emails sent to a person containing a keyword in iOS Outlook?
On my iPhone, using Outlook, can I search for a keyword in a mail received from somebody? If I search for the keyword I see all the emails I received from everybody containing the keyword. But is there a way to search for all the emails sent to a particular user containing the keyword?</p>

答: Search for the name - this should bring it up at the top of the page - select it and recent emails should be shown. If that doesn't work, try searching for "keyword name".</p>


问:
How to add every combination of numbers in an array
I'm taking in an array of numbers [4, 6, 23, 10, 1, 3] I need to return true if any combinations of numbers in the array add up to the largest number in the array. So the example above should return true because 3 + 4 + 6 + 10 = 23

My thought behind this problem is I should first put the array in numerical order then make a new array with just the numbers I'm adding because I'm not adding the largest number. Then I need some method that says "If any combination of adding these numbers together equals the largest number in the original array return true". This is the code I've written so far, but I'm stuck on the for loop.. Any help would be very much appreciated!

```<code>function ArrayChallenge(arr){
  let order = arr.sort(function(a, b){return a-b})
  let addThese = order.slice(0,order.length-1)

  for(i = 0; i < addThese.length-1; i++){
    return true
  }
}

console.log(ArrayChallenge([3,5,-1,8,12]))
</code>```

答:
It seems like a trick question. Here's the answer:

```<code>function ArrayChallenge(arr){
  return true
}
</code>```

Because the sum of just the largest number is always equal to the largest number.

If this solution is somehow not allowed, see subset sum problem:

there is a multiset S of integers and a target-sum T, and the question is to decide whether any subset of the integers sum to precisely T.

The most straightforward solution to that problem is with recursion; something like this:

```<code>function subsetSum(arr, sum) {
  if (arr.length == 0) {
    // No numbers left in the array. The only sum we can make is 0.
    // If that is the sum we are seeking, great!
    return sum == 0
  } else {
    // We will try both using and not using the first number in the array.
    // The rest is passed to the recursive call.
    const [current, ...remaining] = arr
    return (
      // Exclude current number, and recurse. We have to make the full
      // sum with the remaining numbers.
      subsetSum(remaining, sum) ||
      // Include current number, meaning we have sum - current left
      // to make with the remaining numbers.
      subsetSum(remaining, sum - current)
    )
  }
}
</code>```

Body:
I'm taking in an array of numbers [4, 6, 23, 10, 1, 3] I need to return true if any combinations of numbers in the array add up to the largest number in the array. So the example above should return true because 3 + 4 + 6 + 10 = 23

My thought behind this problem is I should first put the array in numerical order then make a new array with just the numbers I'm adding because I'm not adding the largest number. Then I need some method that says "If any combination of adding these numbers together equals the largest number in the original array return true". This is the code I've written so far, but I'm stuck on the for loop.. Any help would be very much appreciated!

function ArrayChallenge(arr){
  let order = arr.sort(function(a, b){return a-b})
  let addThese = order.slice(0,order.length-1)

  for(i = 0; i < addThese.length-1; i++){
    return true
  }
}

console.log(ArrayChallenge([3,5,-1,8,12]))

Body:
It seems like a trick question. Here's the answer:

function ArrayChallenge(arr){
  return true
}

Because the sum of just the largest number is always equal to the largest number.

If this solution is somehow not allowed, see subset sum problem:

there is a multiset S of integers and a target-sum T, and the question is to decide whether any subset of the integers sum to precisely T.

The most straightforward solution to that problem is with recursion; something like this:

function subsetSum(arr, sum) {
  if (arr.length == 0) {
    // No numbers left in the array. The only sum we can make is 0.
    // If that is the sum we are seeking, great!
    return sum == 0
  } else {
    // We will try both using and not using the first number in the array.
    // The rest is passed to the recursive call.
    const [current, ...remaining] = arr
    return (
      // Exclude current number, and recurse. We have to make the full
      // sum with the remaining numbers.
      subsetSum(remaining, sum) ||
      // Include current number, meaning we have sum - current left
      // to make with the remaining numbers.
      subsetSum(remaining, sum - current)
    )
  }
}


问:
HTML list-style-type dash
Is there a way to create a list-style in HTML with a dash (i.e. - or – – or — —) i.e.

```<code><ul>
  <li>abc</li>
</ul>
</code>```

Outputting:

```<code>- abc
</code>```

It's occurred to me to do this with something like li:before { content: "-" };, though I don't know the cons of that option (and would be much obliged for feedback).

More generically, I wouldn't mind knowing how to use generic characters for list items.

答:
When using symbols that do not exist on the keyboard, see HTML entities and use CSS code values for the list-style-type property. See the list of CSS codes at HTML Character Entity References for different symbols.

For symbols that are there on the keyboard, use the keyboard symbols directly as values to the list-style-type property.

See example code below:

HTML Entities: Long Rightwards Double Arrow

One

Two

Three

Dash symbol on the keyboard

One

Two

Three

```

ContentLicense: CC BY-SA 3.0

Title: HTML list-style-type dash

Body:
Is there a way to create a list-style in HTML with a dash (i.e. - or – – or — —) i.e.

abc

Outputting:

- abc

It's occurred to me to do this with something like li:before { content: "-" };, though I don't know the cons of that option (and would be much obliged for feedback).

More generically, I wouldn't mind knowing how to use generic characters for list items.

Body:
When using symbols that do not exist on the keyboard, see HTML entities and use CSS code values for the list-style-type property. See the list of CSS codes at HTML Character Entity References for different symbols.

For symbols that are there on the keyboard, use the keyboard symbols directly as values to the list-style-type property.

See example code below:

<!-- See HTML entities for symbols NOT on the keyboard -->
<h3>HTML Entities: Long Rightwards Double Arrow</h3>
<ul style="list-style-type: '\27F9';">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

<!-- Use symbols on the keyboard directly -->
<h3>Dash symbol on the keyboard</h3>
<ul style="list-style-type: '-';">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>


问:
Is statebase framework such as Lift Scalable?
I've watch Harry Heymann, from Foursquare, gave a presentation on Lift to BASE usergroup. He mention something about how Lift being statebase isn't going to scale well in that video.

Is that true? If so why is that? Note: I know very little about state base.

I can't seem to find the google, I'll look for it later. Thank you in advance.

答: I think it's pretty clear that Lift apps scale very well. Foursquare and the UK Guardian are both using Lift.  Both sites are very highly trafficked and neither has had a material Lift-related outage.  Please also see the link that Diego posted.  It provides an in-depth discussion of scaling Lift-powered sites.</p>


问:
Can't move in map view swift
I can't move or zoom the map to other locations. I used this tutorial: https://www.youtube.com/watch?v=qrdIL44T6FQ to show my location in the map. For some reason the map first zooms in very slowly (+- 30 seconds) to my location after opening the app. Then when I want to move around in the map I cant. It stays on my current location.

Here is my code:

import UIKit
import MapKit
import CoreLocation

class FirstViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.locationManager.delegate = self

        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest

        self.locationManager.requestWhenInUseAuthorization()

        self.locationManager.startUpdatingLocation()

        self.mapView.showsUserLocation = true

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let location = locations.last

        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)

        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5 ))

        self.mapView.setRegion(region, animated: true)

        self.locationManager.startUpdatingLocation()

    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Errors: " + error.localizedDescription)
    }

}```

Does anyone know the problem? Thanks!

答:
For those wondering what his mistake was:

He put self.locationManager.startUpdatingLocation() in the locationManager method instead of self.locationManager.stopUpdatingLocation.

Title: Can't move in map view swift

Body:
I can't move or zoom the map to other locations. I used this tutorial: https://www.youtube.com/watch?v=qrdIL44T6FQ to show my location in the map. For some reason the map first zooms in very slowly (+- 30 seconds) to my location after opening the app. Then when I want to move around in the map I cant. It stays on my current location.

Here is my code:

import UIKit
import MapKit
import CoreLocation

class FirstViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.locationManager.delegate = self

        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest

        self.locationManager.requestWhenInUseAuthorization()

        self.locationManager.startUpdatingLocation()

        self.mapView.showsUserLocation = true

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let location = locations.last

        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)

        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5 ))

        self.mapView.setRegion(region, animated: true)

        self.locationManager.startUpdatingLocation()

    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Errors: " + error.localizedDescription)
    }

}

Does anyone know the problem? Thanks!


问:
How to manually set K-means cluster's centers?
I would like to not to predic centers, but to assign each object to an already defined center. How can I?</p>

答:
You can fit your KMeans to the desired cluster centers, and then use this model to predict your data.

```<code>from sklearn.cluster import KMeans
import numpy as np

cluster_centers = np.array([[1, 1], [0, 0]])
data  = [[1, 2], [1, 1], [3, 1], [10, -1]]

kmeans = KMeans(n_clusters=2, init=cluster_centers, n_init=1)
kmeans.fit(cluster_centers)
</code>```

We just fit the model with our two desired center points, making our desired cluster centers the actual centers of the model.

```<code>kmeans.cluster_centers_
# array([[0., 0.],
#        [1., 1.]])
kmeans.predict(data)
# array([1, 1, 1, 1])
</code>```

If we use this model to assign the data, all data points are assigned to cluster 1.

In contrast, if we initiate on our cluster centers and then fit the model to the data, the centers get adjusted and are no longer the ones we initially wanted.

```<code>kmeans_init = KMeans(n_clusters=2, init=cluster_centers, n_init=1)
kmeans_init.fit(data)
kmeans_init.cluster_centers_
# array([[ 1.66666667,  1.33333333],
#        [10.        , -1.        ]])
kmeans_init.predict(data)
# array([0, 0, 0, 1])
</code>```

Now the data is spread over the two clusters.

Note: n_clusters has to match the number of your cluster centers

Body:
You can fit your KMeans to the desired cluster centers, and then use this model to predict your data.

from sklearn.cluster import KMeans
import numpy as np

cluster_centers = np.array([[1, 1], [0, 0]])
data  = [[1, 2], [1, 1], [3, 1], [10, -1]]

kmeans = KMeans(n_clusters=2, init=cluster_centers, n_init=1)
kmeans.fit(cluster_centers)

We just fit the model with our two desired center points, making our desired cluster centers the actual centers of the model.

kmeans.cluster_centers_
# array([[0., 0.],
#        [1., 1.]])
kmeans.predict(data)
# array([1, 1, 1, 1])

If we use this model to assign the data, all data points are assigned to cluster 1.

In contrast, if we initiate on our cluster centers and then fit the model to the data, the centers get adjusted and are no longer the ones we initially wanted.

kmeans_init = KMeans(n_clusters=2, init=cluster_centers, n_init=1)
kmeans_init.fit(data)
kmeans_init.cluster_centers_
# array([[ 1.66666667,  1.33333333],
#        [10.        , -1.        ]])
kmeans_init.predict(data)
# array([0, 0, 0, 1])

Now the data is spread over the two clusters.

Note: n_clusters has to match the number of your cluster centers


问:
ValueError when trying to plot a histogram
Problem Background

I am trying to plot a histogram to see the distribution of Customer Ages in a bin of size 4. I was initially using a different size of bin, but adjusting the bin this way affected the count or the y-axis of the graph.

Using plt.ylim(min, max) was my way to set the y-axis. To specify the max variable, I tried to count the largest value in the bin which was for ages (25<x<=35).

I keep getting a value error when making the count. Even when I convert the series to an integer using .astype(int), it displays another error.

Error Message:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Please, how do I rectify this?

Code Snippet

```<code>freq, bins, patches = plt.hist(bank_churn_df['Customer_Age'],
                               label = 'Ages',
                               bins=4)

plt.ylim(0,bank_churn_df[(bank_churn_df.Customer_Age > 25) & (bank_churn_df.Customer_Age <= 35)].value_counts())

</code>```

答:
Note that ylim expects 2 arguments: bottom and top.
Both should be single values.

As bottom you passed 0, so far OK, it is a single value.

But the top is the result of value_counts(), i.e. it is a pandasonic
Series of values.

All what I wrote above is however only a marginal remark.

I see such a flaw in your code, that value_counts computes how many times
occurs each individual value.
But the top limit of your y axis should be the max of how many values
are in each bin.

So maybe you should:

first compute pd.cut from your source data,

then compute value_counts from them,

and finally take max of these values.

Another try is to generate your histogram without any explicit
call to ylim, relying on default values.

Body:
Problem Background

I am trying to plot a histogram to see the distribution of Customer Ages in a bin of size 4. I was initially using a different size of bin, but adjusting the bin this way affected the count or the y-axis of the graph.

Using plt.ylim(min, max) was my way to set the y-axis. To specify the max variable, I tried to count the largest value in the bin which was for ages (25<x<=35).

I keep getting a value error when making the count. Even when I convert the series to an integer using .astype(int), it displays another error.

Error Message:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Please, how do I rectify this?

Code Snippet

freq, bins, patches = plt.hist(bank_churn_df['Customer_Age'],
                               label = 'Ages',
                               bins=4)

plt.ylim(0,bank_churn_df[(bank_churn_df.Customer_Age > 25) & (bank_churn_df.Customer_Age <= 35)].value_counts())


问:
Don't restart docker container on host reboot. Restart the container only when it crashed due to error
I want to restart the docker container only when container crashed due to error. And don't want to restart the container if host reboots.
Which restart_policy will work for the above case?</p>

答:
Start containers automatically

 on-failure[:max-retries]

Restart the container if it exits due to an error, which manifests as a non-zero exit code. Optionally, limit the number of times the Docker daemon attempts to restart the container using the :max-retries option.

```<code>
docker run -d --restart  on-failure[:max-retries] CONTAINER

</code>```

UPDATE

A Docker host is a physical computer system or virtual machine running Linux. This can be your laptop, server or virtual machine in your data center, or computing resource provided by a cloud provider. The component on the host that does the work of building and running containers is the Docker Daemon.

Keep containers alive during daemon downtime

By default, when the Docker daemon terminates, it shuts down running containers. You can configure the daemon so that containers remain running if the daemon becomes unavailable. This functionality is called live restore. The live restore option helps reduce container downtime due to daemon crashes, planned outages, or upgrades.

Enable live restore

There are two ways to enable the live restore setting to keep containers alive when the daemon becomes unavailable. Only do one of the following.

Add the configuration to the daemon configuration file. On Linux, this defaults to  /etc/docker/daemon.json. On Docker Desktop for Mac or Docker Desktop for Windows, select the Docker icon from the task bar, then click Preferences -> Daemon -> Advanced.

Use the following JSON to enable live-restore.

```<code>    {
      "live-restore": true
    }
</code>```

Restart the Docker daemon. On Linux, you can avoid a restart (and avoid any downtime for your containers) by reloading the Docker daemon. If you use systemd, then use the command systemctl reload docker. Otherwise, send a SIGHUP signal to the dockerd process.

If you prefer, you can start the dockerd process manually with the --live-restore flag. This approach is not recommended because it does not set up the environment that systemd or another process manager would use when starting the Docker process. This can cause unexpected behavior.

Body:
Start containers automatically

 on-failure[:max-retries]

Restart the container if it exits due to an error, which manifests as a non-zero exit code. Optionally, limit the number of times the Docker daemon attempts to restart the container using the :max-retries option.

docker run -d --restart  on-failure[:max-retries] CONTAINER

UPDATE

A Docker host is a physical computer system or virtual machine running Linux. This can be your laptop, server or virtual machine in your data center, or computing resource provided by a cloud provider. The component on the host that does the work of building and running containers is the Docker Daemon.

Keep containers alive during daemon downtime

By default, when the Docker daemon terminates, it shuts down running containers. You can configure the daemon so that containers remain running if the daemon becomes unavailable. This functionality is called live restore. The live restore option helps reduce container downtime due to daemon crashes, planned outages, or upgrades.

Enable live restore

There are two ways to enable the live restore setting to keep containers alive when the daemon becomes unavailable. Only do one of the following.

Add the configuration to the daemon configuration file. On Linux, this defaults to  /etc/docker/daemon.json. On Docker Desktop for Mac or Docker Desktop for Windows, select the Docker icon from the task bar, then click Preferences -> Daemon -> Advanced.

Use the following JSON to enable live-restore.

    {
      "live-restore": true
    }

Restart the Docker daemon. On Linux, you can avoid a restart (and avoid any downtime for your containers) by reloading the Docker daemon. If you use systemd, then use the command systemctl reload docker. Otherwise, send a SIGHUP signal to the dockerd process.

If you prefer, you can start the dockerd process manually with the --live-restore flag. This approach is not recommended because it does not set up the environment that systemd or another process manager would use when starting the Docker process. This can cause unexpected behavior.


问:
How I get values updating/refreshing related input areas in Javascript?
I have a form and when I press the Try button it returns values for the 3rd and 6th input fields of the form according to the values entered in 1,2 and 5.6. Also, the 7th input field combines the 3rd and 6th results.
My question is how can I get the result values from input fields 3 and 6 without clicking the Try It button and also update the input field 7 without refreshing the page?

My code is in JSFiddle UPDATED !!

My Javascript are:

```<code> <script type="text/javascript">
   function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
    if (with_space===true) {
     return string_one+'/'+string_two;
    }
    else {
     return string_one+string_two;
    }
   }
   function join_names() {
    var input_name_first = document.getElementsByName('ht')[0].value;
    var input_name_last = document.getElementsByName('ft')[0].value;
    var input_name_full = document.getElementsByName('htft')[0];
    var var_name_full = concatenate(input_name_first, input_name_last, true);
    input_name_full.value = var_name_full;
   }
  </script>

  <script type="text/javascript">
function myFunctionFt() {
  var home = document.getElementById("home_score").value;
    var away = document.getElementById("away_score").value;
  var results;
  if (home > away) {
    results = "1";
  } else if (home < away) {
    results = "2";
  }  else if (home = away) {
    results = "X";
  }
  document.getElementById("ft").value = results;
}
</script>

  <script type="text/javascript">
function myFunctionHt() {
  var home = document.getElementById("home_ht_score").value;
    var away = document.getElementById("away_ht_score").value;
  var results;
  if (home > away) {
    results = "1";
  } else if (home < away) {
    results = "2";
  }  else if (home = away) {
    results = "X";
  }
  document.getElementById("ht").value = results;
}
</script>
</code>```

答:
I have removed all the previous answers from this answer and added a new answer in place. I have read your last comment and you said that my code was not working for the Home Team HT Score and Away Team HT Score. Well, I had made the logic to behave this way because it makes more sense to put the result in HT Result once both of the teams have played or in other words when we have both of the inputs. In sports, it rarely happens that only one team plays. Right. So outputting the result in HT result based on one of the inputs makes no sense. But if this is what you want, you simply have to change the logic from if (!input_home || !input_away) return; to if (!input_home && !input_away) return; and it will start working the way you want. Basically in the first logic statement with "||" we are saying unless both of the inputs are available don't out into HT result and in the second statement with && we are saying id doesn't matter if one of them is not present, just take whatever is present and output it in HT result. The same thing is happening for FT. You just have to change || to &&.

Here is the final working code:

  //FT and HT Result//
  let name_first = document.getElementById('ht');
    let name_last = document.getElementById('ft');
    let input_name_first = name_first.value;
    let input_name_last = name_last.value;

  //HT Home//
  let home = document.getElementById("home_ht_score");
    let away = document.getElementById("away_ht_score");
  home_ht_score.addEventListener("input", myFunctionHt);
  away_ht_score.addEventListener("input", myFunctionHt);
  let input_away = away.value;
  let input_home = home.value;
  //FT Home//
  let home_ft = document.getElementById("home_score");
    let away_ft = document.getElementById("away_score");
  home_score.addEventListener("input", myFunctionFt);
  away_score.addEventListener("input", myFunctionFt);
  let input_ft_away = away_ft.value;
  let input_ft_home = home_ft.value;

function myFunctionHt() {
  input_away = away.value;
  input_home = home.value;
  input_name_first = name_first.value;
  input_name_last = name_last.value;
    if (!input_home && !input_away) return;
  var results = "";
  if (input_home > input_away) {
    results = "1";
  } else if (input_home < input_away) {
    results = "2";
  }  else if (input_home = input_away) {
    results = "X";
  }
  document.getElementById("ht").value = results;
  join_names();
}

function myFunctionFt() {
  input_ft_away = away_ft.value;
  input_ft_home = home_ft.value;
  input_name_first = name_first.value;
  input_name_last = name_last.value;
    if (!input_ft_home && !input_ft_away) return;
  var results = "";
  if (input_ft_home > input_ft_away) {
    results = "1";
  } else if (input_ft_home < input_ft_away) {
    results = "2";
  }  else if (input_ft_home = input_ft_away) {
    results = "X";
  }
  document.getElementById("ft").value = results;
  join_names();
}

function join_names() {
   if (!input_name_first && !input_name_last) return;
    let input_name_full = document.getElementsByName('htft')[0];
    var var_name_full = concatenate(name_first.value, name_last.value, true);
    input_name_full.value = var_name_full;
   }

 function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
    if (with_space===true) {
     return string_one+'/'+string_two;
    }
    else {
     return string_one+string_two;
    }
   }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <form class="form-group" action="addemp" method="post" onsubmit="return true" onClick="return false">
    <table border="0" cellpadding="1">
      <tbody>
        <tr>
          <td> <label class="form-label" style="color:blue" for="name">Home Team HT Score</label> </td>
          <td> <input id="home_ht_score" name="home_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>

        </tr>
        <tr>
          <td> <label class="form-label" style="color:red" for="name">Away Team HT Score</label> </td>
          <td> <input id="away_ht_score" name="away_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>

        </tr>

        <tr>
          <td><label class="form-label" style="color:green" for="name">HT Result</label> </td>
          <td> <input id="ht" name="ht" type="text" class="form-control mb-3" oninput="join_names();" onpaste="join_names();" style="width: 200px;"></td>

        </tr>

        <tr>
          <td><label class="form-label" style="color:blue" for="name">Home FT Score</label> </td>
          <td> <input id="home_score" name="home_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
        </tr>
        <tr>
          <td><label class="form-label" style="color:red" for="name">Away FT Score</label> </td>
          <td> <input id="away_score" name="away_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
        </tr>

        <tr>
          <td> <label class="form-label" style="color:green" for="name">FT Result</label> </td>
          <td> <input id="ft" name="ft" type="text" class="form-control mb-3" onchange="join_names();" onpaste="join_names();" style="width: 200px;"></td>

        </tr>

        <tr>
          <td><label class="form-label" style="color:green" for="name">HT/FT</label> </td>
          <td> <input name="htft" type="text" class="form-control mb-3" style="width: 200px;"> </td>

        </tr>

        <tr>
          <td> </td>
          <td><button class="btn btn-primary mb-4" type="submit">Save Match Result</button> </td>

        </tr>
      </tbody>

    </table>
  </form>
</body>

</html></code>```

Body:
I have removed all the previous answers from this answer and added a new answer in place. I have read your last comment and you said that my code was not working for the Home Team HT Score and Away Team HT Score. Well, I had made the logic to behave this way because it makes more sense to put the result in HT Result once both of the teams have played or in other words when we have both of the inputs. In sports, it rarely happens that only one team plays. Right. So outputting the result in HT result based on one of the inputs makes no sense. But if this is what you want, you simply have to change the logic from if (!input_home || !input_away) return; to if (!input_home && !input_away) return; and it will start working the way you want. Basically in the first logic statement with "||" we are saying unless both of the inputs are available don't out into HT result and in the second statement with && we are saying id doesn't matter if one of them is not present, just take whatever is present and output it in HT result. The same thing is happening for FT. You just have to change || to &&.

Here is the final working code:

  //FT and HT Result//
  let name_first = document.getElementById('ht');
    let name_last = document.getElementById('ft');
    let input_name_first = name_first.value;
    let input_name_last = name_last.value;

  //HT Home//
  let home = document.getElementById("home_ht_score");
    let away = document.getElementById("away_ht_score");
  home_ht_score.addEventListener("input", myFunctionHt);
  away_ht_score.addEventListener("input", myFunctionHt);
  let input_away = away.value;
  let input_home = home.value;
  //FT Home//
  let home_ft = document.getElementById("home_score");
    let away_ft = document.getElementById("away_score");
  home_score.addEventListener("input", myFunctionFt);
  away_score.addEventListener("input", myFunctionFt);
  let input_ft_away = away_ft.value;
  let input_ft_home = home_ft.value;

function myFunctionHt() {
  input_away = away.value;
  input_home = home.value;
  input_name_first = name_first.value;
  input_name_last = name_last.value;
    if (!input_home && !input_away) return;
  var results = "";
  if (input_home > input_away) {
    results = "1";
  } else if (input_home < input_away) {
    results = "2";
  }  else if (input_home = input_away) {
    results = "X";
  }
  document.getElementById("ht").value = results;
  join_names();
}

function myFunctionFt() {
  input_ft_away = away_ft.value;
  input_ft_home = home_ft.value;
  input_name_first = name_first.value;
  input_name_last = name_last.value;
    if (!input_ft_home && !input_ft_away) return;
  var results = "";
  if (input_ft_home > input_ft_away) {
    results = "1";
  } else if (input_ft_home < input_ft_away) {
    results = "2";
  }  else if (input_ft_home = input_ft_away) {
    results = "X";
  }
  document.getElementById("ft").value = results;
  join_names();
}

function join_names() {
   if (!input_name_first && !input_name_last) return;
    let input_name_full = document.getElementsByName('htft')[0];
    var var_name_full = concatenate(name_first.value, name_last.value, true);
    input_name_full.value = var_name_full;
   }

 function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
    if (with_space===true) {
     return string_one+'/'+string_two;
    }
    else {
     return string_one+string_two;
    }
   }

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <form class="form-group" action="addemp" method="post" onsubmit="return true" onClick="return false">
    <table border="0" cellpadding="1">
      <tbody>
        <tr>
          <td> <label class="form-label" style="color:blue" for="name">Home Team HT Score</label> </td>
          <td> <input id="home_ht_score" name="home_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>

        </tr>
        <tr>
          <td> <label class="form-label" style="color:red" for="name">Away Team HT Score</label> </td>
          <td> <input id="away_ht_score" name="away_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>

        </tr>

        <tr>
          <td><label class="form-label" style="color:green" for="name">HT Result</label> </td>
          <td> <input id="ht" name="ht" type="text" class="form-control mb-3" oninput="join_names();" onpaste="join_names();" style="width: 200px;"></td>

        </tr>

        <tr>
          <td><label class="form-label" style="color:blue" for="name">Home FT Score</label> </td>
          <td> <input id="home_score" name="home_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
        </tr>
        <tr>
          <td><label class="form-label" style="color:red" for="name">Away FT Score</label> </td>
          <td> <input id="away_score" name="away_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
        </tr>

        <tr>
          <td> <label class="form-label" style="color:green" for="name">FT Result</label> </td>
          <td> <input id="ft" name="ft" type="text" class="form-control mb-3" onchange="join_names();" onpaste="join_names();" style="width: 200px;"></td>

        </tr>

        <tr>
          <td><label class="form-label" style="color:green" for="name">HT/FT</label> </td>
          <td> <input name="htft" type="text" class="form-control mb-3" style="width: 200px;"> </td>

        </tr>

        <tr>
          <td> </td>
          <td><button class="btn btn-primary mb-4" type="submit">Save Match Result</button> </td>

        </tr>
      </tbody>

    </table>
  </form>
</body>

</html>


问:
GitHub gh-pages to work with the app domain name?
I deployed a react app on gh-pages. The problem is that the URL, like https://username.io/react-app-name doesn't work. I'm running into a problem, because the app doesn't have a route to "react-app-name"...it has to be just "/" or "/users" etc. So by this kind of error loads a "not found" page. The not found has a go back home button, which takes me to the homepage "/", and from there the app works. How can I resolve this problem?
Sorry for my bad English, hopefully you get it what I want to ask.</p>

答:
If I understand your question correctly, you might have missed setting the homepage property properly in your package.json file.

Here is how to do so:

Open your package.json file.

At the top level, give the homepage of your app in this format: https://<gitname>.github.io/<repo-name>.

Here is an example:

```<code>{
  "name": "react-app",
  "version": "0.1.0",
  "homepage": "https://gitname.github.io/react-app-name",
  ....
</code>```

Your React app will be deployed at /react-app-name.

To learn more about how to deploy a React app to GitHub Pages, read this.

If that was indeed done correctly, you might want to look into specifying the basename prop in BrowserRouter that provides a base URL path for all the locations in the application (as suggested in ivanosevitch's answer).

If none of the above solves the issue, please elaborate on your problem so it is easier to understand where it is stemming from.

Body:
If I understand your question correctly, you might have missed setting the homepage property properly in your package.json file.

Here is how to do so:

Open your package.json file.

At the top level, give the homepage of your app in this format: https://<gitname>.github.io/<repo-name>.

Here is an example:

{
  "name": "react-app",
  "version": "0.1.0",
  "homepage": "https://gitname.github.io/react-app-name",
  ....

Your React app will be deployed at /react-app-name.

To learn more about how to deploy a React app to GitHub Pages, read this.

If that was indeed done correctly, you might want to look into specifying the basename prop in BrowserRouter that provides a base URL path for all the locations in the application (as suggested in ivanosevitch's answer).

If none of the above solves the issue, please elaborate on your problem so it is easier to understand where it is stemming from.


问:
Ruby: install gem if user does not have it installed
I have a ruby script that I want to send to a couple of coworkers.  Instead of telling them to install a few required gems, is there a safe way to have ruby install them if not found?

For example, a user doesn't have the yui-compressor gem.  Instead of the terminal displaying an error when they run ruby example.rb it would automatically run gem install -r yui-compressor for them.  Is there a way to handle this?

答: You could use a tool like bundler: http://gembundler.com/</p>


问:
Can Logo and Name of the App Change After Login? Swift
Let's say that the logo of the app is simple W and the name of the app is My Life.

After login with a business mail I want to change the name of the app and the logo according to the business mail.

Is it possible and if yes how?

答:
You can change an app icon if the app already contains the desired icon (see https://www.hackingwithswift.com/example-code/uikit/how-to-change-your-app-icon-dynamically-with-setalternateiconname); you cannot, say, download an icon and switch to it from within the app.

You cannot change an app display name at all. It is set through the info.plist. It can be localized (so that it changes if the user changes languages) but not altered.


问:
Why does Sequelize is inverting the INSERT query it produces by calling the custom N:N method?
Good evening.

I have a database with the following N:N association:

-> BlogPost.belogsToMany(Category through: PostsCategories)

-> Category.belongsToMany(BlogPost through: PostsCategories)

PostsCategories being the junction table's model.

On the process of inserting one BlogPost to the database, I have to catalog in which categories does it fall under on the junction table. So following some examples on the documentation I came up with:

```<code>const blogPost = await BlogPost.create({ title, content, userId });
await blogPost.addCategories(categoriesList);
</code>```

So far so good, but there was an error. Basically Sequelize is inverting the order on the columns/values when writing the query. If I add

```<code>blogPost: { id: 3, categories: [1, 2] }
</code>```

it produces this query:

```<code>"'INSERT INTO `PostsCategories` (`categoryId`,`postId`) VALUES (3,1),(3,2);'"
</code>```

It's inverted and I've tried a gazillion things and it doesn't work. :(

Any thoughts on this?

Thanks!

EDIT: MY MODELS

```<code>module.exports = (sequelize, DataTypes) => {
  const Category = sequelize.define('Category', {
    name: DataTypes.STRING,
  },
  { tableName: 'Categories', timestamps: false });

  Category.associate = (models) => {
    const { BlogPost, PostsCategories } = models;

    Category.belongsToMany(
      BlogPost, { through: PostsCategories, foreignKey: 'postId', as: 'blogPosts' },
    );
  };

  return Category;
};

module.exports = (sequelize, DataTypes) => {
  const BlogPost = sequelize.define('BlogPost', {
    title: DataTypes.STRING,
    content: DataTypes.STRING,
    userId: DataTypes.INTEGER,
  },
  { tableName: 'BlogPosts', timestamps: true, createdAt: 'published', updatedAt: 'updated' });

  BlogPost.associate = (models) => {
    const { User, PostsCategories, Category } = models;

    BlogPost.belongsToMany(
      Category, { through: PostsCategories, foreignKey: 'categoryId', as: 'categories' },
    );

    BlogPost.belongsTo(User, { foreignKey: 'userId', as: 'user' });
  };

  return BlogPost;
};

module.exports = (sequelize, _DataTypes) => {
  const PostsCategories = sequelize.define('PostsCategories',
  {},
  { timestamps: false, tableName: 'PostsCategories' });

  return PostsCategories;
};
</code>```

答:
I got my answer. Lol.

My association declarations were faulty.

```<code>    BlogPost.belongsToMany(
      Category, { through: PostsCategories, foreignKey: 'categoryId', as: 'categories' },
    );

</code>```

Actually the foreignKey is related to the BlogPost on the junction table.

I also inverted my declaration to being able to "read" it better.

```<code>    BlogPost.belongsToMany(
      Category, { as: 'categories', through: PostsCategories, foreignKey: 'postId' },
    );
</code>```

BlogPost belongsToMany Category

if I query a BlogPost and want it with every category it'll return as 'categories'

the association is established through PostsCategories

the way the BlogPost associate with PostsCategories is with the foreignKey 'postId'

Body:
Good evening.

I have a database with the following N:N association:

-> BlogPost.belogsToMany(Category through: PostsCategories)

-> Category.belongsToMany(BlogPost through: PostsCategories)

PostsCategories being the junction table's model.

On the process of inserting one BlogPost to the database, I have to catalog in which categories does it fall under on the junction table. So following some examples on the documentation I came up with:

const blogPost = await BlogPost.create({ title, content, userId });
await blogPost.addCategories(categoriesList);

So far so good, but there was an error. Basically Sequelize is inverting the order on the columns/values when writing the query. If I add

blogPost: { id: 3, categories: [1, 2] }

it produces this query:

"'INSERT INTO `PostsCategories` (`categoryId`,`postId`) VALUES (3,1),(3,2);'"

It's inverted and I've tried a gazillion things and it doesn't work. :(

Any thoughts on this?

Thanks!

EDIT: MY MODELS

module.exports = (sequelize, DataTypes) => {
  const Category = sequelize.define('Category', {
    name: DataTypes.STRING,
  },
  { tableName: 'Categories', timestamps: false });

  Category.associate = (models) => {
    const { BlogPost, PostsCategories } = models;

    Category.belongsToMany(
      BlogPost, { through: PostsCategories, foreignKey: 'postId', as: 'blogPosts' },
    );
  };

  return Category;
};

module.exports = (sequelize, DataTypes) => {
  const BlogPost = sequelize.define('BlogPost', {
    title: DataTypes.STRING,
    content: DataTypes.STRING,
    userId: DataTypes.INTEGER,
  },
  { tableName: 'BlogPosts', timestamps: true, createdAt: 'published', updatedAt: 'updated' });

  BlogPost.associate = (models) => {
    const { User, PostsCategories, Category } = models;

    BlogPost.belongsToMany(
      Category, { through: PostsCategories, foreignKey: 'categoryId', as: 'categories' },
    );

    BlogPost.belongsTo(User, { foreignKey: 'userId', as: 'user' });
  };

  return BlogPost;
};

module.exports = (sequelize, _DataTypes) => {
  const PostsCategories = sequelize.define('PostsCategories',
  {},
  { timestamps: false, tableName: 'PostsCategories' });

  return PostsCategories;
};

Body:
I got my answer. Lol.

My association declarations were faulty.

    BlogPost.belongsToMany(
      Category, { through: PostsCategories, foreignKey: 'categoryId', as: 'categories' },
    );

Actually the foreignKey is related to the BlogPost on the junction table.

I also inverted my declaration to being able to "read" it better.

    BlogPost.belongsToMany(
      Category, { as: 'categories', through: PostsCategories, foreignKey: 'postId' },
    );

BlogPost belongsToMany Category

if I query a BlogPost and want it with every category it'll return as 'categories'

the association is established through PostsCategories

the way the BlogPost associate with PostsCategories is with the foreignKey 'postId'


问:
Conventional practice for signal handling/child processes
EDIT: If managing child processes for a shell script is really purely a matter of "opinion"......no wonder there are so many terrible shell scripts. Thanks for continuing that.

I'm having trouble understanding how SIGTERM is conventionally handled with relation to child processes in Linux.

I am writing a command line utility in Bash.

It looks like

```<code>command1
command2
command3
</code>```

Very simple, right?

However, if my program is sent SIGTERM signal, the Bash script will end but the current child process (e.g. command2) will continue.

But with some more code, I can write my program like this

```<code>trap 'jobs -p | xargs -r kill' TERM

command1 &
wait
command2 &
wait
command3 &
wait
</code>```

That will propogate SIGTERM to the currently running child process. I haven't often seen Bash scripts written like that, but that's what it would take.

Should I:

Write my program in the second style each time I create a child process?

Or expect users to launch my program in a process group if they want to send SIGTERM?

What's the best practice/conventions for process management responsibilities with respect to SIGTERM for children?

答:
tl;dr

The first way.

If a process starts a child process and waits for it to finish (the example), nothing special is necessary.

If a process starts a child process and may prematurely terminate it, it should start that child in a new process group and send signals to the group.

Details

Oddly for how often this applies (like, every shell script), I can't find a good answer about convention/best practice.

Some deduction:

Creating and signaling process groups are very common. In particular, interactive shells do this. So (unless it takes extra steps to prevent it) a processes' children can receive SIGINT signals at any time, in very normal circumstances.

In the interest of supporting as few paradigms as possible, it seems to make sense to rely on that always.

That means the first style is okay, and the burden of process management is placed on processes that deliberately terminate their children during regular operation (which is relatively less common).

See also "Case study: timeout" below for further evidence.

How to do it

While the perspective of the question was from the requirements of a vanilla callee program, this answer prompts the question: how does one start a process in a new process group (in the non-vanilla case that one wishes to prematurely interrupt the process)?

This is easy in some languages and difficult in others. I've created a utility  run-pgrp to assist in the latter case.

#!/usr/bin/env python3
# Run the command in a new process group, and forward signals.
import os
import signal
import sys

pid = os.fork()
if not pid:
    os.setpgid(0, 0)
    os.execvp(sys.argv[1], sys.argv[1:])

def receiveSignal(sig, frame):
    os.killpg(pid, sig)
signal.signal(signal.SIGINT, receiveSignal)
signal.signal(signal.SIGTERM, receiveSignal)

_, status = os.waitpid(-1, 0)
sys.exit(status)
```
<p>The caller can use that to wrap the process that it prematurely terminate.</p>
<p>Node.js example:</p>
<pre class="lang-js prettyprint-override"><code>const childProcess = require("child_process");
(async () => {
  const process = childProcess.spawn(
    "run-pgrp",
    ["bash", "-c", "echo start; sleep 600; echo done"],
    { stdio: "inherit" }
  );
  /* leaves orphaned process
  const process = childProcess.spawn(
    "bash",
    ["-c", "echo start; sleep 600; echo done"],
    { stdio: "inherit" }
  );
  */
  await new Promise(res => setTimeout(res, /* 1s */ 1000));
  process.kill();
  if (process.exitCode == null) {
    await new Promise(res => process.on("exit", res));
  }
})();
</code>```

At the end of this program, the sleep process is terminated. If the command invoked directly without run-pgrp, the sleep process continues to run.

Case study: timeout

The GNU timeout utility is a program that may terminate its child process.

Notably, it runs the child in a new process group. This supports the conclusion that potential interruptions should be preceded by creating a new process group.

Interestingly, however, timeout puts itself in the process group as well, to avoid complexities around forwarding signals, but causing some strange behavior. https://unix.stackexchange.com/a/57692/56781

For example, in an interactive shell, run

```<code>bash -c "echo start; timeout 600 sleep 600; echo done"
</code>```

Try to interrupt this (Ctrl+C). It doesn't respond, because timeout never gets the signal!

In contrast, my run-pgrp utility keeps itself in the original process group and forwards SIGINT/SIGTERM to the child group.

Body:
EDIT: If managing child processes for a shell script is really purely a matter of "opinion"......no wonder there are so many terrible shell scripts. Thanks for continuing that.

I'm having trouble understanding how SIGTERM is conventionally handled with relation to child processes in Linux.

I am writing a command line utility in Bash.

It looks like

command1
command2
command3

Very simple, right?

However, if my program is sent SIGTERM signal, the Bash script will end but the current child process (e.g. command2) will continue.

But with some more code, I can write my program like this

trap 'jobs -p | xargs -r kill' TERM

command1 &
wait
command2 &
wait
command3 &
wait

That will propogate SIGTERM to the currently running child process. I haven't often seen Bash scripts written like that, but that's what it would take.

Should I:

Write my program in the second style each time I create a child process?

Or expect users to launch my program in a process group if they want to send SIGTERM?

What's the best practice/conventions for process management responsibilities with respect to SIGTERM for children?

Body:
tl;dr

The first way.

If a process starts a child process and waits for it to finish (the example), nothing special is necessary.

If a process starts a child process and may prematurely terminate it, it should start that child in a new process group and send signals to the group.

Details

Oddly for how often this applies (like, every shell script), I can't find a good answer about convention/best practice.

Some deduction:

Creating and signaling process groups are very common. In particular, interactive shells do this. So (unless it takes extra steps to prevent it) a processes' children can receive SIGINT signals at any time, in very normal circumstances.

In the interest of supporting as few paradigms as possible, it seems to make sense to rely on that always.

That means the first style is okay, and the burden of process management is placed on processes that deliberately terminate their children during regular operation (which is relatively less common).

See also "Case study: timeout" below for further evidence.

How to do it

While the perspective of the question was from the requirements of a vanilla callee program, this answer prompts the question: how does one start a process in a new process group (in the non-vanilla case that one wishes to prematurely interrupt the process)?

This is easy in some languages and difficult in others. I've created a utility  run-pgrp to assist in the latter case.

#!/usr/bin/env python3
# Run the command in a new process group, and forward signals.
import os
import signal
import sys

pid = os.fork()
if not pid:
    os.setpgid(0, 0)
    os.execvp(sys.argv[1], sys.argv[1:])

def receiveSignal(sig, frame):
    os.killpg(pid, sig)
signal.signal(signal.SIGINT, receiveSignal)
signal.signal(signal.SIGTERM, receiveSignal)

_, status = os.waitpid(-1, 0)
sys.exit(status)

The caller can use that to wrap the process that it prematurely terminate.

Node.js example:

const childProcess = require("child_process");
(async () => {
  const process = childProcess.spawn(
    "run-pgrp",
    ["bash", "-c", "echo start; sleep 600; echo done"],
    { stdio: "inherit" }
  );
  /* leaves orphaned process
  const process = childProcess.spawn(
    "bash",
    ["-c", "echo start; sleep 600; echo done"],
    { stdio: "inherit" }
  );
  */
  await new Promise(res => setTimeout(res, /* 1s */ 1000));
  process.kill();
  if (process.exitCode == null) {
    await new Promise(res => process.on("exit", res));
  }
})();

At the end of this program, the sleep process is terminated. If the command invoked directly without run-pgrp, the sleep process continues to run.

Case study: timeout

The GNU timeout utility is a program that may terminate its child process.

Notably, it runs the child in a new process group. This supports the conclusion that potential interruptions should be preceded by creating a new process group.

Interestingly, however, timeout puts itself in the process group as well, to avoid complexities around forwarding signals, but causing some strange behavior. https://unix.stackexchange.com/a/57692/56781

For example, in an interactive shell, run

bash -c "echo start; timeout 600 sleep 600; echo done"

Try to interrupt this (Ctrl+C). It doesn't respond, because timeout never gets the signal!

In contrast, my run-pgrp utility keeps itself in the original process group and forwards SIGINT/SIGTERM to the child group.


问:
Why is my for loop not transferring all list items to my dictionary (PYTHON)
I have 3 lists: year, list1, list2.
I want to create a dictionary with {year1: list_item1, year2: list_item2, etc..}
My code:

```<code>list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]

years = []
for i in range(2018,2024):
    years.append(i)

predicted_change = {}
n = 0
while n < 6:
    for i in years:
        for t in list1:
            for e in list2:
                predicted_change[i] = t
                n += 1
    break

predicted_change
</code>```

Results: {2018: 5, 2019: 5, 2020: 5, 2021: 5, 2022: 5, 2023: 5}

Any ideas? I was looking for {2018: 1, 2019: 2, 2020: 3, etc...}
Thanks!

答:
```<code>predicted_change = {}

for counter, i in enumerate(range(2018, 2024), start=1):
    predicted_change[i] = i
    predicted_change[i] = counter

print(predicted_change)

</code>```

output

```<code>{2018: 1, 2019: 2, 2020: 3, 2021: 4, 2022: 5, 2023: 6}
</code>```

Use enumerate() to get a counter in a loop

```<code>languages = ['Python', 'C', 'C++', 'C#', 'Java']
</code>```

Bad way

```<code>i = 0 #counter variable
for language in languages:
    print(i, language)
    i+=1
</code>```

or

```<code>for i in range(len(languages)):
    print(i, languages[i])
</code>```

Good Way

```<code>for i, language in enumerate(languages):
    print(i, language)
</code>```

Body:
I have 3 lists: year, list1, list2.
I want to create a dictionary with {year1: list_item1, year2: list_item2, etc..}
My code:

list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]

years = []
for i in range(2018,2024):
    years.append(i)

predicted_change = {}
n = 0
while n < 6:
    for i in years:
        for t in list1:
            for e in list2:
                predicted_change[i] = t
                n += 1
    break

predicted_change

Results: {2018: 5, 2019: 5, 2020: 5, 2021: 5, 2022: 5, 2023: 5}

Any ideas? I was looking for {2018: 1, 2019: 2, 2020: 3, etc...}
Thanks!

Body:
predicted_change = {}

for counter, i in enumerate(range(2018, 2024), start=1):
    predicted_change[i] = i
    predicted_change[i] = counter

print(predicted_change)

output

{2018: 1, 2019: 2, 2020: 3, 2021: 4, 2022: 5, 2023: 6}

Use enumerate() to get a counter in a loop

languages = ['Python', 'C', 'C++', 'C#', 'Java']

Bad way

i = 0 #counter variable
for language in languages:
    print(i, language)
    i+=1

or

for i in range(len(languages)):
    print(i, languages[i])

Good Way

for i, language in enumerate(languages):
    print(i, language)


问:
Python sudoku backtracking
I was trying out the backtracking algorithm with an easy example (sudoku). I first tried another approach where more possibilities are canceled, but after I got the same error I switched to an easier solution.

look for the first unsolved spot

fill in every number between 1 and 9 and backtrack the new field if it is valid

When I run it and output the non-valid fields I can see that when the algorithm goes out of a recursion call the spot that was in that recursion call is still a 9 (so the algorithm couldn't find anything for that spot)

e.g. the first two lines look something like this (it's trying to solve an empty field):

```<code>[1, 2, 3, 4, 6, 9, 9, 9, 9]

[9, 9, 9, 9, 9, 9, 9, 0, 0]
</code>```

I thought it was a reference error and inserted
[e for e in field]
in the backtracking call so that the old field doesn't get altered although that didn't seem to help.

Here is my code:

```<code>
    for i in range(9):
        a = [field[i][j] for j in range(9) if field[i][j] != 0]
        if len(a) != len(set(a)):
            return False

    for i in range(9):
        a = [field[j][i] for j in range(9) if field[j][i] != 0]
        if len(a) != len(set(a)):
            return False

    for x in range(3):
        for y in range(3):
            a = []
            for addX in range(3):
                for addY in range(3):
                    spot = field[x * 3 + addX][y * 3 + addY]
                    if spot != 0:
                        a.append(spot)
            if len(a) != len(set(a)):
                return False

    return True

def findEmpty(field):

    for i in range(9):
        for j in range(9):
            if field[i][j] == 0:
                return i, j

def backtracking(field):

    find = findEmpty(field)
    if not find:
        return True, field
    else:
        x, y = find

    for i in range(1, 10):
        print(f"Trying {i} at {x} {y}")
        field[x][y] = i
        if isValid(field):
            s = backtracking([e for e in field])
            if s[0]:
                return s
        else:
            print("Not valid")
            for row in field:
                print(row)

    return False, None

field = [[0, 0, 0, 0, 1, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0]]

solution = backtracking(field)
if solution[0]:
    print("There was a solution. The field is:")
    for row in solution[1]:
        print(row)
else:
    print("No solution was found")
</code>```

答:
1- Create rows, cols, and boxes (3x3 units) array of dictionaries to store which indices of each row, col, and boxes have numbers.

2- Take a screenshot of the board. Run a for-loop and mark which points include numbers.

3- Call the recursive backtrack function.

4- Always in recursive functions define the base case to exit out of the recursion.

5- Start a for-loop to see which coordinate is ".". If you see ".", apply steps:[6,7,8,9]

6- Now we need to insert a valid number here. A valid number is a number that does not exist in the current row, col, and box.

7- If you find a valid number, insert it into the board and update rows, cols, and boxes.

8- After we inserted the valid point, we call backtrack function for the next ".".

9- When calling the backtrack, decide at which point you are. If you are in the last column, your next backtrack function will start from the next row and column 0. But if you are in the middle of row, you just increase the column parameter for next backtrack function.

10- If in step 5 your value is not ".", that means there is already a valid number here so call next backtracking depending on where position is.  If you are in the last column, your next backtrack function will start from the next row and column 0. But if you are in the middle of row, you just increase the column parameter for next backtrack function.

```<code>class Solution:
    def solveSudoku(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        n=len(board)
        # create state variables,keep track of rows, cols and boxes
        rows=[{} for _ in range(n)]
        cols=[{} for _ in range(n)]
        boxes=[{} for _ in range(n)]
       # get the initial state of the grid
        for r in range(n):
            for c in range(n):
                if board[r][c]!='.':
                    val=board[r][c]
                    box_id=self.get_box_id(r,c)
                    boxes[box_id][val]=True
                    rows[r][val]=True
                    cols[c][val]=True
        # this backtracking just tells if shoul move to the next cell or not
        self.backtrack(board,boxes,rows,cols,0,0)

    def backtrack(self,board,boxes,rows,cols,r,c):
        # base case. If I hit the last row or col, means all digits were correct so far
        if r>=len(board) or c>=len(board[0]):
            return True
        # situation when cell is empty, fill it with correct value
        if board[r][c]==".":
            for num in range(1,10):
                box_id=self.get_box_id(r,c)
                box=boxes[box_id]
                row=rows[r]
                col=cols[c]
                str_num=str(num)
                # check rows, cols and boxes make sure str_num is not used before
                if self.is_valid(box,col,row,str_num):
                    board[r][c]=str_num
                    boxes[box_id][str_num]=True
                    cols[c][str_num]=True
                    rows[r][str_num]=True
                    # if I am the last col and I placed the correct val, move to next row. So first col of the next row
                    if c==len(board)-1:
                        if self.backtrack(board,boxes,rows,cols,r+1,0):
                            return True
                    # if I am in col between 0-8, move to the col+1, in the same row
                    else:
                        if self.backtrack(board,boxes,rows,cols,r,c+1):
                            return True
                    # If I got a wrong value, then backtrack. So clear the state that you mutated
                    del box[str_num]
                    del row[str_num]
                    del col[str_num]
                    board[r][c]="."
       # if cell is not empty just call the next backtracking
        else:
            if c==len(board)-1:
                if self.backtrack(board,boxes,rows,cols,r+1,0):
                    return True
            else:
                if self.backtrack(board,boxes,rows,cols,r,c+1):
                    return True
        return False

    def is_valid(self,box,row,col,num):
        if num in box or num in row or num in col:
            return False
        else:
            return True

    # a helper to get the id of the 3x3 sub grid, given row and column
    def get_box_id(self,r,c):
        row=(r//3)*3
        col=c//3
        return row+col
</code>```

Title: Python sudoku backtracking

Body:
I was trying out the backtracking algorithm with an easy example (sudoku). I first tried another approach where more possibilities are canceled, but after I got the same error I switched to an easier solution.

look for the first unsolved spot

fill in every number between 1 and 9 and backtrack the new field if it is valid

When I run it and output the non-valid fields I can see that when the algorithm goes out of a recursion call the spot that was in that recursion call is still a 9 (so the algorithm couldn't find anything for that spot)

e.g. the first two lines look something like this (it's trying to solve an empty field):

[1, 2, 3, 4, 6, 9, 9, 9, 9]

[9, 9, 9, 9, 9, 9, 9, 0, 0]

I thought it was a reference error and inserted
[e for e in field]
in the backtracking call so that the old field doesn't get altered although that didn't seem to help.

Here is my code:

    for i in range(9):
        a = [field[i][j] for j in range(9) if field[i][j] != 0]
        if len(a) != len(set(a)):
            return False

    for i in range(9):
        a = [field[j][i] for j in range(9) if field[j][i] != 0]
        if len(a) != len(set(a)):
            return False

    for x in range(3):
        for y in range(3):
            a = []
            for addX in range(3):
                for addY in range(3):
                    spot = field[x * 3 + addX][y * 3 + addY]
                    if spot != 0:
                        a.append(spot)
            if len(a) != len(set(a)):
                return False

    return True

def findEmpty(field):

    for i in range(9):
        for j in range(9):
            if field[i][j] == 0:
                return i, j

def backtracking(field):

    find = findEmpty(field)
    if not find:
        return True, field
    else:
        x, y = find

    for i in range(1, 10):
        print(f"Trying {i} at {x} {y}")
        field[x][y] = i
        if isValid(field):
            s = backtracking([e for e in field])
            if s[0]:
                return s
        else:
            print("Not valid")
            for row in field:
                print(row)

    return False, None

field = [[0, 0, 0, 0, 1, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0]]

solution = backtracking(field)
if solution[0]:
    print("There was a solution. The field is:")
    for row in solution[1]:
        print(row)
else:
    print("No solution was found")

Body:
1- Create rows, cols, and boxes (3x3 units) array of dictionaries to store which indices of each row, col, and boxes have numbers.

2- Take a screenshot of the board. Run a for-loop and mark which points include numbers.

3- Call the recursive backtrack function.

4- Always in recursive functions define the base case to exit out of the recursion.

5- Start a for-loop to see which coordinate is ".". If you see ".", apply steps:[6,7,8,9]

6- Now we need to insert a valid number here. A valid number is a number that does not exist in the current row, col, and box.

7- If you find a valid number, insert it into the board and update rows, cols, and boxes.

8- After we inserted the valid point, we call backtrack function for the next ".".

9- When calling the backtrack, decide at which point you are. If you are in the last column, your next backtrack function will start from the next row and column 0. But if you are in the middle of row, you just increase the column parameter for next backtrack function.

10- If in step 5 your value is not ".", that means there is already a valid number here so call next backtracking depending on where position is.  If you are in the last column, your next backtrack function will start from the next row and column 0. But if you are in the middle of row, you just increase the column parameter for next backtrack function.

class Solution:
    def solveSudoku(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        n=len(board)
        # create state variables,keep track of rows, cols and boxes
        rows=[{} for _ in range(n)]
        cols=[{} for _ in range(n)]
        boxes=[{} for _ in range(n)]
       # get the initial state of the grid
        for r in range(n):
            for c in range(n):
                if board[r][c]!='.':
                    val=board[r][c]
                    box_id=self.get_box_id(r,c)
                    boxes[box_id][val]=True
                    rows[r][val]=True
                    cols[c][val]=True
        # this backtracking just tells if shoul move to the next cell or not
        self.backtrack(board,boxes,rows,cols,0,0)

    def backtrack(self,board,boxes,rows,cols,r,c):
        # base case. If I hit the last row or col, means all digits were correct so far
        if r>=len(board) or c>=len(board[0]):
            return True
        # situation when cell is empty, fill it with correct value
        if board[r][c]==".":
            for num in range(1,10):
                box_id=self.get_box_id(r,c)
                box=boxes[box_id]
                row=rows[r]
                col=cols[c]
                str_num=str(num)
                # check rows, cols and boxes make sure str_num is not used before
                if self.is_valid(box,col,row,str_num):
                    board[r][c]=str_num
                    boxes[box_id][str_num]=True
                    cols[c][str_num]=True
                    rows[r][str_num]=True
                    # if I am the last col and I placed the correct val, move to next row. So first col of the next row
                    if c==len(board)-1:
                        if self.backtrack(board,boxes,rows,cols,r+1,0):
                            return True
                    # if I am in col between 0-8, move to the col+1, in the same row
                    else:
                        if self.backtrack(board,boxes,rows,cols,r,c+1):
                            return True
                    # If I got a wrong value, then backtrack. So clear the state that you mutated
                    del box[str_num]
                    del row[str_num]
                    del col[str_num]
                    board[r][c]="."
       # if cell is not empty just call the next backtracking
        else:
            if c==len(board)-1:
                if self.backtrack(board,boxes,rows,cols,r+1,0):
                    return True
            else:
                if self.backtrack(board,boxes,rows,cols,r,c+1):
                    return True
        return False

    def is_valid(self,box,row,col,num):
        if num in box or num in row or num in col:
            return False
        else:
            return True

    # a helper to get the id of the 3x3 sub grid, given row and column
    def get_box_id(self,r,c):
        row=(r//3)*3
        col=c//3
        return row+col