问:
How to use the useSound hook with multiple audio files
Hi I'm trying to play a different mp3 sound on hover and then stop the sound when the mouse leaves. I installed the use-sound library but I can't figure out how to use it with more than one audio file.

If I rename the play function into playAudio1 for example I can make useSound play the right audio file, but I can't figure out how to stop the correct audio file. I was thinking is there a way to assign the "stop" function in each hook to a different variable name, so I can reference it below in the onMouseLeave event.

The code below gives me an error because I have two identical "stop" functions.

```<code>import React, { useState} from "react";
import Audio1 from "../public/mp3/audio1.mp3";
import Audio2 from "../public/mp3/audio2.mp3";
import useSound from "use-sound";

function Home() {
   const [hoverAudio1, setHoverAudio1] = useState(false);
   const [hoverAudio2, setHoverAudio2] = useState(false);

   const [playAudio1, { stop }] = useSound(Audio1, {
    volume: 0.5,
   });
   const [playAudio2, { stop }] = useSound(Audio2, {
    volume: 0.5,
   });

   return (
      <div
          onMouseEnter={() => {
            setHoverAudio1(true);
            playAudio1();
          }}
          onMouseLeave={() => {
            setHoverAudio1(false);
            stop();
          }}
        >
      </div>
      <div
          onMouseEnter={() => {
            setHoverAudio2(true);
            playAudio2();
          }}
          onMouseLeave={() => {
            setHoverAudio2(false);
            stop();
          }}
        >
      </div>
    )}
</code>```

答:
You can rename destructured keys:</p>
```<code>const [playAudio1, { stop: stopAudio1 }] = useSound(Audio1, {
  volume: 0.5,
});

const [playAudio2, { stop: stopAudio2 }] = useSound(Audio2, {
  volume: 0.5,
});

return (
    <div
        onMouseEnter={() => {
            setHoverAudio1(true);
            playAudio1();
        }}
        onMouseLeave={() => {
            setHoverAudio1(false);
            stopAudio1();
        }}
    ></div>
    <div
        onMouseEnter={() => {
            setHoverAudio2(true);
            playAudio2();
        }}
        onMouseLeave={() => {
            setHoverAudio2(false);
            stopAudio2();
        }}
    ></div>
);
</code>```

Body:
Hi I'm trying to play a different mp3 sound on hover and then stop the sound when the mouse leaves. I installed the use-sound library but I can't figure out how to use it with more than one audio file.

If I rename the play function into playAudio1 for example I can make useSound play the right audio file, but I can't figure out how to stop the correct audio file. I was thinking is there a way to assign the "stop" function in each hook to a different variable name, so I can reference it below in the onMouseLeave event.

The code below gives me an error because I have two identical "stop" functions.

import React, { useState} from "react";
import Audio1 from "../public/mp3/audio1.mp3";
import Audio2 from "../public/mp3/audio2.mp3";
import useSound from "use-sound";

function Home() {
   const [hoverAudio1, setHoverAudio1] = useState(false);
   const [hoverAudio2, setHoverAudio2] = useState(false);

   const [playAudio1, { stop }] = useSound(Audio1, {
    volume: 0.5,
   });
   const [playAudio2, { stop }] = useSound(Audio2, {
    volume: 0.5,
   });

   return (

 {
            setHoverAudio1(true);
            playAudio1();
          }}
          onMouseLeave={() => {
            setHoverAudio1(false);
            stop();
          }}
        >

 {
            setHoverAudio2(true);
            playAudio2();
          }}
          onMouseLeave={() => {
            setHoverAudio2(false);
            stop();
          }}
        >

    )}

Body:
You can rename destructured keys:

const [playAudio1, { stop: stopAudio1 }] = useSound(Audio1, {
  volume: 0.5,
});

const [playAudio2, { stop: stopAudio2 }] = useSound(Audio2, {
  volume: 0.5,
});

return (
    <div
        onMouseEnter={() => {
            setHoverAudio1(true);
            playAudio1();
        }}
        onMouseLeave={() => {
            setHoverAudio1(false);
            stopAudio1();
        }}
    ></div>
    <div
        onMouseEnter={() => {
            setHoverAudio2(true);
            playAudio2();
        }}
        onMouseLeave={() => {
            setHoverAudio2(false);
            stopAudio2();
        }}
    ></div>
);


来源: stackexchange

问:
DATE_ADD Function
A glitch in code on my website caused the start date and end date in an sql table to be set to the same day for my online member directory.  I have the code glitch corrected, but now need a way to fix the data in the database.  I am trying to add a certain number of months (12, 18, 24, etc) to the end_date column depending on the package column.  I only want to do this when the start_date column is equal to the end_date column.  I have a query started, but keep running into an invalid syntax message.  Can someone help?  My sql is below</p>
```<code>UPDATE porye_jbusinessdirectory_orders
SET end_date = DATE_ADD(months,12,end_date)
WHERE start_date = end_date
AND package_id = 1;
</code>```

答:
If I understand you correctly, you want to use DATEADD instead.

Your syntax seems like DATEADD (datepart , number , date ) which is not the syntax for DATE_ADD

```<code>UPDATE porye_jbusinessdirectory_orders
SET end_date = DATEADD(month, 12 ,end_date)
WHERE start_date = end_date
AND package_id = 1;
</code>```

Check more here

ContentLicense: CC BY-SA 4.0

Title: DATE_ADD Function

Body:
A glitch in code on my website caused the start date and end date in an sql table to be set to the same day for my online member directory.  I have the code glitch corrected, but now need a way to fix the data in the database.  I am trying to add a certain number of months (12, 18, 24, etc) to the end_date column depending on the package column.  I only want to do this when the start_date column is equal to the end_date column.  I have a query started, but keep running into an invalid syntax message.  Can someone help?  My sql is below

UPDATE porye_jbusinessdirectory_orders
SET end_date = DATE_ADD(months,12,end_date)
WHERE start_date = end_date
AND package_id = 1;

Body:
If I understand you correctly, you want to use DATEADD instead.

Your syntax seems like DATEADD (datepart , number , date ) which is not the syntax for DATE_ADD

UPDATE porye_jbusinessdirectory_orders
SET end_date = DATEADD(month, 12 ,end_date)
WHERE start_date = end_date
AND package_id = 1;

Check more here


问:
Stream (Geo)JSON file and get startByte and endByte of each JSON record in the file
For very large JSON/GeoJSON files, I'd like to create a primitive key/value store that keeps track of the starting positions and lengths of each JSON record in the file. This way, I could look up individual records at a later stage without reading the whole file into memory (Using the fd.read API). Somewhat similar to a super simple database, but read-only and without the extra overhead.

The issue I'm facing is that I don't know how I could determine the starting position and byte length of each JSON record / GeoJSON feature in the original file.

Here's some pseudo-code showcasing what I'm trying to achieve, note that the geojsonStream.parse callback doesn't receive the startByte and length arguments in reality though.

Thanks for your help, also happy about any feedback outlining why this might be a bad idea :)

import geojsonStream from 'geojson-stream'
import { open } from 'fs/promises'
import { Buffer } from 'buffer'

function getFeaturePositionsInFile(fd) {
  return new Promise((resolve,reject) => {
    const featurePositionsInFile = []
    const stream = fd
      .createReadStream()
      .pipe(geojsonStream.parse((building, index, startByte, length) => {
          // The startByte and length callback arguments are not real unfortunately :(
          featurePositionsInFile.push({
            index,
            startPosition,
            length
          })
      }))
     stream.on('end', () => resolve(featurePositionsInFile))
     stream.on('error', () => reject)
  })
}

function readSingleFeatureFromFile(fd, startPosition, length) {
  return new Promise((resolve, reject) => {
    try {
      const buff = Buffer.alloc(length)
      const offset = 0
      const { buffer } = await fd.read(buff, offset, length, startPosition)
      const singleFeature = JSON.parse(buffer.toString())
      resolve(singleFeature)
    } catch (e) {
      reject(e)
    }
  })
}

const fd = await open('buildings.geojson')
const featurePositionsInFile = await getFeaturePositionsInFile(fd)
const featureIndexToRead = 0
const { startPosition, length } = featurePositionsInFile[featureIndexToRead]
const singleFeature = await readSingleFeatureFromFile(fd, startPosition, length)
```

答:
Alright, since I couldn't find a suitable package for my needs, I created a simple (naïve) solution using RegExp to extract single GeoJSON features.

It works given:

The GeoJSON has a properties object, and the object is the last key in the parent GeoJSON object

the GeoJSON (properties) solely consists ASCII characters

For GeoJSON files containing non-ASCII characters, the byte counting is off. I tried but couldn't really find out what exactly I'm doing wrong, so any help is appreciated!

For a more general solution, I guess one would need to implement the byte counting logic in an existing library such as stream-json

import { open } from 'fs/promises'
import { Buffer } from 'buffer'

const HIGHWATERMARK = 64 * 1024 / 8

function getFeaturePositionsInFile(fd) {
  return new Promise((resolve,reject) => {
    const featurePositionsInFile = []
    const stream = fd.createReadStream({highWaterMark: HIGHWATERMARK, autoClose: false});
    // this RegEx will solely work with standard GeoJSON without any foreign members:
    // https://datatracker.ietf.org/doc/html/rfc7946#section-6.1
    // The properties object has to be present, and has to be that last key in the GeoJSON object
    const jsonExtractor = /\{[\n\r\s]*?"type":[\n\r\s]*?"Feature"[\S\s]*?\}(?:[\n\r\s]*\})+/g

    let string = ''
    let endPos = 0

    stream.on('data', (d) => {
      const section = d.toString()
      const sectionLength = (new TextEncoder().encode(section)).length
      string += section
      endPos+= sectionLength

      let match
      let latestEndPositionInString = 0
      while ((match = jsonExtractor.exec(string)) != null) {
        const startPositionInString = match.index
        const featureString = match[0]
        const endPositionInString = startPositionInString + featureString.length
        const curStringLength = (new TextEncoder().encode(string)).length
        // calculate starting position in file
        const startPosition = endPos - curStringLength + startPositionInString
        // calculate number of bytes in feature
        const byteLength = (new TextEncoder().encode(featureString)).length
        // store info for later in our lookup array
        featurePositionsInFile.push({
          startPosition,
          byteLength
        })
        if (endPositionInString > latestEndPositionInString) {
          latestEndPositionInString = endPositionInString
        }
      }
      // remove features from string to free memory
      string = string.substring(latestEndPositionInString)
    })
    stream.on('end', () => resolve(featurePositionsInFile))
    stream.on('error', () => reject)
  })
}

function readSingleFeatureFromFile(fd, startPosition, length) {
  return new Promise(async (resolve, reject) => {
    try {
      const buff = Buffer.alloc(length)
      const offset = 0
      const { buffer } = await fd.read(buff, offset, length, startPosition)
      const featureString = buffer.toString()
      const singleFeature = JSON.parse(featureString)
      resolve(singleFeature)
    } catch (e) {
      reject(e)
    }
  })
}

async function getFeature(featureIndexToRead, featurePositionsInFile) {
  const { startPosition, byteLength } = featurePositionsInFile[featureIndexToRead]
  const singleFeature = await readSingleFeatureFromFile(fd, startPosition, byteLength)
  return singleFeature
}

// source: https://raw.githubusercontent.com/node-geojson/geojson-stream/master/test/data/featurecollection.geojson
const path = 'featurecollection.geojson'
// -> has 3 features

const fd = await open(path, 'r');
const featurePositionsInFile = await getFeaturePositionsInFile(fd)
// get nth (e.g 3rd) feature in file
const firstFeature = await getFeature(2, featurePositionsInFile)
console.log(firstFeature)

// done! make sure to close the filehandle
fd.close()
```

https://gist.github.com/chrispahm/c226cca151b25147869288600151a5f8

Body:
Alright, since I couldn't find a suitable package for my needs, I created a simple (naïve) solution using RegExp to extract single GeoJSON features.

It works given:

The GeoJSON has a properties object, and the object is the last key in the parent GeoJSON object

the GeoJSON (properties) solely consists ASCII characters

For GeoJSON files containing non-ASCII characters, the byte counting is off. I tried but couldn't really find out what exactly I'm doing wrong, so any help is appreciated!

For a more general solution, I guess one would need to implement the byte counting logic in an existing library such as stream-json

import { open } from 'fs/promises'
import { Buffer } from 'buffer'

const HIGHWATERMARK = 64 * 1024 / 8

function getFeaturePositionsInFile(fd) {
  return new Promise((resolve,reject) => {
    const featurePositionsInFile = []
    const stream = fd.createReadStream({highWaterMark: HIGHWATERMARK, autoClose: false});
    // this RegEx will solely work with standard GeoJSON without any foreign members:
    // https://datatracker.ietf.org/doc/html/rfc7946#section-6.1
    // The properties object has to be present, and has to be that last key in the GeoJSON object
    const jsonExtractor = /\{[\n\r\s]*?"type":[\n\r\s]*?"Feature"[\S\s]*?\}(?:[\n\r\s]*\})+/g

    let string = ''
    let endPos = 0

    stream.on('data', (d) => {
      const section = d.toString()
      const sectionLength = (new TextEncoder().encode(section)).length
      string += section
      endPos+= sectionLength

      let match
      let latestEndPositionInString = 0
      while ((match = jsonExtractor.exec(string)) != null) {
        const startPositionInString = match.index
        const featureString = match[0]
        const endPositionInString = startPositionInString + featureString.length
        const curStringLength = (new TextEncoder().encode(string)).length
        // calculate starting position in file
        const startPosition = endPos - curStringLength + startPositionInString
        // calculate number of bytes in feature
        const byteLength = (new TextEncoder().encode(featureString)).length
        // store info for later in our lookup array
        featurePositionsInFile.push({
          startPosition,
          byteLength
        })
        if (endPositionInString > latestEndPositionInString) {
          latestEndPositionInString = endPositionInString
        }
      }
      // remove features from string to free memory
      string = string.substring(latestEndPositionInString)
    })
    stream.on('end', () => resolve(featurePositionsInFile))
    stream.on('error', () => reject)
  })
}

function readSingleFeatureFromFile(fd, startPosition, length) {
  return new Promise(async (resolve, reject) => {
    try {
      const buff = Buffer.alloc(length)
      const offset = 0
      const { buffer } = await fd.read(buff, offset, length, startPosition)
      const featureString = buffer.toString()
      const singleFeature = JSON.parse(featureString)
      resolve(singleFeature)
    } catch (e) {
      reject(e)
    }
  })
}

async function getFeature(featureIndexToRead, featurePositionsInFile) {
  const { startPosition, byteLength } = featurePositionsInFile[featureIndexToRead]
  const singleFeature = await readSingleFeatureFromFile(fd, startPosition, byteLength)
  return singleFeature
}

// source: https://raw.githubusercontent.com/node-geojson/geojson-stream/master/test/data/featurecollection.geojson
const path = 'featurecollection.geojson'
// -> has 3 features

const fd = await open(path, 'r');
const featurePositionsInFile = await getFeaturePositionsInFile(fd)
// get nth (e.g 3rd) feature in file
const firstFeature = await getFeature(2, featurePositionsInFile)
console.log(firstFeature)

// done! make sure to close the filehandle
fd.close()

https://gist.github.com/chrispahm/c226cca151b25147869288600151a5f8


问:
Customizing CSS classes in ASP.NET
I am working on an application where the user will be allowed to change the font color of header titles.

The header titles use a value from cssClass (the cssClass uses font-size, font-color, font-weight & font-family).

Is there a way that I can allow a custom font-color in the css file itself?

One option would be to eliminate font-color from the cssClass, and use Font-Color in the .aspx page.

答:
There isn't any problem in having color inside your CSS file and also inline on any HTML element, since inline styles will override the color defined on the file.

Imagine your CSS have this:

```<code>a#lnkTest { color: #ff0000; }
</code>```

But you do it on your aspx.vb:

```<code>lnkTest.ForeColor = Color.Blue;
</code>```

Your generated HTML will be:

```<code> <a id="lnkTest" style="color: #0000ff">Bla bla bla</a>
</code>```

So, the overrided color works without problems. Also, if you want to do it with JavaScript, it works in the same way:

```<code>document.getElementById("lnkTest").style.color = "#0000ff";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Customizing CSS classes in ASP.NET

Body:
There isn't any problem in having color inside your CSS file and also inline on any HTML element, since inline styles will override the color defined on the file.

Imagine your CSS have this:

a#lnkTest { color: #ff0000; }

But you do it on your aspx.vb:

lnkTest.ForeColor = Color.Blue;

Your generated HTML will be:

 <a id="lnkTest" style="color: #0000ff">Bla bla bla</a>

So, the overrided color works without problems. Also, if you want to do it with JavaScript, it works in the same way:

document.getElementById("lnkTest").style.color = "#0000ff";


问:
How can I convert an array of characters to an integer (for 2 or more digits)
The array has to be entered by the user, and not specified in the app itself.

```<code>char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    cin >> coeff[i];
    cin >> expo[i];
}
</code>```

When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit and still be saved in it in the variable?

PS. I'm forced into using an array of characters here and not integers

答:
I recommend directly using int variables instead of char arrays. But as you have to do it for your homework, I found a way to input data into a char array:

```<code>istream& operator>> (istream& is, char char_array[INT_MAX]) // INT_MAX means the maximum value for an int
{
    std::string s; is >> s;

    if (s.size() > 20) s = s.substr(0, 20);

    for (int i = 0; i < s.size(); i++)
    {
        char_array[i] = s[i];
    }
    return is;
}
</code>```

Here I am overloading the operator >> to work with char arrays of size INT_MAX.

Then in your main function, you can simply say:

```<code>int main()
{
    char char_array[20]{};

    std::cin >> char_array;

    for (int i = 0; i < sizeof(char_array); i++)
    {
        std::cout << char_array[i];
    }
}
</code>```

As simple as that. Also according to the code that you submitted, don't do the following:

```<code>using namespace std;
</code>```

...as it is considered as bad practice.
I know there are better ways than this but this is just my idea.

Body:
The array has to be entered by the user, and not specified in the app itself.

char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    cin >> coeff[i];
    cin >> expo[i];
}

When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit and still be saved in it in the variable?

PS. I'm forced into using an array of characters here and not integers

Body:
I recommend directly using int variables instead of char arrays. But as you have to do it for your homework, I found a way to input data into a char array:

istream& operator>> (istream& is, char char_array[INT_MAX]) // INT_MAX means the maximum value for an int
{
    std::string s; is >> s;

    if (s.size() > 20) s = s.substr(0, 20);

    for (int i = 0; i < s.size(); i++)
    {
        char_array[i] = s[i];
    }
    return is;
}

Here I am overloading the operator >> to work with char arrays of size INT_MAX.

Then in your main function, you can simply say:

int main()
{
    char char_array[20]{};

    std::cin >> char_array;

    for (int i = 0; i < sizeof(char_array); i++)
    {
        std::cout << char_array[i];
    }
}

As simple as that. Also according to the code that you submitted, don't do the following:

using namespace std;

...as it is considered as bad practice.
I know there are better ways than this but this is just my idea.


问:
Material-UI NextJS Button Styling Issue
i am having a problem getting the styling right on a couple of buttons in JS, it seems when i add a styling class via className that on first render the formatting works, but on subsequent refreshes it loses its styling. It is only happening on the two individual buttons i have. After troubleshooting for ages, i have found that everything works when i use SX instead of classNames, so if i do this then the refresh works. So in code below one button styles and remains styles, but the second one, refreshing my button class does not? Stumped at this point, i ran through forums and see a lot about NextJs needing some extra config in _document and _app to make it work, but i ran this in from the NextJs Material UI boiler plate from Git so dont think it could be that causing it.

Code:

```<code>import React from 'react'

import { AppBar, Toolbar, alpha } from "@mui/material";
import Button from '@mui/material/Button'
import ButtonBase from '@mui/material/ButtonBase';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import InputBase from '@mui/material/InputBase';
import SearchIcon from '@mui/icons-material/Search';
import AddIcon from '@mui/icons-material/Add';
import { makeStyles } from '@mui/styles'

const useStyles = makeStyles(theme => ({

    button: {
        ...theme.typography.mainmenu,
        borderRadius: "40px",
        width: "230px",
        height: "130px",
        marginLeft: "30px",
        alignItem: "center",
        "&:hover": {
            backgroundColor: theme.palette.secondary
        },
        [theme.breakpoints.down("sm")]: {
            width: '100% !important', // Overrides inline-style
            height: 100
        },
    },

}))
/*Image Button Styling Begins*/
const images = [
    {
        url: '/assets/breakfastMenu.jpg',
        title: 'Breakfast',
        width: '20%',
    },
    {
        url: '/assets/steak.jpg',
        title: 'Mains',
        width: '20%',
    },
    {
        url: '/assets/desserts.jpg',
        title: 'Desserts',
        width: '20%',
    },
];
const Image = styled('span')(({ theme }) => ({
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    color: theme.palette.common.primary,
}));

const ImageButton = styled(ButtonBase)(({ theme }) => ({
    position: 'relative',
    height: 150,
    [theme.breakpoints.down('sm')]: {
        width: '100% !important', // Overrides inline-style
        height: 100,
    },
    '&:hover, &.Mui-focusVisible': {
        zIndex: 1,
        '& .MuiImageBackdrop-root': {
            opacity: 0.15,
        },
        '& .MuiImageMarked-root': {
            opacity: 0,
        },
        '& .MuiTypography-root': {
            border: '4px solid currentColor',
        },
    },
}));

const ImageSrc = styled('span')({
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    backgroundSize: 'cover',
    backgroundPosition: 'center 40%',
});
const ImageBackdrop = styled('span')(({ theme }) => ({
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    backgroundColor: theme.palette.common.black,
    opacity: 0.4,
    transition: theme.transitions.create('opacity'),
}));

const ImageMarked = styled('span')(({ theme }) => ({
    height: 3,
    width: 18,
    backgroundColor: theme.palette.common.white,
    position: 'absolute',
    bottom: -2,
    left: 'calc(50% - 9px)',
    transition: theme.transitions.create('opacity'),
}));
/*Image Button Styling Ends*/

const Search = styled('div')(({ theme }) => ({
    position: 'relative',
    borderRadius: theme.shape.borderRadius,
    backgroundColor: alpha(theme.palette.common.white, 0.15),
    '&:hover': {
        backgroundColor: alpha(theme.palette.common.white, 0.25),
    },
    marginLeft: 0,
    width: '100%',
    [theme.breakpoints.up('sm')]: {
        marginLeft: theme.spacing(1),
        width: 'auto',
    },
}));

const SearchIconWrapper = styled('div')(({ theme }) => ({
    padding: theme.spacing(0, 2),
    height: '100%',
    position: 'absolute',
    pointerEvents: 'none',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
}));

const StyledInputBase = styled(InputBase)(({ theme }) => ({
    color: 'inherit',
    '& .MuiInputBase-input': {
        padding: theme.spacing(1, 1, 1, 0),
        // vertical padding + font size from searchIcon
        paddingLeft: `calc(1em + ${theme.spacing(4)})`,
        transition: theme.transitions.create('width'),
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            width: '12ch',
            '&:focus': {
                width: '20ch',
            },
        },
    },
}));

const Header = () => {
    const classes = useStyles();
    return (<React.Fragment>
        <AppBar position="sticky" className={classes.appBar}>
            <Toolbar disableGutters>

                {images.map((image) => (
                    <ImageButton
                        focusRipple
                        key={image.title}
                        style={{
                            width: image.width,
                        }}
                    >
                        <ImageSrc style={{
                            backgroundImage: `url(${image.url})`
                        }} />
                        <ImageBackdrop className="MuiImageBackdrop-root" />
                        <Image>
                            <Typography
                                component="span"
                                variant="subtitle1"
                                color="white"
                                fontWeight="bold"

                                sx={{
                                    position: 'relative',
                                    p: "7em",
                                    pt: "2em",
                                    pb: (theme) => `calc(${theme.spacing(1)} + 6px)`,
                                }}
                            >
                                {image.title}
                                <ImageMarked className="MuiImageMarked-root" />
                            </Typography>
                        </Image>
                    </ImageButton>
                ))}
                <Button size="large" variant="contained" color="secondary"
                    startIcon={<AddIcon />}
                    sx={{
                        borderRadius: "40px", borderRadius: "40px",
                        width: "230px",
                        height: "130px",
                        marginLeft: "30px",
                        alignItem: "center",
                    }} >Add A recipe</Button>
                <Button size="large" variant="contained" color="secondary" className={classes.button}>Meals for the Week</Button>
                <Search>
                    <SearchIconWrapper>
                        <SearchIcon />
                    </SearchIconWrapper>
                    <StyledInputBase
                        placeholder="Search…"
                        inputProps={{ 'aria-label': 'search' }}
                    />
                </Search>
            </Toolbar>
        </AppBar>

    </React.Fragment >
    )
}

export default Header
</code>```

答:
Exactly, you need to add some configuration to the _document.tsx in order to make the styles work properly with the NextJS server side rendering feature. The reason behind this is that you need that some styles are injected in the DOM for you.

As you can see in the MUI docs, you can use the ServerStyleSheets to handle the server side rendering properly.

This is the code I have in my _document.tsx

```<code>import React from 'react';
import Document, { Html, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@mui/styles';

export default class MyDocument extends Document {
    render() {
        return (
            <Html>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}

MyDocument.getInitialProps = async (ctx) => {
    // Render app and page and get the context of the page with collected side effects.
    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
        originalRenderPage({
            enhanceApp: (App) => (props) => sheets.collect(<App {...props} />)
        });

    const initialProps = await Document.getInitialProps(ctx);

    return {
        ...initialProps,
        // Styles fragment is rendered after the app and page rendering finish.
        styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()]
    };
};
</code>```

You can read more information about this in these Server rendering - MUI docs

Title: Material-UI NextJS Button Styling Issue

Body:
i am having a problem getting the styling right on a couple of buttons in JS, it seems when i add a styling class via className that on first render the formatting works, but on subsequent refreshes it loses its styling. It is only happening on the two individual buttons i have. After troubleshooting for ages, i have found that everything works when i use SX instead of classNames, so if i do this then the refresh works. So in code below one button styles and remains styles, but the second one, refreshing my button class does not? Stumped at this point, i ran through forums and see a lot about NextJs needing some extra config in _document and _app to make it work, but i ran this in from the NextJs Material UI boiler plate from Git so dont think it could be that causing it.

Code:

import React from 'react'

import { AppBar, Toolbar, alpha } from "@mui/material";
import Button from '@mui/material/Button'
import ButtonBase from '@mui/material/ButtonBase';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import InputBase from '@mui/material/InputBase';
import SearchIcon from '@mui/icons-material/Search';
import AddIcon from '@mui/icons-material/Add';
import { makeStyles } from '@mui/styles'

const useStyles = makeStyles(theme => ({

    button: {
        ...theme.typography.mainmenu,
        borderRadius: "40px",
        width: "230px",
        height: "130px",
        marginLeft: "30px",
        alignItem: "center",
        "&:hover": {
            backgroundColor: theme.palette.secondary
        },
        [theme.breakpoints.down("sm")]: {
            width: '100% !important', // Overrides inline-style
            height: 100
        },
    },

}))
/*Image Button Styling Begins*/
const images = [
    {
        url: '/assets/breakfastMenu.jpg',
        title: 'Breakfast',
        width: '20%',
    },
    {
        url: '/assets/steak.jpg',
        title: 'Mains',
        width: '20%',
    },
    {
        url: '/assets/desserts.jpg',
        title: 'Desserts',
        width: '20%',
    },
];
const Image = styled('span')(({ theme }) => ({
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    color: theme.palette.common.primary,
}));

const ImageButton = styled(ButtonBase)(({ theme }) => ({
    position: 'relative',
    height: 150,
    [theme.breakpoints.down('sm')]: {
        width: '100% !important', // Overrides inline-style
        height: 100,
    },
    '&:hover, &.Mui-focusVisible': {
        zIndex: 1,
        '& .MuiImageBackdrop-root': {
            opacity: 0.15,
        },
        '& .MuiImageMarked-root': {
            opacity: 0,
        },
        '& .MuiTypography-root': {
            border: '4px solid currentColor',
        },
    },
}));

const ImageSrc = styled('span')({
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    backgroundSize: 'cover',
    backgroundPosition: 'center 40%',
});
const ImageBackdrop = styled('span')(({ theme }) => ({
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    backgroundColor: theme.palette.common.black,
    opacity: 0.4,
    transition: theme.transitions.create('opacity'),
}));

const ImageMarked = styled('span')(({ theme }) => ({
    height: 3,
    width: 18,
    backgroundColor: theme.palette.common.white,
    position: 'absolute',
    bottom: -2,
    left: 'calc(50% - 9px)',
    transition: theme.transitions.create('opacity'),
}));
/*Image Button Styling Ends*/

const Search = styled('div')(({ theme }) => ({
    position: 'relative',
    borderRadius: theme.shape.borderRadius,
    backgroundColor: alpha(theme.palette.common.white, 0.15),
    '&:hover': {
        backgroundColor: alpha(theme.palette.common.white, 0.25),
    },
    marginLeft: 0,
    width: '100%',
    [theme.breakpoints.up('sm')]: {
        marginLeft: theme.spacing(1),
        width: 'auto',
    },
}));

const SearchIconWrapper = styled('div')(({ theme }) => ({
    padding: theme.spacing(0, 2),
    height: '100%',
    position: 'absolute',
    pointerEvents: 'none',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
}));

const StyledInputBase = styled(InputBase)(({ theme }) => ({
    color: 'inherit',
    '& .MuiInputBase-input': {
        padding: theme.spacing(1, 1, 1, 0),
        // vertical padding + font size from searchIcon
        paddingLeft: `calc(1em + ${theme.spacing(4)})`,
        transition: theme.transitions.create('width'),
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            width: '12ch',
            '&:focus': {
                width: '20ch',
            },
        },
    },
}));

const Header = () => {
    const classes = useStyles();
    return (<React.Fragment>
        <AppBar position="sticky" className={classes.appBar}>
            <Toolbar disableGutters>

                {images.map((image) => (
                    <ImageButton
                        focusRipple
                        key={image.title}
                        style={{
                            width: image.width,
                        }}
                    >
                        <ImageSrc style={{
                            backgroundImage: `url(${image.url})`
                        }} />
                        <ImageBackdrop className="MuiImageBackdrop-root" />
                        <Image>
                            <Typography
                                component="span"
                                variant="subtitle1"
                                color="white"
                                fontWeight="bold"

                                sx={{
                                    position: 'relative',
                                    p: "7em",
                                    pt: "2em",
                                    pb: (theme) => `calc(${theme.spacing(1)} + 6px)`,
                                }}
                            >
                                {image.title}
                                <ImageMarked className="MuiImageMarked-root" />
                            </Typography>
                        </Image>
                    </ImageButton>
                ))}
                <Button size="large" variant="contained" color="secondary"
                    startIcon={<AddIcon />}
                    sx={{
                        borderRadius: "40px", borderRadius: "40px",
                        width: "230px",
                        height: "130px",
                        marginLeft: "30px",
                        alignItem: "center",
                    }} >Add A recipe</Button>
                <Button size="large" variant="contained" color="secondary" className={classes.button}>Meals for the Week</Button>
                <Search>
                    <SearchIconWrapper>
                        <SearchIcon />
                    </SearchIconWrapper>

Body:
Exactly, you need to add some configuration to the _document.tsx in order to make the styles work properly with the NextJS server side rendering feature. The reason behind this is that you need that some styles are injected in the DOM for you.

As you can see in the MUI docs, you can use the ServerStyleSheets to handle the server side rendering properly.

This is the code I have in my _document.tsx

import React from 'react';
import Document, { Html, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@mui/styles';

export default class MyDocument extends Document {
    render() {
        return (
            <Html>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}

MyDocument.getInitialProps = async (ctx) => {
    // Render app and page and get the context of the page with collected side effects.
    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
        originalRenderPage({
            enhanceApp: (App) => (props) => sheets.collect(<App {...props} />)
        });

    const initialProps = await Document.getInitialProps(ctx);

    return {
        ...initialProps,
        // Styles fragment is rendered after the app and page rendering finish.
        styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()]
    };
};

You can read more information about this in these Server rendering - MUI docs


问:
Excel: SUMPRODUCT with percentages
I use the following formula to calculate the SUMPRODUCT of the values in a column with the condition that there is a match between B2:B6 and A1:A3 (shoutout to user:8162520).

=SUMPRODUCT(($B$1:$B$6=$A$9)*(G2:G6))

Now however I would like to subtract to that result the percentage in C1 and/or D1, and "give it" to one of the other blue numbers, again with the condition that there is a match between C2:C6 or D2:D6 and A7:A9.

So for example in G7 the result for "1" should be 50% of 10 + 75% of 5, because "2" takes 50% of 10(G2) and "3" takes 25% of 5(G5).

The point is to create an overview of how many hours employees (1,2,3) have to spend spend on project B2:B6 for each week (E,F,G), and what happens if other employees take a certain percentage of the workload (C,D). What is the most efficient way to do this?

The numbers in A, B,C, D are reference numbers, they should not be part of the calculation. Maybe it's clearer if I use letters. See also the right results for E7:G7. The outcome must be the sum of the values in each column (workload) minus the percentage in C and D IF there is someone sharing the workload:

答:
So deducting the percentage in C1:D1, presumably where there is no workload the result should be zero?

```<code>=SUMPRODUCT(($B$2:$B$6=$A7)*($C$2:$D$6<>"")*(1-$C$1:$D$1)*G$2:G$6)
</code>```

Title: Excel: SUMPRODUCT with percentages

Body:
So deducting the percentage in C1:D1, presumably where there is no workload the result should be zero?

=SUMPRODUCT(($B$2:$B$6=$A7)*($C$2:$D$6<>"")*(1-$C$1:$D$1)*G$2:G$6)


问:
Smarty - include file
I tried to include a tpl file using smarty include file like this,

```<code>{include file='file_name.tpl'}
</code>```

its not working for me. Is it needed to include path name.

答:
Try to set path to templates before. So call setTemplateDir before rendering of your template.

More here: https://www.smarty.net/docs/en/api.set.template.dir.tpl

Also as I can see Smarty allows to specify full path to template file inside of include directive. So even this is possible:

{include file='file:/usr/local/share/templates/navigation.tpl'}

But personally I would not recommend you to use this approach and stick to setTemplateDir and consistent place for templates in your app.

Little more information on that topic: https://www.smarty.net/docs/en/resources.tpl

Title: Smarty - include file

Body:
I tried to include a tpl file using smarty include file like this,

{include file='file_name.tpl'}

its not working for me. Is it needed to include path name.


问:
How to Set the Query Logging Level for a User in OBIEE12c
We would like to set query log level for a individual OBIEE 12c user to diagnose the query performance of data issue. Would anyone please guide us the way of set the log level for a obiee12c user.</p>

答:
Setting the query log level in obiee12c is as follows

In the Oracle BI Administration Tool, select Manage, then Identity.

The Identity Manager dialog is displayed.

Double-click the name of the user for which you want to set the query logging level.

The User dialog is displayed.

Set the logging level by clicking the Up or Down arrows next to the Logging Level field.

To disable query logging for a user, set the logging level to 0.

Click OK.

Study the following document for more detail about the query log level.
https://docs.oracle.com/middleware/1221/biee/BIESG/logging.htm#BIESG182


问:
Augmented matrix with symbolic variables and rref
Take a look at

```<code>syms x y z
A=[1 -2 x;2 1 y;-3 1 z]
rref(A)
</code>```

This is an augmented matrix and I need the final output to be

```<code>1  0  | (x+2y)/5
0  1  | (y-2x)/5
0  0  | z+x+y
</code>```

But rref() yeilds this

```<code>1  0  0
0  1  0
0  0  1
</code>```

Any suggestions how to get the intended output?

答:
As long as the symbolic variables are confined to the right half of your augmented matrix, you could proceed as follows. Suppose that [A|B] is your augmented matrix. Then, you could do the following.

```<code>M = rref([A, eye(size(A,1))]);
C = M(:,(size(A,2)+1):end) * B;
</code>```

In this case, C is the result of applying the row operations that brought M to its RREF to the symbolic matrix B.

Here's a modification that produces the result you initially expected.

```<code>syms x y z
A=[1 -2;2 1;-3 1];
B=[x;y;z];

[m,n] = size(A);
M = [eye(m),zeros(m,n)];
M(:,1:n) = A;
M(:,(m+1):end) = eye(m,n);
P = M(:,n+1:end);

R = rref(M);
C = R(:,n+1:end)/P*B;

disp(C)
</code>```

Result:

```<code> x/5 + (2*y)/5
 y/5 - (2*x)/5
     x + y + z
</code>```

Body:
Take a look at

syms x y z
A=[1 -2 x;2 1 y;-3 1 z]
rref(A)

This is an augmented matrix and I need the final output to be

1  0  | (x+2y)/5
0  1  | (y-2x)/5
0  0  | z+x+y

But rref() yeilds this

1  0  0
0  1  0
0  0  1

Any suggestions how to get the intended output?

Body:
As long as the symbolic variables are confined to the right half of your augmented matrix, you could proceed as follows. Suppose that [A|B] is your augmented matrix. Then, you could do the following.

M = rref([A, eye(size(A,1))]);
C = M(:,(size(A,2)+1):end) * B;

In this case, C is the result of applying the row operations that brought M to its RREF to the symbolic matrix B.

Here's a modification that produces the result you initially expected.

syms x y z
A=[1 -2;2 1;-3 1];
B=[x;y;z];

[m,n] = size(A);
M = [eye(m),zeros(m,n)];
M(:,1:n) = A;
M(:,(m+1):end) = eye(m,n);
P = M(:,n+1:end);

R = rref(M);
C = R(:,n+1:end)/P*B;

disp(C)

Result:

 x/5 + (2*y)/5
 y/5 - (2*x)/5
     x + y + z


问:
PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'remove_wpcf7' not found or invalid function name
Apologies for this broad question but I am not hugely familiar with the Error Log entries at present.  Any directives on where to begin the relevant research, would be greatly appreciated.

For the past 12 months, I have had the Google Authenticate Plugin, installed on a WordPress powered eCommerce website I work on.  There had been no issues with the Plugin until a recent VPS and WordPress update.  Since said updates, the Google Authenticate Plugin does not recognise any of the inputted codes.  I am not sure if the error is being triggered by the WordPress update or the VPS itself.

I then checked the error_log and saw the below entry when trying to use the Google Authenticate Plugin:

```<code>mod_fcgid: stderr: PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'remove_wpcf7' not found or invalid function name in /var/www/vhosts/example.com/httpdocs/wp-includes/class-wp-hook.php on line 286, referer: https://www.example.com/wp-admin/plugins.php
</code>```

Troubleshooting

As standard, I deactivated all Plugins (Except for the WooCommerce Plugin) as well as the WordPress Theme I had created.  I then simply activated WordPress' Twenty Seventeen Theme.  The error still persisted; leaving me wondering just what is causing the issue.

I can see there is a reference to WordPress' core files.  Maybe there is some incompatibilities?

Any directives on this, would be greatly appreciated ... Even if to just help me expand on this question.

答:
If you're here because of Timber/Twig this is an example of the correct way to use add_filter with timber/context:</p>
```<code>add_filter('timber/context', function($context) {
    $context['promo_modal'] = get_field('promo_modal', 'option');
    return $context;
});
</code>```

Body:
Apologies for this broad question but I am not hugely familiar with the Error Log entries at present.  Any directives on where to begin the relevant research, would be greatly appreciated.

For the past 12 months, I have had the Google Authenticate Plugin, installed on a WordPress powered eCommerce website I work on.  There had been no issues with the Plugin until a recent VPS and WordPress update.  Since said updates, the Google Authenticate Plugin does not recognise any of the inputted codes.  I am not sure if the error is being triggered by the WordPress update or the VPS itself.

I then checked the error_log and saw the below entry when trying to use the Google Authenticate Plugin:

mod_fcgid: stderr: PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'remove_wpcf7' not found or invalid function name in /var/www/vhosts/example.com/httpdocs/wp-includes/class-wp-hook.php on line 286, referer: https://www.example.com/wp-admin/plugins.php

Troubleshooting

As standard, I deactivated all Plugins (Except for the WooCommerce Plugin) as well as the WordPress Theme I had created.  I then simply activated WordPress' Twenty Seventeen Theme.  The error still persisted; leaving me wondering just what is causing the issue.

I can see there is a reference to WordPress' core files.  Maybe there is some incompatibilities?

Any directives on this, would be greatly appreciated ... Even if to just help me expand on this question.

Body:
If you're here because of Timber/Twig this is an example of the correct way to use add_filter with timber/context:

add_filter('timber/context', function($context) {
    $context['promo_modal'] = get_field('promo_modal', 'option');
    return $context;
});


问:
Reduce artifacts when resampling a Brain MRI scan using scipy affine_transform
I have a Brain MRI. It is gray scale with 20 slices. I put it into a numpy array with shape (20,256,256).  I use scipy.ndimage affine_transform to rotate and resample the array as below.

The dark stipes in the image is the artifact that I want reduce. The artifact is caused by the relatively large gap between the slices. In this example the pixel spacing is 0.85 mm, but the distance between slices is 7 mm.

I tried to change the order of the affine transform, but even order=5 has the same artifacts.  Below is order=0 (nearest neighbor)...

and you can see how the curvature of the skull is compounding the problem.  Are there any tricks to fix this?  Maybe I should add dummy data between the pixels to equalize the spacing? Maybe I should use polar coordinates to eliminate the curvature?  Any other ideas?

答:
The affine_transform using any order will look terrible. You need to do feature detection and delaunay triangulation on both images first, and then use the interpolating variable as a morph parameter to move the pixels between the corresponding features in adjacent images.  see link https://devendrapratapyadav.github.io/FaceMorphing/

see also this video https://www.youtube.com/watch?v=5FEr5SiXB1g


问:
Split CSV file into 2 lists depending on value
I have a UTF-8 encoded CSV file like this..

```<code>"id","name","type","price"
"23","item1","t-shirt","37"
"56","item66","jumper","3"
"366","item7","jumper","55"
"745","item 9","t-shirt","45"
"3245","item 12","t-shirt","67"
"654","item 88","jumper","66"
"2","item 99","jumper","77"
</code>```

And using python I am trying to split it into 2 lists based on type to give me an output like this..

```<code>File 1
id   | name    | type    | price
--------------------------------
23   | item1   | t-shirt | 37
745  | item 9  | t-shirt | 45
3245 | item 12 | t-shirt | 67

File 2
id   | name    | type    | price
--------------------------------
56   | item66  | jumper  | 3
366  | item7   | jumper  | 55
654  | item 88 | jumper  | 66
2    | item 99 | jumper  | 77
</code>```

I have this so far

```<code>list1 = []
list2 = []

with open(filename, encoding="utf8") as csv_file:

    csv_reader = csv.reader(csv_file, delimiter='\t')

        for row in csv_reader:

            if row['type'] == 't-shirt':
                list1.append(row)
            elif row['type'] == 't-shirt':
                list2.append(row)

</code>```

But this is giving me the following error...

```<code>TypeError: list indices must be integers or slices, not str
</code>```

Where am I going wrong?

答:
When you use csv.reader, row is a list. List indices must be integers, so row['type'] isn't allowed. If you want it to be a dict, use csv.DictReader

```<code>list1 = []
list2 = []

with open(filename, encoding="utf8") as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter='\t')
    for row in csv_reader:
        if row['type'] == 't-shirt':
            list1.append(row)
        elif row['type'] == 'jumper':
            list2.append(row)
</code>```

Alternatively, if you want to stick to csv.reader, use integer indices (you can hardcode row[2] or look for "type" in the column headers which you'll get as the first record of the csv file):

```<code>with open(filename, encoding="utf8") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='\t')
    columns = next(csv_reader)
    type_col = columns.index("type")
    for row in csv_reader:
        if row[type_col] == 't-shirt':
            list1.append(row)
        elif row[type_col] == 'jumper':
            list2.append(row)
</code>```

Body:
I have a UTF-8 encoded CSV file like this..

"id","name","type","price"
"23","item1","t-shirt","37"
"56","item66","jumper","3"
"366","item7","jumper","55"
"745","item 9","t-shirt","45"
"3245","item 12","t-shirt","67"
"654","item 88","jumper","66"
"2","item 99","jumper","77"

And using python I am trying to split it into 2 lists based on type to give me an output like this..

File 1
id   | name    | type    | price
--------------------------------
23   | item1   | t-shirt | 37
745  | item 9  | t-shirt | 45
3245 | item 12 | t-shirt | 67

File 2
id   | name    | type    | price
--------------------------------
56   | item66  | jumper  | 3
366  | item7   | jumper  | 55
654  | item 88 | jumper  | 66
2    | item 99 | jumper  | 77

I have this so far

list1 = []
list2 = []

with open(filename, encoding="utf8") as csv_file:

    csv_reader = csv.reader(csv_file, delimiter='\t')

        for row in csv_reader:

            if row['type'] == 't-shirt':
                list1.append(row)
            elif row['type'] == 't-shirt':
                list2.append(row)

But this is giving me the following error...

TypeError: list indices must be integers or slices, not str

Where am I going wrong?

Body:
When you use csv.reader, row is a list. List indices must be integers, so row['type'] isn't allowed. If you want it to be a dict, use csv.DictReader

list1 = []
list2 = []

with open(filename, encoding="utf8") as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter='\t')
    for row in csv_reader:
        if row['type'] == 't-shirt':
            list1.append(row)
        elif row['type'] == 'jumper':
            list2.append(row)

Alternatively, if you want to stick to csv.reader, use integer indices (you can hardcode row[2] or look for "type" in the column headers which you'll get as the first record of the csv file):

with open(filename, encoding="utf8") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='\t')
    columns = next(csv_reader)
    type_col = columns.index("type")
    for row in csv_reader:
        if row[type_col] == 't-shirt':
            list1.append(row)
        elif row[type_col] == 'jumper':
            list2.append(row)


问:
State not captured by callback in React component
I have this component that uses useState, and wraps its children in a Modal component, which is an old component from our application, and the modal component happens to be a total nightmare. But it takes an acceptData object which has a callback prop for when the "accept" button is clicked.

My issue is that my component is getting its state updated via another child (see onFileReadComplete), but then later when the button is clicked, that state is null. I can even see in the React dev tools that the state is not null, it has the value I expect.

Here is the component:

const CSVEditSwitcher = ({ acceptData, hideData }) => {
  const [parsedData, setParsedData] = useState(null);
  const dispatch = useDispatch();
  const enterLineups = lineupObject => dispatch(csvEditAPI(lineupObject));

  const modalProps = {
    className: "csv-upload",
    commonHide: true,
    acceptData: {
      actionName: "Submit",
      className: acceptData.className,
      callback: () => {
        if (!parsedData) {
          console.log("no data!"); // we keep getting here!
          return;
        }
        enterLineups(parsedData.masterLineups).then(acceptData.callback);
      },
    },
    hideData,
    validator: () => true,
  };

  return (
    <Modal {...modalProps}>
      {!parsedData ? (
        <UploadEditTemplate
          onFileReadComplete={data => {
            console.log({ data }); // this is always correct!
            setParsedData(data);
          }}
        />
      ) : (
        <ImportResults {...parsedData} />
      )}
    </Modal>
  );
};
```
<p>In case it's some crazy <code>this</code> issue, I've tried replacing the callback with a <code>function () { }</code> syntax, to no avail.</p>
<p>There's nothing interesting in the call point for the callback in <code>Modal</code>:</p>
<pre class="lang-js prettyprint-override"><code>  accept(e) {
    if (!e) return;
    if (e.key && (e.key !== "Enter" || e.key !== "Return")) return;

    const { acceptCallback } = this.state;
    console.log(acceptCallback, e);
    if (acceptCallback) acceptCallback(e);
  }
</code>```

Update

As a hail-mary, I tried converting this to a class component (wrapping it in a functional component that provides the hook values). It actually works, but only when accessing this.state.parsedData explicitly in the callback. i.e., I have const { parsedData } = this.state at the top of the render method for the other uses of that value, but the destructured variable does not work in the callback.

I would love if anyone could lend insight on what the hell is going on here!

答:
While destructuring props in injection ({...modalProps}...), you create a new instance in memory. Therefore callback prop will always have initial parsedData value.

My suggestion is to use callback as a reference to useCallback which aware to state manipulation

```<code> const callback = useCallback(() => {
        if (!parsedData) {
          console.log("no data!")
          return;
        }
        enterLineups(parsedData.masterLineups).then(acceptData.callback);
      }, [parsedData])

 const modalProps = {
    className: "csv-upload",
    commonHide: true,
    acceptData: {
      actionName: "Submit",
      className: acceptData.className,
      callback
    },
    hideData,
    validator: () => true,
  };
</code>```

Body:
I have this component that uses useState, and wraps its children in a Modal component, which is an old component from our application, and the modal component happens to be a total nightmare. But it takes an acceptData object which has a callback prop for when the "accept" button is clicked.

My issue is that my component is getting its state updated via another child (see onFileReadComplete), but then later when the button is clicked, that state is null. I can even see in the React dev tools that the state is not null, it has the value I expect.

Here is the component:

const CSVEditSwitcher = ({ acceptData, hideData }) => {
  const [parsedData, setParsedData] = useState(null);
  const dispatch = useDispatch();
  const enterLineups = lineupObject => dispatch(csvEditAPI(lineupObject));

  const modalProps = {
    className: "csv-upload",
    commonHide: true,
    acceptData: {
      actionName: "Submit",
      className: acceptData.className,
      callback: () => {
        if (!parsedData) {
          console.log("no data!"); // we keep getting here!
          return;
        }
        enterLineups(parsedData.masterLineups).then(acceptData.callback);
      },
    },
    hideData,
    validator: () => true,
  };

  return (
    <Modal {...modalProps}>
      {!parsedData ? (
        <UploadEditTemplate
          onFileReadComplete={data => {
            console.log({ data }); // this is always correct!
            setParsedData(data);
          }}
        />
      ) : (
        <ImportResults {...parsedData} />
      )}
    </Modal>
  );
};

In case it's some crazy this issue, I've tried replacing the callback with a function () { } syntax, to no avail.

There's nothing interesting in the call point for the callback in Modal:

  accept(e) {
    if (!e) return;
    if (e.key && (e.key !== "Enter" || e.key !== "Return")) return;

    const { acceptCallback } = this.state;
    console.log(acceptCallback, e);
    if (acceptCallback) acceptCallback(e);
  }

Update

As a hail-mary, I tried converting this to a class component (wrapping it in a functional component that provides the hook values). It actually works, but only when accessing this.state.parsedData explicitly in the callback. i.e., I have const { parsedData } = this.state at the top of the render method for the other uses of that value, but the destructured variable does not work in the callback.

I would love if anyone could lend insight on what the hell is going on here!

Body:
While destructuring props in injection ({...modalProps}...), you create a new instance in memory. Therefore callback prop will always have initial parsedData value.

My suggestion is to use callback as a reference to useCallback which aware to state manipulation

 const callback = useCallback(() => {
        if (!parsedData) {
          console.log("no data!")
          return;
        }
        enterLineups(parsedData.masterLineups).then(acceptData.callback);
      }, [parsedData])

 const modalProps = {
    className: "csv-upload",
    commonHide: true,
    acceptData: {
      actionName: "Submit",
      className: acceptData.className,
      callback
    },
    hideData,
    validator: () => true,
  };


问:
Grappler optimization failed. Error: Op type not registered 'FusedBatchNormV3' in Tensorflow Serving
I am serving a model using Tensorflow Serving.

```<code>TensorFlow ModelServer: 1.13.0-rc1+dev.sha.fd92d2f
TensorFlow Library: 1.13.0-rc1
</code>```

I sanity tested with load_model and predict(...) in notebook and it is making the expected predictions. The model is a ResNet50 with custom head (fine tuned).

If i try to submit the request as instructed in:

https://www.tensorflow.org/tfx/tutorials/serving/rest_simple

I got error

```<code>2022-02-10 22:22:09.120103: W external/org_tensorflow/tensorflow/core/kernels/partitioned_function_ops.cc:197] Grappler optimization failed. Error: Op type not registered 'FusedBatchNormV3' in binary running on tensorflow-no-gpu-20191205-rec-eng. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) `tf.contrib.resampler` should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed.
2022-02-10 22:22:09.137225: W external/org_tensorflow/tensorflow/core/framework/op_kernel.cc:1401] OP_REQUIRES failed at partitioned_function_ops.cc:118 : Not found: Op type not registered 'FusedBatchNormV3' in binary running on tensorflow-no-gpu-20191205-rec-eng. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) `tf.contrib.resampler` should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed.
</code>```

Any idea how to resolve? Will provide more details upon request.

答:
I found out what's wrong. the tensorflow server version seemed wrong. Just ensure it is:

TensorFlow ModelServer: 2.8.0-rc1+dev.sha.9400ef1

TensorFlow Library: 2.8.0

Body:
I am serving a model using Tensorflow Serving.

TensorFlow ModelServer: 1.13.0-rc1+dev.sha.fd92d2f
TensorFlow Library: 1.13.0-rc1

I sanity tested with load_model and predict(...) in notebook and it is making the expected predictions. The model is a ResNet50 with custom head (fine tuned).

If i try to submit the request as instructed in:

https://www.tensorflow.org/tfx/tutorials/serving/rest_simple

I got error

2022-02-10 22:22:09.120103: W external/org_tensorflow/tensorflow/core/kernels/partitioned_function_ops.cc:197] Grappler optimization failed. Error: Op type not registered 'FusedBatchNormV3' in binary running on tensorflow-no-gpu-20191205-rec-eng. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) `tf.contrib.resampler` should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed.
2022-02-10 22:22:09.137225: W external/org_tensorflow/tensorflow/core/framework/op_kernel.cc:1401] OP_REQUIRES failed at partitioned_function_ops.cc:118 : Not found: Op type not registered 'FusedBatchNormV3' in binary running on tensorflow-no-gpu-20191205-rec-eng. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) `tf.contrib.resampler` should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed.

Any idea how to resolve? Will provide more details upon request.


问:
Getting database values from post* events
my goal is to log all changes (INSERT, UPDATE, DELETE) made to the database. At the moment I use the "state" properties of the event args from the event listener API of NHibernate.

Unfortunately this doesn't work well if the changed property itself is another entity or if a user type is used. In these cases I would like to log the entity's Id/the value of the db columns etc.

But I did not found any data in the event args (IEntityPersister, ISession, etc.) that contain the original values of the db columns. Is this actually possible?

Here's a sample where an INSERT operation in handled. result.DatabaseValues contains the changed data.

```<code>private DatabaseOperation CreateInsertOperation(PostInsertEvent @event, LoggedClassConfiguration entityLoggingConfiguration)
  {
     string tableName = @event.Persister.QuerySpaces.First();
     DatabaseOperation result = ...

     object[] newState = @event.State;
     for (int i = 0; i < newState.Length; i++)
     {
        object newValue = newState[i];

        PropertyColumnMapping map = entityLoggingConfiguration.GetMapping(@event.Persister.PropertyNames.ElementAt(i));
        if (map == null)
        {
           continue;
        }

        result.DatabaseValues.Add(new DatabaseValue
        {
           NewValue = newValue,
           FieldName = map.DatabaseColumnName
        });
     }

     return result;
  }
</code>```

答:
I implemented a logger this way:

```<code>var persister = anEvent.Persister;
for (int i = 0; i < persister.PropertyNames.Length; i++)
{
    var propertyType = persister.PropertyTypes[i];
    if (!propertyType.IsCollectionType)
    {
        var insertEvent = anEvent as PostInsertEvent;
        if (insertEvent != null)
        {
            var logEntry = (AuditLog) baseLog.Clone();
            logEntry.PropertyName = persister.PropertyNames[i];
            logEntry.PropertyNewValue = this.GetStateValue( insertEvent.State[i] );
            logger.DebugFormat( "Feld hinzugefuegt: '{0}' => '{1}'", logEntry.PropertyName, logEntry.PropertyNewValue );
            Session.Save( logEntry );
        }
    }
}
</code>```

With this Way you get every propter which is inserted into the database. The only problem you have is with collection types and the references.

If I implemented an AuditLogging today, I would persist all Information into XML into a CLOB Database field.

Body:
my goal is to log all changes (INSERT, UPDATE, DELETE) made to the database. At the moment I use the "state" properties of the event args from the event listener API of NHibernate.

Unfortunately this doesn't work well if the changed property itself is another entity or if a user type is used. In these cases I would like to log the entity's Id/the value of the db columns etc.

But I did not found any data in the event args (IEntityPersister, ISession, etc.) that contain the original values of the db columns. Is this actually possible?

Here's a sample where an INSERT operation in handled. result.DatabaseValues contains the changed data.

private DatabaseOperation CreateInsertOperation(PostInsertEvent @event, LoggedClassConfiguration entityLoggingConfiguration)
  {
     string tableName = @event.Persister.QuerySpaces.First();
     DatabaseOperation result = ...

     object[] newState = @event.State;
     for (int i = 0; i < newState.Length; i++)
     {
        object newValue = newState[i];

        PropertyColumnMapping map = entityLoggingConfiguration.GetMapping(@event.Persister.PropertyNames.ElementAt(i));
        if (map == null)
        {
           continue;
        }

        result.DatabaseValues.Add(new DatabaseValue
        {
           NewValue = newValue,
           FieldName = map.DatabaseColumnName
        });
     }

     return result;
  }

Body:
I implemented a logger this way:

var persister = anEvent.Persister;
for (int i = 0; i < persister.PropertyNames.Length; i++)
{
    var propertyType = persister.PropertyTypes[i];
    if (!propertyType.IsCollectionType)
    {
        var insertEvent = anEvent as PostInsertEvent;
        if (insertEvent != null)
        {
            var logEntry = (AuditLog) baseLog.Clone();
            logEntry.PropertyName = persister.PropertyNames[i];
            logEntry.PropertyNewValue = this.GetStateValue( insertEvent.State[i] );
            logger.DebugFormat( "Feld hinzugefuegt: '{0}' => '{1}'", logEntry.PropertyName, logEntry.PropertyNewValue );
            Session.Save( logEntry );
        }
    }
}

With this Way you get every propter which is inserted into the database. The only problem you have is with collection types and the references.

If I implemented an AuditLogging today, I would persist all Information into XML into a CLOB Database field.


问:
Why does MS Access not allow to copy a file when it is being used?
Generally you can copy a file even though it is being used and paste it into a different location.

However, I am unable to copy an MS Access file when it is being used, I get an error that the file is being used by another process. Is there any way to copy an MS Access file that is being used?

答: If you have any forms open that have a record source linked to a table, this will not allow the copy/paste</p>


问:
How do I sort a simple Lua table alphabetically?
I have already seen many threads with examples of how to do this, the problem is, I still can't do it.

All the examples have tables with extra data. For example somethings like this

```<code>lines = {
  luaH_set = 10,
  luaH_get = 24,
  luaH_present = 48,
}
</code>```

or this,

```<code>obj = {
   { N = 'Green1'      },
   { N = 'Green'       },
   { N = 'Sky blue99'  }
}
</code>```

I can code in a few languages but I'm very new to Lua, and tables are really confusing to me. I can't seem to work out how to adapt the code in the examples to be able to sort a simple table.

This is my table:

```<code>local players = {"barry", "susan", "john", "wendy", "kevin"}
</code>```

I want to sort these names alphabetically. I understand that Lua tables don't preserve order, and that's what's confusing me. All I essentially care about doing is just printing these names in alphabetical order, but I feel I need to learn this properly and know how to index them in the right order to a new table.

The examples I see are like this:

```<code>local function cmp(a, b)
   a = tostring(a.N)
   b = tostring(b.N)
   local patt = '^(.-)%s*(%d+)$'
   local _,_, col1, num1 = a:find(patt)
   local _,_, col2, num2 = b:find(patt)
   if (col1 and col2) and col1 == col2 then
      return tonumber(num1) < tonumber(num2)
   end
   return a < b
end

table.sort(obj, cmp)
for i,v in ipairs(obj) do
   print(i, v.N)
end
</code>```

or this:

```<code>function pairsByKeys (t, f)
  local a = {}
  for n in pairs(t) do table.insert(a, n) end
  table.sort(a, f)
  local i = 0      -- iterator variable
  local iter = function ()   -- iterator function
    i = i + 1
    if a[i] == nil then return nil
    else return a[i], t[a[i]]
    end
  end
  return iter
end

for name, line in pairsByKeys(lines) do
  print(name, line)
end
</code>```

and I'm just absolutely thrown by this as to how to do the same thing for a simple 1D table.

Can anyone please help me to understand this? I know if I can understand the most basic example, I'll be able to teach myself these harder examples.

答:
```<code>local players = {"barry", "susan", "john", "wendy", "kevin"}

-- sort ascending, which is the default
table.sort(players)
print(table.concat(players, ", "))

-- sort descending
table.sort(players, function(a,b) return a > b end)
print(table.concat(players, ", "))
</code>```

Here's why:

Your table players is a sequence.

```<code>local players = {"barry", "susan", "john", "wendy", "kevin"}
</code>```

Is equivalent to

```<code>local players = {
  [1] = "barry",
  [2] = "susan",
  [3] = "john",
  [4] = "wendy",
  [5] = "kevin",
}
</code>```

If you do not provide keys in the table constructor, Lua will use integer keys automatically.

A table like that can be sorted by its values. Lua will simply rearrange the index value pairs in respect to the return value of the compare function. By default this is

```<code>function (a,b) return a < b end
</code>```

If you want any other order you need to provide a function that returs true if element a comes befor b

Read this https://www.lua.org/manual/5.4/manual.html#pdf-table.sort

table.sort
Sorts the list elements in a given order, in-place, from list[1] to
list[#list]

This example is not a "list" or sequence:

```<code>lines = {
  luaH_set = 10,
  luaH_get = 24,
  luaH_present = 48,
}
</code>```

Which is equivalent to

```<code>lines = {
  ["luaH_set"] = 10,
  ["luaH_get"] = 24,
  ["luaH_present"] = 48,
}
</code>```

it only has strings as keys. It has no order. You need a helper sequence to map some order to that table's element.

The second example

```<code>obj = {
   { N = 'Green1'      },
   { N = 'Green'       },
   { N = 'Sky blue99'  }
}
</code>```

which is equivalent to

```<code>obj = {
  [1] = { N = 'Green1'      },
  [2] = { N = 'Green'       },
  [3] = { N = 'Sky blue99'  },
}
</code>```

Is a list. So you could sort it. But sorting it by table values wouldn't make too much sense. So you need to provide a function that gives you a reasonable way to order it.

Read this so you understand what a "sequence" or "list" is in this regard. Those names are used for other things as well. Don't let it confuse you.

https://www.lua.org/manual/5.4/manual.html#3.4.7

It is basically a table that has consecutive integer keys starting at 1.

Understanding this difference is one of the most important concepts while learning Lua. The length operator, ipairs and many functions of the table library only work with sequences.

Body:
I have already seen many threads with examples of how to do this, the problem is, I still can't do it.

All the examples have tables with extra data. For example somethings like this

lines = {
  luaH_set = 10,
  luaH_get = 24,
  luaH_present = 48,
}

or this,

obj = {
   { N = 'Green1'      },
   { N = 'Green'       },
   { N = 'Sky blue99'  }
}

I can code in a few languages but I'm very new to Lua, and tables are really confusing to me. I can't seem to work out how to adapt the code in the examples to be able to sort a simple table.

This is my table:

local players = {"barry", "susan", "john", "wendy", "kevin"}

I want to sort these names alphabetically. I understand that Lua tables don't preserve order, and that's what's confusing me. All I essentially care about doing is just printing these names in alphabetical order, but I feel I need to learn this properly and know how to index them in the right order to a new table.

The examples I see are like this:

local function cmp(a, b)
   a = tostring(a.N)
   b = tostring(b.N)
   local patt = '^(.-)%s*(%d+)$'
   local _,_, col1, num1 = a:find(patt)
   local _,_, col2, num2 = b:find(patt)
   if (col1 and col2) and col1 == col2 then
      return tonumber(num1) < tonumber(num2)
   end
   return a < b
end

table.sort(obj, cmp)
for i,v in ipairs(obj) do
   print(i, v.N)
end

or this:

function pairsByKeys (t, f)
  local a = {}
  for n in pairs(t) do table.insert(a, n) end
  table.sort(a, f)
  local i = 0      -- iterator variable
  local iter = function ()   -- iterator function
    i = i + 1
    if a[i] == nil then return nil
    else return a[i], t[a[i]]
    end
  end
  return iter
end

for name, line in pairsByKeys(lines) do
  print(name, line)
end

and I'm just absolutely thrown by this as to how to do the same thing for a simple 1D table.

Can anyone please help me to understand this? I know if I can understand the most basic example, I'll be able to teach myself these harder examples.

Body:
local players = {"barry", "susan", "john", "wendy", "kevin"}

-- sort ascending, which is the default
table.sort(players)
print(table.concat(players, ", "))

-- sort descending
table.sort(players, function(a,b) return a > b end)
print(table.concat(players, ", "))

Here's why:

Your table players is a sequence.

local players = {"barry", "susan", "john", "wendy", "kevin"}

Is equivalent to

local players = {
  [1] = "barry",
  [2] = "susan",
  [3] = "john",
  [4] = "wendy",
  [5] = "kevin",
}

If you do not provide keys in the table constructor, Lua will use integer keys automatically.

A table like that can be sorted by its values. Lua will simply rearrange the index value pairs in respect to the return value of the compare function. By default this is

function (a,b) return a < b end

If you want any other order you need to provide a function that returs true if element a comes befor b

Read this https://www.lua.org/manual/5.4/manual.html#pdf-table.sort

table.sort
Sorts the list elements in a given order, in-place, from list[1] to
list[#list]

This example is not a "list" or sequence:

lines = {
  luaH_set = 10,
  luaH_get = 24,
  luaH_present = 48,
}

Which is equivalent to

lines = {
  ["luaH_set"] = 10,
  ["luaH_get"] = 24,
  ["luaH_present"] = 48,
}

it only has strings as keys. It has no order. You need a helper sequence to map some order to that table's element.

The second example

obj = {
   { N = 'Green1'      },
   { N = 'Green'       },
   { N = 'Sky blue99'  }
}

which is equivalent to

obj = {
  [1] = { N = 'Green1'      },
  [2] = { N = 'Green'       },
  [3] = { N = 'Sky blue99'  },
}

Is a list. So you could sort it. But sorting it by table values wouldn't make too much sense. So you need to provide a function that gives you a reasonable way to order it.

Read this so you understand what a "sequence" or "list" is in this regard. Those names are used for other things as well. Don't let it confuse you.

https://www.lua.org/manual/5.4/manual.html#3.4.7

It is basically a table that has consecutive integer keys starting at 1.

Understanding this difference is one of the most important concepts while learning Lua. The length operator, ipairs and many functions of the table library only work with sequences.


问:
TypeScript - The property does not exist in the type, but it actually exists
I'm trying to make my own xml builder on typescript. I have this issue:

```<code>Property 'children' does not exist on type 'XMLNode'.
  Property 'children' does not exist on type 'XMLNodeWithoutClidren'.
</code>```

its my code:

```<code>export interface Stringable {
  toString(): string
}

export type XMLProperty<T extends Stringable> = T

export interface XMLNodeWithoutClidren {
  readonly attributes: Map<string, XMLProperty<Stringable>>;
}

export interface XMLNodeWithClidren extends XMLNodeWithoutClidren {
  readonly children: Set<XMLNode>;
}

export type XMLNode = XMLNodeWithoutClidren | XMLNodeWithClidren;

class NodeWithoutChildrenBuilder {
  static build(node: XMLNodeWithoutClidren): string {
    return `some logic`
  }
}

class NodeWithChildrenBuilder {
  static build(node: XMLNodeWithClidren): string {
    return `some logic`
  }
}

class NodeParser {
  static parse(node: XMLNode) {
    if (node.children) {
      return NodeWithChildrenBuilder.build(node);
    }

    return NodeWithoutChildrenBuilder.build(node);
  }
}
</code>```

Playground

What's wrong with my code?

答:
If you try to access a property which isn't known to exist on an object, the compiler will warn you about it:

```<code>interface Foo {
  x: string;
}
function f(foo: Foo) {
  foo.y // <-- error, property 'y' does not exist on type 'Foo'
}
</code>```

This doesn't mean that the property cannot exist, it's just that the compiler has no idea if the property exists or not, and so it considers the access a probable error.  And because it has no idea if the property exists or not, it treats it as having the any type, because it could be anything (not necessarily undefined):

```<code>const b = { x: "", y: 1 };
f(b); // okay
</code>```

In your case, you are trying to access the children property on an object which is a union of two types: XMLNodeWithChildren which is known to have a children property of a certain type, and XMLNodeWithoutChildren which is not.

Despite the name, the compiler cannot know that XMLNodeWithoutChildren lacks a children property. Indeed, your own code defines XMLNodeWithChildren as an extension of XMLNodeWithoutChildren. By the rules of subtyping, every XMLNodeWithChildren is also a perfectly valid XMLNodeWithoutChildren. And there are all kinds of potential perfectly valid XMLNodeWithoutChildren extensions:

```<code>interface XMLNodeWithNumericChildren extends XMLNodeWithoutChildren {
  children: number;
}
</code>```

So, technically, faced with an object of type XMLNodeWithChildren | XMLNodeWithoutChildren, the compiler has no idea what, if anything, can be concluded about the children property.  It would be unsafe for the compiler to think that the type of the property is Set<XMLNode> | undefined.  It has to consider it any, and that doesn't help with control flow narrowing.

Case in point, let's imagine that NodeWithChildrenBuilder.build() actually does something Set-like with its argument's children property:

```<code>class NodeWithChildrenBuilder {
  static build(node: XMLNodeWithChildren): string {
    node.children.has(node); // compiles fine
    return `some logic`
  }
}
</code>```

You can then  cause a runtime error if you call NodeParser.parse() with an argument with some random children property, and the compiler is not guaranteed to catch this:

```<code>const x = { attributes: new Map(), children: 123 }
NodeParser.parse(x) // no compiler error, but RUNTIME ERROR!
</code>```

That's what's "wrong" with your code.

Of course, in practice, it seems unlikely that someone will hand you a pathological node of a type like XMLNodeWithNumericChildren.  And so while it's technically unsafe to use the presence of children to narrow an XMLNode to an XMLNodeWithChildren, you'd like to do it anyway.

If so, the easiest way for you to deal with this is to use the in operator type guard like this:

```<code>class NodeParser {
  static parse(node: XMLNode) {
    if ("children" in node) {  // <-- in operator here
      return NodeWithChildrenBuilder.build(node); // okay
    }
    return NodeWithoutChildrenBuilder.build(node); // okay
  }
}
</code>```

This works with no compiler errors now.  Note that this is still technically unsafe.  Someone can still call NodeParser.parse(x) like above and get a runtime error. But this lack of safety is considered acceptable in order to give people a way to do the kind of check you're doing: see this comment on microsoft/TypeScript#15256, the PR that implemented in guarding:

We considered the soundness aspect and it's not very different from existing soundness issues around aliased objects with undeclared properties. [...] The reality is that most unions are already correctly disjointed and don't alias enough to manifest the problem. Someone writing an in test is not going to write a "better" check; all that really happens in practice is that people add type assertions or move the code to an equally-unsound user-defined type predicate. On net I don't think this is any worse than the status quo (and is better because it induces fewer user-defined type predicates, which are error-prone if written using in due to a lack of typo-checking).

So, one solution is for you to change if (node.children) to if ("children" in node), forget about pathological XMLNode values, and move on with your life!

If upon reading the above though, you still worry about pathological cases, you can refactor your types so that XMLNodeWithoutChildren actually cannot have a defined children property value.  It could look like this:

```<code>interface BaseXMLNode {
  readonly attributes: Map<string, XMLProperty<Stringable>>;
}

export interface XMLNodeWithoutChildren extends BaseXMLNode {
  children?: never;
}

export interface XMLNodeWithChildren extends BaseXMLNode {
  readonly children: Set<XMLNode>;
}

export type XMLNode = XMLNodeWithoutChildren | XMLNodeWithChildren;
</code>```

Now we have a BaseXMLNode that both XMLNodeWithoutChildren and XMLNodeWithChildren derive from.  The XMLNodeWithoutChildren type has an optional children property of the impossible never type.  Since there are no values of type never, an optional property of type never is essentially the same as a prohibited property. The only value you'll ever see at the children property is undefined.

And that means XMLNode is now a truly discriminated union where the children property can be used to tell which type of XMLNode you have:

Once we do that, your original NodeParser code works again:

```<code>class NodeParser {
  static parse(node: XMLNode) {
    if (node.children) {
      return NodeWithChildrenBuilder.build(node); // okay
    }

    return NodeWithoutChildrenBuilder.build(node); // okay
  }
}
</code>```

and now those pathological cases are impossible, since children needs to either be a Set<...> or undefined:

```<code>const x = { attributes: new Map(), children: 123 }
NodeParser.parse(x) // error!
// ------------> ~
// Types of property 'children' are incompatible.
</code>```

This solution is as type-safe as you can get; it might or might not be worth the refactoring to get such type safety, depending on your use cases.

Playground link to code

Body:
I'm trying to make my own xml builder on typescript. I have this issue:

Property 'children' does not exist on type 'XMLNode'.
  Property 'children' does not exist on type 'XMLNodeWithoutClidren'.

its my code:

export interface Stringable {
  toString(): string
}

export type XMLProperty<T extends Stringable> = T

export interface XMLNodeWithoutClidren {
  readonly attributes: Map<string, XMLProperty<Stringable>>;
}

export interface XMLNodeWithClidren extends XMLNodeWithoutClidren {
  readonly children: Set<XMLNode>;
}

export type XMLNode = XMLNodeWithoutClidren | XMLNodeWithClidren;

class NodeWithoutChildrenBuilder {
  static build(node: XMLNodeWithoutClidren): string {
    return `some logic`
  }
}

class NodeWithChildrenBuilder {
  static build(node: XMLNodeWithClidren): string {
    return `some logic`
  }
}

class NodeParser {
  static parse(node: XMLNode) {
    if (node.children) {
      return NodeWithChildrenBuilder.build(node);
    }

    return NodeWithoutChildrenBuilder.build(node);
  }
}

<a href="https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgZRimQHNMAjAGzwG8AoOOGCQ4pEgCgEoAuOAZyKk6AXzp1QkWEwCeYPAA0AsgBkAClAjzYMgDwAVOKFRIAJvwJD2FagD44AXjj7xk6PGSoMORaoByEKbAAOoIMAAWEACuMADClAimUMBIcPSMyZimEEiUMnCYMELkMcD8fEqYYLqCbCQANHDK6praMHqspDbAtrYA3KKu4O6IKGhYuE3%20gSFh4fGJyanGKeZTKgFBoRHRcQlJKWkMcJnZufnY4QiUB0h8%20MAwus2bPQNiEsPS7fLrr45-GbbSIxBa3OAAH0BWzmYKWAzo2EomH4FlewN2sSuNyWACEotcglAjoxBIUENg4CVCRwkDM%20C8gXNMfslrwBFYSCTGCdHlEoKkAAb8CAAWzwlAgJApguOYg%20SJRaKZESxhLxBJuaG5ZJgFKpmtMtPp0NmqtZKXZtVI3IyfIFcGFYolUplcsGiORqLgrzUmCg-G16Q55MpYH9geNQQZ0yCXFtiHQcCjwAAdJd1ZaE3aYPzUujYdjbvjCWhU9SbimuAMeXAPrXkrmHQWdqCixrS1By4aqzW66IgA" rel="nofollow noreferrer">Playground

What's wrong with my code?

Body:
If you try to access a property which isn't known to exist on an object, the compiler will warn you about it:

interface Foo {
  x: string;
}
function f(foo: Foo) {
  foo.y // <-- error, property 'y' does not exist on type 'Foo'
}

This doesn't mean that the property cannot exist, it's just that the compiler has no idea if the property exists or not, and so it considers the access a probable error.  And because it has no idea if the property exists or not, it treats it as having the any type, because it could be anything (not necessarily undefined):

const b = { x: "", y: 1 };
f(b); // okay

In your case, you are trying to access the children property on an object which is a union of two types: XMLNodeWithChildren which is known to have a children property of a certain type, and XMLNodeWithoutChildren which is not.

Despite the name, the compiler cannot know that XMLNodeWithoutChildren lacks a children property. Indeed, your own code defines XMLNodeWithChildren as an extension of XMLNodeWithoutChildren. By the rules of subtyping, every XMLNodeWithChildren is also a perfectly valid XMLNodeWithoutChildren. And there are all kinds of potential perfectly valid XMLNodeWithoutChildren extensions:

interface XMLNodeWithNumericChildren extends XMLNodeWithoutChildren {
  children: number;
}

So, technically, faced with an object of type XMLNodeWithChildren | XMLNodeWithoutChildren, the compiler has no idea what, if anything, can be concluded about the children property.  It would be unsafe for the compiler to think that the type of the property is Set<XMLNode> | undefined.  It has to consider it any, and that doesn't help with control flow narrowing.

Case in point, let's imagine that NodeWithChildrenBuilder.build() actually does something Set-like with its argument's children property:

class NodeWithChildrenBuilder {
  static build(node: XMLNodeWithChildren): string {
    node.children.has(node); // compiles fine
    return `some logic`
  }
}

You can then  cause a runtime error if you call NodeParser.parse() with an argument with some random children property, and the compiler is not guaranteed to catch this:

const x = { attributes: new Map(), children: 123 }
NodeParser.parse(x) // no compiler error, but RUNTIME ERROR!

That's what's "wrong" with your code.

Of course, in practice, it seems unlikely that someone will hand you a pathological node of a type like XMLNodeWithNumericChildren.  And so while it's technically unsafe to use the presence of children to narrow an XMLNode to an XMLNodeWithChildren, you'd like to do it anyway.

If so, the easiest way for you to deal with this is to use the in operator type guard like this:

class NodeParser {
  static parse(node: XMLNode) {
    if ("children" in node) {  // <-- in operator here
      return NodeWithChildrenBuilder.build(node); // okay
    }
    return NodeWithoutChildrenBuilder.build(node); // okay
  }
}

This works with no compiler errors now.  Note that this is still technically unsafe.  Someone can still call NodeParser.parse(x) like above and get a runtime error. But this lack of safety is considered acceptable in order to give people a way to do the kind of check you're doing: see this comment on microsoft/TypeScript#15256, the PR that implemented in guarding:

We considered the soundness aspect and it's not very different from existing soundness issues around aliased objects with undeclared properties. [...] The reality is that most unions are already correctly disjointed and don't alias enough to manifest the problem. Someone writing an in test is not going to write a "better" check; all that really happens in practice is that people add type assertions or move the code to an equally-unsound user-defined type predicate. On net I don't think this is any worse than the status quo (and is better because it induces fewer user-defined type predicates, which are error-prone if written using in due to a lack of typo-checking).

So, one solution is for you to change if (node.children) to if ("children" in node), forget about pathological XMLNode values, and move on with your life!

If upon reading the above though, you still worry about pathological cases, you can refactor your types so that XMLNodeWithoutChildren actually cannot have a defined children property value.  It could look like this:

interface BaseXMLNode {
  readonly attributes: Map<string, XMLProperty<Stringable>>;
}

export interface XMLNodeWithoutChildren extends BaseXMLNode {
  children?: never;
}

export interface XMLNodeWithChildren extends BaseXMLNode {
  readonly children: Set<XMLNode>;
}

export type XMLNode = XMLNodeWithoutChildren | XMLNodeWithChildren;

Now we have a BaseXMLNode that both XMLNodeWithoutChildren and XMLNodeWithChildren derive from.  The XMLNodeWithoutChildren type has an optional children property of the impossible never type.  Since there are no values of type never, an optional property of type never is essentially the same as a prohibited property. The only value you'll ever see at the children property is undefined.

And that means XMLNode is now a truly discriminated union where the children property can be used to tell which type of XMLNode you have:

Once we do that, your original NodeParser code works again:

class NodeParser {
  static parse(node: XMLNode) {
    if (node.children) {
      return NodeWithChildrenBuilder.build(node); // okay
    }

    return NodeWithoutChildrenBuilder.build(node); // okay
  }
}

and now those pathological cases are impossible, since children needs to either be a Set<...> or undefined:

const x = { attributes: new Map(), children: 123 }
NodeParser.parse(x) // error!
// ------------> ~
// Types of property 'children' are incompatible.

This solution is as type-safe as you can get; it might or might not be worth the refactoring to get such type safety, depending on your use cases.

<a href="https://www.typescriptlang.org/play?#code/HYQwtgpgzgDiDGEAEApeIA2AvJBvAUEkgJbAAuEATgGYLIBiA9o3oUUgB4BcSUZlpAOYBuNgF821AK7B4ZYo2BJqACmrMeTRgEpW7ZcwB0ATyQB6M0gA8AWhtIqlRpQA0SGE5hUypgOTHfJAATRmgkYEYyBw5iPiRFJB8vJF8tX3F8TKJ4RTiAIyQAXjxOHgAiMrdjHgBGJDFRIlU87WFzS0YAaxBjTLZQSFg6JABlYjAYDAh6Yg5WNiIIDhhnKNIKGmGR-iEQPKm9fUTGbYFgQRVtHj4zwQX6rPYllcoopOQADQBZABkABU83mMVgAKtEKMAglBRjtznspgA+IpIEGPRbLVYkchUWiIJDfH4AOUYQQgAHViGQABaMKRkADCVOIGCClAgSgIRyQbJAIWAGFMIDIOzydOgPC+IBgVhuQjcBIBjC8r2Bp12+wgCIRjXYEnuz0x6xxwwJxNJFOpjOZrPZ4PZUPxvzN5MpNLpVpZbI59yIPL5AqQ8CZnvZPBGEDIVlNJM1OqIev0BteiWMyWjpOR6Zd1NpDODNqUAB9HUSYxaqR6C6J7vAMCAoNDneXc5WvQAhKTWqiHfR8IXEeBIUXWlQRUk8LPN935r1XXiwwQ9o5sshSShKAAGUEYkCQGEYggHG59D30CfYtfrjbLrtb7I7XcoS6Iffkg+HLNHMYnTpvlpn7JzrK5zPuwY4QIYQbWl6hhUvWX6kq0J6+hGa6btuu77oe8DHlyEhnmigZ1g2SDOn8ICUFA3ackcr4Du4FFUQhEA-qWiGgUQxDUEgKhlFBIbAGUWLhDGug0VyKGruupF-hWAHAA+LJUIYH5BMxSESQ8yHcqh0lNq6LbyYppKUCpnafuBGlHPhuqETkwBxHMxS4EgQoimKUA8MAEAAO5IJKMCXG4-EFrUABMADMp7sGRjHKXAlEQCoHC6BY3IyPIu6OM4GSPAM0BwHiABKEC4mQzjzImGLJkamx4mqcIaqB5UNRcQELvc57oi8bypp8vyKsqPignakLQq18KasiqL3LVuLIG29YQFmoF+ooAZuQIooUJ5-lSjKC7ygNgIqlYE0alqcZaVVPVYhs80lvpObTtBtpLBCDqLVRK3iRe8kAPxeRAABuVBXV10S3XNJq-uat7yaNn1LT9J5rfypghV6YYRlGsOxp1hFJr1aZ45meNTnmr1Fo9sl3sA1b6JeJFPW6lMCcZ1EnnR77mWp4E8F9y14+1twcTpUnoTuyBYUeJ42fGdnEdecP-lTHNPr9L5kP2PMjvzNMq3JVMi0IYvgZB8mwfBllXfoK5oUgW5S3uB6y3hBM1krMmkuRiUa1z2tvgxiXMaxzpidpXE8ebmOAWLkkOyzdPq2ZeuibbtnafbemyYZau88pqnqRn8vXReuRRE5JSbcQ23iuEvl7YF2jBfJ4VRaXsV+4YCVMSl7QOJQTiUAAhPcaV2JPU+T0iAB+4+WCCfXQow3EeEqQIpLHwCBBRyCkDkEz9hqhi5ZkYhAA" rel="nofollow noreferrer">Playground link to code