问:
How can I call a function from the parent component with an event in the child?
I'm busy learning React and one of the tasks is building a game where the cards shuffle on each try. The card array and the shuffle method are in a parent component (I use map to render the cards), but the retry button is in the child component.

I've read almost 20 StackOverflow questions and many docs, but somehow my logic is simply not working.

Can someone please help me to get this to work.

Parent:

```<code>import React from 'react'
import FlipCard from './FlipCard'

const cards = [
    {
        id: 1,
        text: 'NOPE',
    },
    {
        id: 2,
        text: `!!WIN-
        NER!!`,
    },
    {
        id: 3,
        text: 'NOPE',
    },
]

const shuffle = array => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        const temp = array[i]
        array[i] = array[j]
        array[j] = temp
    }
    return array
}

const shuffleCards = shuffle(cards)

const CardGameUI = () => {
    return (
        <div className="cards-ui">
            {cards.map(card => (
                <FlipCard
                    key={card.id}
                    text={card.text}
                    value={card.id}
                    shuffleCards={shuffleCards}
                />
            ))}
        </div>
    )
}

export default CardGameUI
</code>```

Child:

```<code>import React from 'react'
import ReactCardFlip from 'react-card-flip'
import FrontComponent from './FrontComponent'
import BackComponent from './BackComponent'
import RetryModal from './RetryModal'

class FlipCard extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            isFlipped: false,
            gamesPlayed: 0,
            gamesWon: 0,
            gamesLost: 0,
            show: false,
            gameMsg: '',
        }

        this.handleFlip = this.handleFlip.bind(this)
        this.handleShow = this.handleShow.bind(this)
        this.handleClose = this.handleClose.bind(this)
        this.handleReset = this.handleReset.bind(this)
        this.handleRetry = this.handleRetry.bind(this)
    }

    handleReset() {
        this.setState({
            isFlipped: false,
            gamesPlayed: 0,
            gamesWon: 0,
            gamesLost: 0,
            show: false,
            gameMsg: '',
        })
        this.props.shuffleCards
    }

    handleRetry() {
        this.setState({
            isFlipped: false,
            show: false,
            gameMsg: '',
        })
        this.props.shuffleCards
    }

    handleClose() {
        this.setState({
            show: false,
        })
    }
    handleShow() {
        this.setState({
            show: true,
        })
    }

    handleFlip() {
        this.setState({
            isFlipped: true,
            gamesPlayed: +1,
            show: false,
        })

        if (this.props.value !== 2) {
            this.setState({
                gamesLost: 0,
                gameMsg:
                    'It looks like you lost this round. Want to play another?',
            })
        } else if (this.props.value === 2) {
            this.setState({
                gamesWon: 0,
                gameMsg: 'CONGRATULATIONS!!!. Want to win again?',
            })
        }

        setTimeout(() => {
            this.handleShow()
        }, 1000)
    }

    render() {
        const text = this.props.text
        const value = this.props.value
        const isFlipped = this.state.isFlipped

        return (
            <>
                <ReactCardFlip isFlipped={isFlipped} flipDirection="horizontal">
                    <FrontComponent onClick={this.handleFlip} />

                    <BackComponent text={text} value={value} />
                </ReactCardFlip>

                <RetryModal
                    handleShow={this.handleShow}
                    handleClose={this.handleClose}
                    handleReset={this.handleReset}
                    handleRetry={this.handleRetry}
                    show={this.state.show}
                    text={this.state.gameMsg}
                />
            </>
        )
    }
}

export default FlipCard
</code>```

I included all the code from these two components as I wasn't sure what will help clarify.

Essentially the shuffleCards method needs to run when handleReset and handleRetry are triggered.

答:
You essentially have 3 problems:

the shuffleCards prop you were passing down was not actually a function, but the result of calling the function that shuffles the cards.

You seem to recognise the above by doing this.props.shuffleCards in the
child component - rather than this.props.shuffleCards() which here
would cause an error since this.props.shuffleCards is not a
function. But that is itself an admission of the problem, because
you clearly need to call a function here, in order to make anything
happen.

The function itself doesn't actually create a new shuffled array, but mutates the old one. Yes, it then returns that, but by returning the old object, even in mutated form, React won't be able to see a change and therefore won't know that the array has been mutated.

So here's how to solve. First, make the card array a state variable in the parent function, and make shuffleCards an actual function, that lives in the parent component (because it needs to access the current cards state), and one that, rather than simply mutating the old array of cards, makes a new array and updates the state with it.

Here's the new parent component, and note that the shuffle and shuffleCards values you've defined outside it are no longer needed or wanted:

```<code>const CardGameUI = () => {
    const [shuffledCards, setShuffledCards] = React.useState(cards);

    const shuffleCards = (currentCards) => {
        const array = [...currentCards]; // this makes a (shallow) copy of the array, so it's recognised by React as something new
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1))
            const temp = array[i]
            array[i] = array[j]
            array[j] = temp
        }
        setShuffledCards(array);
    };

    return (
        <div className="cards-ui">
            {shuffledCards.map(card => (
                <FlipCard
                    key={card.id}
                    text={card.text}
                    value={card.id}
                    shuffleCards={shuffleCards}
                />
            ))}
        </div>
    )
}
</code>```

And then you need to update the child component so that it actually calls this state-updating function, by changing as I indicated in point 2) above: replace this.props.shuffleCards with this.props.shuffleCards().

The cards should now be correctly shuffled when the appropriate actions are taken in the child component. (And let me know if anything still doesn't work as intended - I haven't actually tested this out.)

Body:
I'm busy learning React and one of the tasks is building a game where the cards shuffle on each try. The card array and the shuffle method are in a parent component (I use map to render the cards), but the retry button is in the child component.

I've read almost 20 StackOverflow questions and many docs, but somehow my logic is simply not working.

Can someone please help me to get this to work.

Parent:

import React from 'react'
import FlipCard from './FlipCard'

const cards = [
    {
        id: 1,
        text: 'NOPE',
    },
    {
        id: 2,
        text: `!!WIN-
        NER!!`,
    },
    {
        id: 3,
        text: 'NOPE',
    },
]

const shuffle = array => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        const temp = array[i]
        array[i] = array[j]
        array[j] = temp
    }
    return array
}

const shuffleCards = shuffle(cards)

const CardGameUI = () => {
    return (

            {cards.map(card => (
                <FlipCard
                    key={card.id}
                    text={card.text}
                    value={card.id}
                    shuffleCards={shuffleCards}
                />
            ))}

    )
}

export default CardGameUI

Child:

import React from 'react'
import ReactCardFlip from 'react-card-flip'
import FrontComponent from './FrontComponent'
import BackComponent from './BackComponent'
import RetryModal from './RetryModal'

class FlipCard extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            isFlipped: false,
            gamesPlayed: 0,
            gamesWon: 0,
            gamesLost: 0,
            show: false,
            gameMsg: '',
        }

        this.handleFlip = this.handleFlip.bind(this)
        this.handleShow = this.handleShow.bind(this)
        this.handleClose = this.handleClose.bind(this)
        this.handleReset = this.handleReset.bind(this)
        this.handleRetry = this.handleRetry.bind(this)
    }

    handleReset() {
        this.setState({
            isFlipped: false,
            gamesPlayed: 0,
            gamesWon: 0,
            gamesLost: 0,
            show: false,
            gameMsg: '',
        })
        this.props.shuffleCards
    }

    handleRetry() {
        this.setState({
            isFlipped: false,
            show: false,
            gameMsg: '',
        })
        this.props.shuffleCards
    }

    handleClose() {
        this.setState({
            show: false,
        })
    }
    handleShow() {
        this.setState({
            show: true,
        })
    }

    handleFlip() {
        this.setState({
            isFlipped: true,
            gamesPlayed: +1,
            show: false,
        })

        if (this.props.value !== 2) {
            this.setState({
                gamesLost: 0,
                gameMsg:
                    'It looks like you lost this round. Want to play another?',
            })
        } else if (this.props.value === 2) {
            this.setState({
                gamesWon: 0,
                gameMsg: 'CONGRATULATIONS!!!. Want to win again?',
            })
        }

        setTimeout(() => {
            this.handleShow()
        }, 1000)
    }

    render() {
        const text = this.props.text
        const value = this.props.value
        const isFlipped = this.state.isFlipped

        return (
            <>
                <ReactCardFlip isFlipped={isFlipped} flipDirection="horizontal">
                    <FrontComponent onClick={this.handleFlip} />

                    <BackComponent text={text} value={value} />
                </ReactCardFlip>

                <RetryModal
                    handleShow={this.handleShow}
                    handleClose={this.handleClose}
                    handleReset={this.handleReset}
                    handleRetry={this.handleRetry}
                    show={this.state.show}
                    text={this.state.gameMsg}
                />
            </>
        )
    }
}

export default FlipCard

I included all the code from these two components as I wasn't sure what will help clarify.

Essentially the shuffleCards method needs to run when handleReset and handleRetry are triggered.

Body:
You essentially have 3 problems:

the shuffleCards prop you were passing down was not actually a function, but the result of calling the function that shuffles the cards.

You seem to recognise the above by doing this.props.shuffleCards in the
child component - rather than this.props.shuffleCards() which here
would cause an error since this.props.shuffleCards is not a
function. But that is itself an admission of the problem, because
you clearly need to call a function here, in order to make anything
happen.

The function itself doesn't actually create a new shuffled array, but mutates the old one. Yes, it then returns that, but by returning the old object, even in mutated form, React won't be able to see a change and therefore won't know that the array has been mutated.

So here's how to solve. First, make the card array a state variable in the parent function, and make shuffleCards an actual function, that lives in the parent component (because it needs to access the current cards state), and one that, rather than simply mutating the old array of cards, makes a new array and updates the state with it.

Here's the new parent component, and note that the shuffle and shuffleCards values you've defined outside it are no longer needed or wanted:

const CardGameUI = () => {
    const [shuffledCards, setShuffledCards] = React.useState(cards);

    const shuffleCards = (currentCards) => {
        const array = [...currentCards]; // this makes a (shallow) copy of the array, so it's recognised by React as something new
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1))
            const temp = array[i]
            array[i] = array[j]
            array[j] = temp
        }
        setShuffledCards(array);
    };

    return (
        <div className="cards-ui">
            {shuffledCards.map(card => (
                <FlipCard
                    key={card.id}
                    text={card.text}
                    value={card.id}
                    shuffleCards={shuffleCards}
                />
            ))}
        </div>
    )
}

And then you need to update the child component so that it actually calls this state-updating function, by changing as I indicated in point 2) above: replace this.props.shuffleCards with this.props.shuffleCards().

The cards should now be correctly shuffled when the appropriate actions are taken in the child component. (And let me know if anything still doesn't work as intended - I haven't actually tested this out.)


来源: stackexchange

问:
Google Cloud Run route traffic to a specific domain using static IP
I have a cloud run service, which sends requests to a number of domains:

domain1.com

domain2.com

domain3.com

domain3.com requires that all my requests are coming from the same static IP address

Is this possible to do so in cloud run?

I've found a guide on how to set up static outbound IP address.  But I don't really understand whether it is possible to do that only for one specific domain.

If I understand correctly, it should be done (if possible) somewhere on the Cloud NAT level.

Also, I guess that I would need to first "explore" an IP address of the domain3.com in order to use that address in Cloud NAT.

答:
From a Cloud Run service, you can't use a specific IP to reach only one domain and not the others.

On a Cloud Run service, you can plug a serverless VPC connector to route all the traffic in that connector (I assume that your domain.com are public domain, therefore the all parameter for the egress), and add a Cloud NAT to use your reserved IP(s). (here in the documentation)

Because you route ALL the traffic, you can't select for that domain (or IP) and not this one. It's ALL!

ContentLicense: CC BY-SA 4.0


问:
Making an image stay at the bottom of the page but not go over content
I have an a logo image that is supposed to remain at the bottom of a nav drawer. The only way I know to have it be at the bottom is with the absolute and bottom properties, but that's causing it to overlap the list items on a short device (shrink the height of the browser window until scroll bar appears). As soon as the scroll bars appear, the logo will go over top of the list items.

Here's my sandbox with a drawer and random fake image: https://codesandbox.io/s/drawer-with-image-at-bottom-xpuhp

Is there a way to start it at the bottom without using absolute? And/or a way keep it at the bottom until the window height necessitates scroll bars and then have it be part of that scrollable content behavior? If that makes sense. I've played around with variations of flex properties, but I don't really understand it. If I remove absolute it starts way up under the last list item in drawer and I need it at the bottom until scrollbar.

my css for the img:

```<code>logo: {
      width: "220px",
      height: "150px",
      marginLeft: "50px",
      marginRight: "50px",
      bottom: "24px",
      position: "absolute"
    }
</code>```

thanks

答:
What I would use is a wrapper (in this example with the class container) that has a display of flex. The children (a list and your image) should be on the vertical axis, therefore use flex-direction: column; so your main axis is vertical. And because you want your first child (your list) at the beginning and your last child at the end (your image) you can use justify-content: space-between;. This will distribute your items evenly, with your first item at the start and last item at the end. Flex may be hard to understand at first, but it is very powerful. Some information that might help:

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox
and https://css-tricks.com/snippets/css/a-guide-to-flexbox/.

Here's an example of what I wrote about (open in a full page and resize to see the effect):

html,
body {
  height: 100%;
  margin: 0;
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  /* You can leave this out or change it to 100% depending on your situation*/
  width: 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <ul>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
  </ul>
  <img src="https://www.placecage.com/300/200" alt="">
</div></code>```

Body:
I have an a logo image that is supposed to remain at the bottom of a nav drawer. The only way I know to have it be at the bottom is with the absolute and bottom properties, but that's causing it to overlap the list items on a short device (shrink the height of the browser window until scroll bar appears). As soon as the scroll bars appear, the logo will go over top of the list items.

Here's my sandbox with a drawer and random fake image: https://codesandbox.io/s/drawer-with-image-at-bottom-xpuhp

Is there a way to start it at the bottom without using absolute? And/or a way keep it at the bottom until the window height necessitates scroll bars and then have it be part of that scrollable content behavior? If that makes sense. I've played around with variations of flex properties, but I don't really understand it. If I remove absolute it starts way up under the last list item in drawer and I need it at the bottom until scrollbar.

my css for the img:

logo: {
      width: "220px",
      height: "150px",
      marginLeft: "50px",
      marginRight: "50px",
      bottom: "24px",
      position: "absolute"
    }

thanks

Body:
What I would use is a wrapper (in this example with the class container) that has a display of flex. The children (a list and your image) should be on the vertical axis, therefore use flex-direction: column; so your main axis is vertical. And because you want your first child (your list) at the beginning and your last child at the end (your image) you can use justify-content: space-between;. This will distribute your items evenly, with your first item at the start and last item at the end. Flex may be hard to understand at first, but it is very powerful. Some information that might help:

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox
and https://css-tricks.com/snippets/css/a-guide-to-flexbox/.

Here's an example of what I wrote about (open in a full page and resize to see the effect):

html,
body {
  height: 100%;
  margin: 0;
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  /* You can leave this out or change it to 100% depending on your situation*/
  width: 300px;
}

<div class="container">
  <ul>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
    <li>List item</li>
  </ul>
  <img src="https://www.placecage.com/300/200" alt="">
</div>


问:
Delegate Nic(.ar) domain name to vps or domain host
I've bought a .com.ar domain from nic.ar, just to claim a domain before starting the publicity campaign of a project.

I was trying to setup a MX record to forward emails from the domain to a google account, when realized there's no dns record management panel in nic.ar, as it isn't a domain host. I can instead delegate the domain to a nameserver, and specify an ipv4 and ipv6.

I can't get to understand what I've to do next. I've my own VPS, should I delegate the domain to the VPS, using my hosting service's nameservers? If so, how should I manage the dns records from the host? I'm used to work with nginx to handle server's traffic, but once the request reaches the server it has already resolved all the domains involved. Is there something like a 'domain proxy'?

Can I somehow evade manual configuration of the domain host by 'masking' this domain to another domain properly hosted in websites like hostinger, freenom, namecheap, etc?

Sorry if I'm messing things up, the whole concept of a domain host being separated from the actual domain name did totally lost me.

答:
I have many domains registered through donweb (because it also allows me to pay in Argentine pesos) and, although by default they place their NS, you can change them whenever you want from your customer panel. It is even possible to do it with .COM.AR and .AR domains

When you register a domain with them, they also provide you with a DNS zone and you can add, remove and modify the records. In that case you don't need a separate DNS service.


问:
Observing changes of derived properties: CALayer KVO example
Is there a way to observe changes in derived properties?  For example, I want to know when a CALayer has been added as a sublayer so that I can adjust its geometry relative to its (new) parent.

So, I have a subclassed CALayer, say CustomLayer, and I figured I could register an observer  for the property in init:

```<code>[self addObserver:self forKeyPath:@"superlayer" options:0 context:nil]
</code>```

and implement observeValueForKeyPath:ofObject:change:context.  Nothing ever happens because, presumably, superlayer is a derived property (the attr dictionary stores an opaque ID for the parent).  Similarly, I can't subclass setSuperlayer: because it is never called.  In fact, as far as I can tell there are no instance methods called or public properties set on the sublayer when a parent does [self addSublayer:aCustomLayer].

Then I thought, OK, I'll subclass addSublayer like this:

```<code>- (void)addSublayer:(CALayer *)aLayer {
    [aLayer willChangeValueForKey:@"superlayer"];
    [super addSublayer:aLayer];
    [aLayer didChangeValueForKey:@"superlayer"];
}
</code>```

but still nothing!  (Perhaps it's a clue that when I make a simple standalone test class and use the will[did]ChangeValueForKey: then it works.)  This is maybe a more general Cocoa KVO question.  What should I be doing?  Thanks in advance!

答:
Well, superlayer is defined as a readonly property, which means that there's no setSuperlayer: method. (If there is, it would be private, and you probably shouldn't use it.) If I had to make a guess, it would be that the superlayer property just isn't KVO-compliant. And, aside from that, I generally don't think it's a good idea for classes to observe themselves.

Maybe there's another way of doing this. When a layer is added to a superlayer, the onOrderIn action takes place. Now, actionForKey: is an instance method that gives a layer an opportunity to customize the default animations for certain properties. You could override actionForKey: to detect when the onOrderIn action takes place, do your thing, then call super's implementation.

I consider this a pretty messy hack, too, though. But it should be a bit more "self-contained" than having to use custom layers for everything and messing with KVO messages.

OwnerDisplayName: dk

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to observe changes in derived properties?  For example, I want to know when a CALayer has been added as a sublayer so that I can adjust its geometry relative to its (new) parent.

So, I have a subclassed CALayer, say CustomLayer, and I figured I could register an observer  for the property in init:

[self addObserver:self forKeyPath:@"superlayer" options:0 context:nil]

and implement observeValueForKeyPath:ofObject:change:context.  Nothing ever happens because, presumably, superlayer is a derived property (the attr dictionary stores an opaque ID for the parent).  Similarly, I can't subclass setSuperlayer: because it is never called.  In fact, as far as I can tell there are no instance methods called or public properties set on the sublayer when a parent does [self addSublayer:aCustomLayer].

Then I thought, OK, I'll subclass addSublayer like this:

- (void)addSublayer:(CALayer *)aLayer {
    [aLayer willChangeValueForKey:@"superlayer"];
    [super addSublayer:aLayer];
    [aLayer didChangeValueForKey:@"superlayer"];
}

but still nothing!  (Perhaps it's a clue that when I make a simple standalone test class and use the will[did]ChangeValueForKey: then it works.)  This is maybe a more general Cocoa KVO question.  What should I be doing?  Thanks in advance!

OwnerDisplayName: Alex


问:
Trying to compare return values to list
randomgenerator() is a function that yields 6 random integers, the user is prompted to also enter 6 values which are added to lucky[].
I want to compare each yield value to the lucky[] list for a match, but the if condition is not being met.

for x in randomgenerator():
      print(f"\n{x} is a winning number.")
      if x in lucky:
           print(f"There is a match with number {x}")
           match.append(x)
```
```def randomgenerator():
    for i in range(5):
        yield random.randint(1,2)
    yield random.randint(1,2)
```

答:
You said randomgenerator returns a tuple containing ints.

randomgenerator() is a function that yields 6 random values

I guess by "values" you meant integers, since it's very strange to generate random strings.

Then lucky is filled with input() returned values, which are strings.

```<code>if str(x) in lucky: # This should work, since it will convert the int x to a string
</code>```

a similar solution would be:

```<code>lucky = list(map(int, lucky)) # all the elements are converted to integers
</code>```

Title: Trying to compare return values to list

Body:
randomgenerator() is a function that yields 6 random integers, the user is prompted to also enter 6 values which are added to lucky[].
I want to compare each yield value to the lucky[] list for a match, but the if condition is not being met.

for x in randomgenerator():
      print(f"\n{x} is a winning number.")
      if x in lucky:
           print(f"There is a match with number {x}")
           match.append(x)

def randomgenerator():
    for i in range(5):
        yield random.randint(1,2)
    yield random.randint(1,2)

Body:
You said randomgenerator returns a tuple containing ints.

randomgenerator() is a function that yields 6 random values

I guess by "values" you meant integers, since it's very strange to generate random strings.

Then lucky is filled with input() returned values, which are strings.

if str(x) in lucky: # This should work, since it will convert the int x to a string

a similar solution would be:

lucky = list(map(int, lucky)) # all the elements are converted to integers


问:
Validating Input C++
```<code>int num = 0;

while(true){
  cout << "enter num: ";
  cin >> num;
  if(!(num)){
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "num must be an int" << endl;
  }else if(num <= 0){
    cout << "num must be greater than 0" << endl;
  }else if(static_cast<double>(static_cast<int>(num)) != num){
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "num must be an int" << endl;
  }else{
    break;
  };
};
</code>```

I've been looking through SO and I found some threads that addressed similar issues, but nothing that is specific to what I'm trying to achieve. I'm only trying to accept integer inputs, no decimals, no strings, no characters. If I enter in a negative number or 0, it'll throw me an error saying "num must be greater than 0." If I enter in a, it'll throw me an error saying "num must be an int." If I enter 1.0, it'll throw me an error saying "num must be an int."

The problems I'm running into with this is when I enter in 0 for example, instead of executing the conditional statement that checks (num <= 0), it runs the conditional statement that says (!(num)). The other problem I'm running into is when I enter in a value that has a decimal, like 2.0, it'll truncate the numbers after the decimal and send in 2 as the value, completely glossing over the check to see if it's a decimal value and telling the program that it's a valid integer when it's not.

Does anyone have a solution for this, or an article link that solves problem like mines? Thank you!

答:
This:

```<code>cin >> num;
if(!(num))
</code>```

Should be this:

```<code>if (!(cin >> num))
</code>```

You are checking the value of num when you should instead be checking the error state of cin.  operator>> returns a reference to the input stream, which is then implicitly convertible to bool, where false means the stream encountered an error.

Also, this is completely useless:

```<code>else if(static_cast<double>(static_cast<int>(num)) != num)
</code>```

Casting an int value to an int is a no-op, and casting an int value to a double back to an int will get you the original int value.

num is an int, it can't read in anything else.  So, by the time your code reaches this point, you know num must be holding a valid int value.  However, if the user had actually entered a floating-point number instead, operator>> would have stopped reading at the decimal point, leaving it and the remaining fractional value in cin's input buffer for later reading.

Also, the 2nd call to cin.ignore() is wrong.  By that point, operator>> was able to read in an int value, it just wasn't satisfactory to you.  So don't ignore subsequent input yet.

If you really need to differentiate between integer and floating-point input, you will have to read in the input as a string first, and then parse it to see what it actually holds, eg:

```<code>int num = 0;
string s;
size_t pos;

while (true){
  cout << "enter num: ";
  if (!(cin >> s)){
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "input error, try again" << endl;
  }
  else{
    try{
      num = stoi(s, &pos);
      if (pos != s.size()) throw invalid_argument("");
      if (num > 0){
        break;
      }
      cout << "num must be greater than 0" << endl;
    }
    catch (const exception &){
      cout << "num must be an int" << endl;
    }
  }
}
</code>```

Online Demo

Title: Validating Input C++

Body:
int num = 0;

while(true){
  cout << "enter num: ";
  cin >> num;
  if(!(num)){
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "num must be an int" << endl;
  }else if(num <= 0){
    cout << "num must be greater than 0" << endl;
  }else if(static_cast<double>(static_cast<int>(num)) != num){
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "num must be an int" << endl;
  }else{
    break;
  };
};

I've been looking through SO and I found some threads that addressed similar issues, but nothing that is specific to what I'm trying to achieve. I'm only trying to accept integer inputs, no decimals, no strings, no characters. If I enter in a negative number or 0, it'll throw me an error saying "num must be greater than 0." If I enter in a, it'll throw me an error saying "num must be an int." If I enter 1.0, it'll throw me an error saying "num must be an int."

The problems I'm running into with this is when I enter in 0 for example, instead of executing the conditional statement that checks (num <= 0), it runs the conditional statement that says (!(num)). The other problem I'm running into is when I enter in a value that has a decimal, like 2.0, it'll truncate the numbers after the decimal and send in 2 as the value, completely glossing over the check to see if it's a decimal value and telling the program that it's a valid integer when it's not.

Does anyone have a solution for this, or an article link that solves problem like mines? Thank you!

Body:
This:

cin >> num;
if(!(num))

Should be this:

if (!(cin >> num))

You are checking the value of num when you should instead be checking the error state of cin.  operator>> returns a reference to the input stream, which is then implicitly convertible to bool, where false means the stream encountered an error.

Also, this is completely useless:

else if(static_cast<double>(static_cast<int>(num)) != num)

Casting an int value to an int is a no-op, and casting an int value to a double back to an int will get you the original int value.

num is an int, it can't read in anything else.  So, by the time your code reaches this point, you know num must be holding a valid int value.  However, if the user had actually entered a floating-point number instead, operator>> would have stopped reading at the decimal point, leaving it and the remaining fractional value in cin's input buffer for later reading.

Also, the 2nd call to cin.ignore() is wrong.  By that point, operator>> was able to read in an int value, it just wasn't satisfactory to you.  So don't ignore subsequent input yet.

If you really need to differentiate between integer and floating-point input, you will have to read in the input as a string first, and then parse it to see what it actually holds, eg:

int num = 0;
string s;
size_t pos;

while (true){
  cout << "enter num: ";
  if (!(cin >> s)){
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "input error, try again" << endl;
  }
  else{
    try{
      num = stoi(s, &pos);
      if (pos != s.size()) throw invalid_argument("");
      if (num > 0){
        break;
      }
      cout << "num must be greater than 0" << endl;
    }
    catch (const exception &){
      cout << "num must be an int" << endl;
    }
  }
}

Online Demo


问:
SQL column of sums of multiple rows while keeping all rows?
So I have a query select that outputs something like this:
(the actual results I'm working with is much more complicated but these are the important parts)

```<code>id   trans
123   5.00
124   6.00
124   7.00
125   8.00
125   9.00
</code>```

I want to create a result like this:

```<code>id   trans  total
123   5.00   5.00
124   6.00  13.00
124   7.00  13.00
125   8.00  17.00
125   9.00  17.00
</code>```

Basically I want to add a column that contains a total of all the transactions for each id, while still showing all the transactions. I think the solution will have something to do with group by, nested selects and the sum function but I can't get it right.

答:
A windowed function works well for this scenario:

```<code>select
  *
  ,sum(trans) over(partition by id) as total
from
  myTable
</code>```

SqlFiddle Example

Body:
So I have a query select that outputs something like this:
(the actual results I'm working with is much more complicated but these are the important parts)

id   trans
123   5.00
124   6.00
124   7.00
125   8.00
125   9.00

I want to create a result like this:

id   trans  total
123   5.00   5.00
124   6.00  13.00
124   7.00  13.00
125   8.00  17.00
125   9.00  17.00

Basically I want to add a column that contains a total of all the transactions for each id, while still showing all the transactions. I think the solution will have something to do with group by, nested selects and the sum function but I can't get it right.

Body:
A windowed function works well for this scenario:

select
  *
  ,sum(trans) over(partition by id) as total
from
  myTable

SqlFiddle Example


问:
JavaScript audio.play() error
my code stopped working today (it worked before).

Here is my code:

```<code>playMe = new Audio(link);
playMe.play();
</code>```

Here is the error I get in the console:

```<code>Uncaught (in promise) DOMException: Failed to load because no supported source was found.
</code>```

It is really the audio.play(); that doesn't work because if I only keep the first line I don't get an error (but obviously is dos't play).

I'm using chrome 52.0.2743.82 m (64-bit)

Thanks.

答:
I had the exact problem as you.

I tried playing a <audio> html element and it worked!

So I thought that maybe...

The only thing you should do is to append playMe to body...

var play_me = new Audio("music.mp3");
document.body.appendChild(play_me);
play_me.play();
```

But don't worry the play_me isn't visible.

ContentLicense: CC BY-SA 3.0

Title: JavaScript audio.play() error

Body:
my code stopped working today (it worked before).

Here is my code:

playMe = new Audio(link);
playMe.play();

Here is the error I get in the console:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

It is really the audio.play(); that doesn't work because if I only keep the first line I don't get an error (but obviously is dos't play).

I'm using chrome 52.0.2743.82 m (64-bit)

Thanks.

Body:
I had the exact problem as you.

I tried playing a <audio> html element and it worked!

So I thought that maybe...

The only thing you should do is to append playMe to body...

var play_me = new Audio("music.mp3");
document.body.appendChild(play_me);
play_me.play();

But don't worry the play_me isn't visible.


答:
Generally speaking, you want:

```<code>SUM(value) OVER (PARTITION BY group)
</code>```

If the first output is from this:

```<code>SELECT id, SUM(col) AS trans
FROM table
GROUP BY id;
</code>```

Then you need this:

```<code>SELECT id, SUM(col) AS trans, SUM(SUM(col)) OVER (PARTITION BY id) AS id_total
FROM table
GROUP BY id;
</code>```

If the first output is from this:

```<code>SELECT id, trans
FROM table;
</code>```

Then you need this:

```<code>SELECT id, trans, SUM(trans) OVER (PARTITION BY id) AS id_total
FROM table;
</code>```

Title: SQL column of sums of multiple rows while keeping all rows?

Body:
Generally speaking, you want:

SUM(value) OVER (PARTITION BY group)

If the first output is from this:

SELECT id, SUM(col) AS trans
FROM table
GROUP BY id;

Then you need this:

SELECT id, SUM(col) AS trans, SUM(SUM(col)) OVER (PARTITION BY id) AS id_total
FROM table
GROUP BY id;

If the first output is from this:

SELECT id, trans
FROM table;

Then you need this:

SELECT id, trans, SUM(trans) OVER (PARTITION BY id) AS id_total
FROM table;


问:
ant warning: "'includeantruntime' was not set"
I receive the following warning:

```<code>[javac] build.xml:9: warning: 'includeantruntime' was not set,
defaulting to build.sysclasspath=last; set to false for repeatable builds
</code>```

What does this mean?

答:
The answer from Daniel works just perfect. Here is a sample snippet that I added to my build.xml:

<target name="compile">
    <mkdir dir="${classes.dir}"/>
    <javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false">

        <classpath>
            <path id="application" location="${jar.dir}/${ant.project.name}.jar"/>
            <path id="junit" location="${lib.dir}/junit-4.9b2.jar"/>
        </classpath>
    </javac>
</target>
```

Body:
I receive the following warning:

[javac] build.xml:9: warning: 'includeantruntime' was not set,
defaulting to build.sysclasspath=last; set to false for repeatable builds

What does this mean?

Body:
The answer from Daniel works just perfect. Here is a sample snippet that I added to my build.xml:

<target name="compile">
    <mkdir dir="${classes.dir}"/>
    <javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false">
                                                 <!--   ^^^^^^^^^^^^^^^^^^^^^^^^^  -->
        <classpath>
            <path id="application" location="${jar.dir}/${ant.project.name}.jar"/>
            <path id="junit" location="${lib.dir}/junit-4.9b2.jar"/>
        </classpath>
    </javac>
</target>


问:
Python combinations without repetitions
I have a list of numbers and I want to make combinations from it. If I have list:

```<code>t = [2,2,2,2,4]
c = list(itertools.combinations(t, 4))
</code>```

The result is:

```<code>(2, 2, 2, 2)
(2, 2, 2, 4)
(2, 2, 2, 4)
(2, 2, 2, 4)
(2, 2, 2, 4)
</code>```

but I want to get:

```<code>(2, 2, 2, 2)
(2, 2, 2, 4)
</code>```

Is it possible to eliminate duplicates except making new list and going through first list?

答:
This can now be done using the package more-itertools which, as of version 8.7, has a function called distinct_combinations to achieve this.

```<code>>>> from itertools import combinations
>>> t = [2,2,2,2,4]
>>> set(combinations(t, 4))
{(2, 2, 2, 2), (2, 2, 2, 4)}

>>> from more_itertools import distinct_combinations
>>> t = [2,2,2,2,4]
>>> list(distinct_combinations(t,4))
(2, 2, 2, 2), (2, 2, 2, 4)]
</code>```

As far as I can tell with my very limited testing performance is similar to the function written by @hahho

Title: Python combinations without repetitions

Body:
I have a list of numbers and I want to make combinations from it. If I have list:

t = [2,2,2,2,4]
c = list(itertools.combinations(t, 4))

The result is:

(2, 2, 2, 2)
(2, 2, 2, 4)
(2, 2, 2, 4)
(2, 2, 2, 4)
(2, 2, 2, 4)

but I want to get:

(2, 2, 2, 2)
(2, 2, 2, 4)

Is it possible to eliminate duplicates except making new list and going through first list?

Body:
This can now be done using the package more-itertools which, as of version 8.7, has a function called distinct_combinations to achieve this.

>>> from itertools import combinations
>>> t = [2,2,2,2,4]
>>> set(combinations(t, 4))
{(2, 2, 2, 2), (2, 2, 2, 4)}

>>> from more_itertools import distinct_combinations
>>> t = [2,2,2,2,4]
>>> list(distinct_combinations(t,4))
(2, 2, 2, 2), (2, 2, 2, 4)]

As far as I can tell with my very limited testing performance is similar to the function written by @hahho


问:
MySQLdb._exceptions.OperationalError: (1698, "Access denied for user 'root'@'localhost'")
When I ran a SQL python script it occurred these errors

```<code>MySQLdb._exceptions.OperationalError: (1698, "Access denied for user 'root'@'localhost'")
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1698, "Access denied for user 'root'@'localhost'")
(Background on this error at: http://sqlalche.me/e/13/e3q8)
</code>```

I looked in the mysql.user table and get the following:

```<code>+------------------+-----------+-----------------------+
| User             | Host      | plugin                |
+------------------+-----------+-----------------------+
| debian-sys-maint | localhost | caching_sha2_password |
| mysql.infoschema | localhost | caching_sha2_password |
| mysql.session    | localhost | caching_sha2_password |
| mysql.sys        | localhost | caching_sha2_password |
| root             | localhost | auth_socket           |
+------------------+-----------+-----------------------+
</code>```

答:
I just had the same problem with MariaDB and found myself here expectating some answers, but no lucky. After some research I did an workaround, and judging by the similarities in both DB managers, I think it will help anyone having this problem too. I'm somewhat newbie so I can't explain the technical stuff behind it but its the default for how mySQL(in my case MariaDB) works.

What I did was create a user on the DB manager (mySQL or MariaDB) for my user on linux and, for don't potentially expose my password having to pass it to the script, I used the authentication plugin 'unix_socket' so you don't need a password at all (of course it's only for linux users):

```<code>MySQL -u root
CREATE USER user@localhost IDENTIFIED VIA 'unix_socket';
</code>```

Then grant privileges to your new user:

```<code>GRANT ALL ON database_name.* TO user@localhost WITH GRANT OPTION;
</code>```

If you want to connect remotely change 'localhost' to '%'; and if you are not a linux user I think you can create a user with a password and pass it to sqlalchemy and it will work.

OBS: I'm not sure but I think the problem is that 'root' uses both the 'unix_socket' and 'mysql_native_password' authentication plugins to increase security.

Body:
When I ran a SQL python script it occurred these errors

MySQLdb._exceptions.OperationalError: (1698, "Access denied for user 'root'@'localhost'")
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1698, "Access denied for user 'root'@'localhost'")
(Background on this error at: http://sqlalche.me/e/13/e3q8)

I looked in the mysql.user table and get the following:

+------------------+-----------+-----------------------+
| User             | Host      | plugin                |
+------------------+-----------+-----------------------+
| debian-sys-maint | localhost | caching_sha2_password |
| mysql.infoschema | localhost | caching_sha2_password |
| mysql.session    | localhost | caching_sha2_password |
| mysql.sys        | localhost | caching_sha2_password |
| root             | localhost | auth_socket           |
+------------------+-----------+-----------------------+

Body:
I just had the same problem with MariaDB and found myself here expectating some answers, but no lucky. After some research I did an workaround, and judging by the similarities in both DB managers, I think it will help anyone having this problem too. I'm somewhat newbie so I can't explain the technical stuff behind it but its the default for how mySQL(in my case MariaDB) works.

What I did was create a user on the DB manager (mySQL or MariaDB) for my user on linux and, for don't potentially expose my password having to pass it to the script, I used the authentication plugin 'unix_socket' so you don't need a password at all (of course it's only for linux users):

MySQL -u root
CREATE USER user@localhost IDENTIFIED VIA 'unix_socket';

Then grant privileges to your new user:

GRANT ALL ON database_name.* TO user@localhost WITH GRANT OPTION;

If you want to connect remotely change 'localhost' to '%'; and if you are not a linux user I think you can create a user with a password and pass it to sqlalchemy and it will work.

OBS: I'm not sure but I think the problem is that 'root' uses both the 'unix_socket' and 'mysql_native_password' authentication plugins to increase security.


问:
I've performed a JOIN using bigrquery and the dbGetQuery function. Now I'd like to query the temporary table I've created but can't connect
I'm afraid that if a bunch of folks start running my actual code I'll be billed for the queries so my example code is for a fake database.

I've successfully established my connection to BigQuery:

```<code>con <- dbConnect(
  bigrquery::bigquery(),
  project = 'myproject',
  dataset = 'dataset',
  billing = 'myproject'
)
</code>```

Then performed a LEFT JOIN using the coalesce function:

```<code>    dbGetQuery(con,
"SELECT
  `myproject.dataset.table_1x`.Pokemon,
  coalesce(`myproject.dataset.table_1`.Type_1,`myproject.dataset.table_2`.Type_1) AS Type_1,
  coalesce(`myproject.dataset.table_1`.Type_2,`myproject.dataset.table_2`.Type_2) AS Type_2,
  `myproject.dataset.table_1`.Total,
  `myproject.dataset.table_1`.HP,
  `myproject.dataset.table_1`.Attack,
  `myproject.dataset.table_1`.Special_Attack,
  `myproject.dataset.table_1`.Defense,
  `myproject.dataset.table_1`.Special_Defense,
  `myproject.dataset.table_1`.Speed,
FROM `myproject.dataset.table_1`
LEFT JOIN `myproject.dataset.table_2`
  ON `myproject.dataset.table_1`.Pokemon = `myproject.dataset.table_2`.Pokemon
ORDER BY `myproject.dataset.table_1`.ID;")
</code>```

The JOIN produced the table I intended and now I'd like to query that table but like...where is it? How do I connect? Can I save it locally so that I can start working my analysis in R? Even if I go to BigQuery, select the Project History tab, select the query I just ran in RStudio, and copy the Job ID for the temporary table, I still get the following error:

```<code>Error: Job 'poke-340100.job_y0IBocmd6Cpy-irYtNdLJ-mWS7I0.US' failed
x Syntax error: Unexpected string literal 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae' at [2:6] [invalidQuery]
Run `rlang::last_error()` to see where the error occurred.
</code>```

And if I follow up:

```<code>Run `rlang::last_error()` to see where the error occurred.
> rlang::last_error()
<error/rlang_error>
Job 'poke-340100.job_y0IBocmd6Cpy-irYtNdLJ-mWS7I0.US' failed
x Syntax error: Unexpected string literal 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae' at [2:6] [invalidQuery]
Backtrace:
 1. DBI::dbGetQuery(con, "SELECT *\nFROM 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae'\nWHERE Type_1 IS NULL;")
 2. DBI::dbGetQuery(con, "SELECT *\nFROM 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae'\nWHERE Type_1 IS NULL;")
 3. DBI:::.local(conn, statement, ...)
 5. bigrquery::dbSendQuery(conn, statement, ...)
 6. bigrquery:::BigQueryResult(conn, statement, ...)
 7. bigrquery::bq_job_wait(job, quiet = conn@quiet)
Run `rlang::last_trace()` to see the full context.
> rlang::last_trace()
<error/rlang_error>
Job 'poke-340100.job_y0IBocmd6Cpy-irYtNdLJ-mWS7I0.US' failed
x Syntax error: Unexpected string literal 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae' at [2:6] [invalidQuery]
Backtrace:
    x
 1. +-DBI::dbGetQuery(con, "SELECT *\nFROM 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae'\nWHERE Type_1 IS NULL;")
 2. \-DBI::dbGetQuery(con, "SELECT *\nFROM 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae'\nWHERE Type_1 IS NULL;")
 3.   \-DBI:::.local(conn, statement, ...)
 4.     +-DBI::dbSendQuery(conn, statement, ...)
 5.     \-bigrquery::dbSendQuery(conn, statement, ...)
 6.       \-bigrquery:::BigQueryResult(conn, statement, ...)
 7.         \-bigrquery::bq_job_wait(job, quiet = conn@quiet)
</code>```

Can someone please explain? Is it just that I can't query a temporary table with the bigrquery package?

答:
From looking at the documentation here and here, the problem might just be that you did not assign the results anywhere.

local_df = dbGetQuery(...
```
<p>should take the results from your database query and copy them into local R memory. Take care as there is no check for the size of the results, so it is easy to run out of memory in when doing this.</p>
<hr />
<p>You have tagged the question with dbplyr, but it looks like you are just using the DBI package. If you want to be writing R and have it translated to SQL, then you can do this using dbplyr. It would look something like this:</p>
<pre class="lang-r prettyprint-override"><code>con <- dbConnect(...) # your connection details here

remote_tbl1 = tbl(con, from = "table_1")
remote_tbl2 = tbl(con, from = "table_2")

new_remote_tbl = remote_tbl1 %>%
  left_join(remote_tbl2, by = "Pokemon", suffix = c("",".y")) %>%
  mutate(Type_1 = coalesce(Type_1, Type_1.y),
         Type_2 = coalesce(Type_2, Type_2.y)) %>%
  select(ID, Pokemon, Type_1, Type_2, ...) %>% # list your return columns
  arrange(ID)
</code>```

When you use this approach, new_remote_tbl can be thought of as a new table in the database which you can query and manipulate further. (It is not actually a table - no data was saved to disc - but you can query it and interact with it as if it were and the database will produce it for you on demand).

There are some limitations of working with a remote table (the biggest is you are limited to commands that dbplyr can translate into SQL). When you want to copy the current remote table into local R memory, use collect:

local_df = remote_df %>%
  collect()
```

Body:
I'm afraid that if a bunch of folks start running my actual code I'll be billed for the queries so my example code is for a fake database.

I've successfully established my connection to BigQuery:

con <- dbConnect(
  bigrquery::bigquery(),
  project = 'myproject',
  dataset = 'dataset',
  billing = 'myproject'
)

Then performed a LEFT JOIN using the coalesce function:

    dbGetQuery(con,
"SELECT
  `myproject.dataset.table_1x`.Pokemon,
  coalesce(`myproject.dataset.table_1`.Type_1,`myproject.dataset.table_2`.Type_1) AS Type_1,
  coalesce(`myproject.dataset.table_1`.Type_2,`myproject.dataset.table_2`.Type_2) AS Type_2,
  `myproject.dataset.table_1`.Total,
  `myproject.dataset.table_1`.HP,
  `myproject.dataset.table_1`.Attack,
  `myproject.dataset.table_1`.Special_Attack,
  `myproject.dataset.table_1`.Defense,
  `myproject.dataset.table_1`.Special_Defense,
  `myproject.dataset.table_1`.Speed,
FROM `myproject.dataset.table_1`
LEFT JOIN `myproject.dataset.table_2`
  ON `myproject.dataset.table_1`.Pokemon = `myproject.dataset.table_2`.Pokemon
ORDER BY `myproject.dataset.table_1`.ID;")

The JOIN produced the table I intended and now I'd like to query that table but like...where is it? How do I connect? Can I save it locally so that I can start working my analysis in R? Even if I go to BigQuery, select the Project History tab, select the query I just ran in RStudio, and copy the Job ID for the temporary table, I still get the following error:

Error: Job 'poke-340100.job_y0IBocmd6Cpy-irYtNdLJ-mWS7I0.US' failed
x Syntax error: Unexpected string literal 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae' at [2:6] [invalidQuery]
Run `rlang::last_error()` to see where the error occurred.

And if I follow up:

Run `rlang::last_error()` to see where the error occurred.
> rlang::last_error()
<error/rlang_error>
Job 'poke-340100.job_y0IBocmd6Cpy-irYtNdLJ-mWS7I0.US' failed
x Syntax error: Unexpected string literal 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae' at [2:6] [invalidQuery]
Backtrace:
 1. DBI::dbGetQuery(con, "SELECT *\nFROM 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae'\nWHERE Type_1 IS NULL;")
 2. DBI::dbGetQuery(con, "SELECT *\nFROM 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae'\nWHERE Type_1 IS NULL;")
 3. DBI:::.local(conn, statement, ...)
 5. bigrquery::dbSendQuery(conn, statement, ...)
 6. bigrquery:::BigQueryResult(conn, statement, ...)
 7. bigrquery::bq_job_wait(job, quiet = conn@quiet)
Run `rlang::last_trace()` to see the full context.
> rlang::last_trace()
<error/rlang_error>
Job 'poke-340100.job_y0IBocmd6Cpy-irYtNdLJ-mWS7I0.US' failed
x Syntax error: Unexpected string literal 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae' at [2:6] [invalidQuery]
Backtrace:
    x
 1. +-DBI::dbGetQuery(con, "SELECT *\nFROM 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae'\nWHERE Type_1 IS NULL;")
 2. \-DBI::dbGetQuery(con, "SELECT *\nFROM 'poke-340100:US.bquxjob_7c3a7664_17ed44bb4ae'\nWHERE Type_1 IS NULL;")
 3.   \-DBI:::.local(conn, statement, ...)
 4.     +-DBI::dbSendQuery(conn, statement, ...)
 5.     \-bigrquery::dbSendQuery(conn, statement, ...)
 6.       \-bigrquery:::BigQueryResult(conn, statement, ...)
 7.         \-bigrquery::bq_job_wait(job, quiet = conn@quiet)

Can someone please explain? Is it just that I can't query a temporary table with the bigrquery package?

Body:
From looking at the documentation here and here, the problem might just be that you did not assign the results anywhere.

local_df = dbGetQuery(...

should take the results from your database query and copy them into local R memory. Take care as there is no check for the size of the results, so it is easy to run out of memory in when doing this.

You have tagged the question with dbplyr, but it looks like you are just using the DBI package. If you want to be writing R and have it translated to SQL, then you can do this using dbplyr. It would look something like this:

con <- dbConnect(...) # your connection details here

remote_tbl1 = tbl(con, from = "table_1")
remote_tbl2 = tbl(con, from = "table_2")

new_remote_tbl = remote_tbl1 %>%
  left_join(remote_tbl2, by = "Pokemon", suffix = c("",".y")) %>%
  mutate(Type_1 = coalesce(Type_1, Type_1.y),
         Type_2 = coalesce(Type_2, Type_2.y)) %>%
  select(ID, Pokemon, Type_1, Type_2, ...) %>% # list your return columns
  arrange(ID)

When you use this approach, new_remote_tbl can be thought of as a new table in the database which you can query and manipulate further. (It is not actually a table - no data was saved to disc - but you can query it and interact with it as if it were and the database will produce it for you on demand).

There are some limitations of working with a remote table (the biggest is you are limited to commands that dbplyr can translate into SQL). When you want to copy the current remote table into local R memory, use collect:

local_df = remote_df %>%
  collect()


问:
How to coalesce a custom type in Postgres?
I have this custom Postgres field:

```<code>execute("CREATE TYPE public.money_with_currency AS (currency_code char(3), amount numeric);")
</code>```

How can I coalesce a null in this field to a default of "USD', 0?

Here's what I tried:

```<code>SUM(COALESCE(promotional_wallet_transactions.amount, ('USD', 0))) AS promotional_wallet_sums

also tried:

SUM(COALESCE(promotional_wallet_transactions.amount, money_with_currency('USD', 0))) AS promotional_wallet_sums

</code>```

Appreciate the help!

答:
Your attempt with the record in parentheses is almost correct – you are only missing a type cast:

CREATE TYPE public.money_with_currency AS (currency_code char(3), amount numeric);
CREATE TYPE

SELECT COALESCE(null,('USD',0)::money_with_currency);
┌──────────┐
│ coalesce │
├──────────┤
│ (USD,0)  │
└──────────┘
(1 row)
```

Body:
I have this custom Postgres field:

execute("CREATE TYPE public.money_with_currency AS (currency_code char(3), amount numeric);")

How can I coalesce a null in this field to a default of "USD', 0?

Here's what I tried:

SUM(COALESCE(promotional_wallet_transactions.amount, ('USD', 0))) AS promotional_wallet_sums

also tried:

SUM(COALESCE(promotional_wallet_transactions.amount, money_with_currency('USD', 0))) AS promotional_wallet_sums

Appreciate the help!


问:
is this syntax correct in jquery
is the syntax of the jquery correct?

the first two lines in the code of jquery

```<code>$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
</code>```

is two insert data in the forms

the next line is to display all the echoed elements in the server:

```<code>$('#age').html(json).show();//at age part of the html
</code>```

the first two lines inserting elements in the form works fine,but displaying the echo elements does not work fine..is there anything wrong in the code??

Code:

```<code>$(document).ready(function(){
    $("#button1").click(function(){
        $.post(
            'script.php',
            { id: $('input[name="id"]', '#myForm').val() },
            function(json) {
                $("input[name='title']").val(json.title);
                $("input[name='age']").val(json.age);
                $('#age').html(json).show();
            },
            "json"
        );
    });
 });

 <div id="age"></div>
</code>```

答:
$(document).ready(function(){ is missing its closing brackets. Add }); at the end of your javascript.

```<code>$(document).ready(function(){

});
</code>```

Title: is this syntax correct in jquery

Body:
is the syntax of the jquery correct?

the first two lines in the code of jquery

$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);

is two insert data in the forms

the next line is to display all the echoed elements in the server:

$('#age').html(json).show();//at age part of the html

the first two lines inserting elements in the form works fine,but displaying the echo elements does not work fine..is there anything wrong in the code??

Code:

$(document).ready(function(){
    $("#button1").click(function(){
        $.post(
            'script.php',
            { id: $('input[name="id"]', '#myForm').val() },
            function(json) {
                $("input[name='title']").val(json.title);
                $("input[name='age']").val(json.age);
                $('#age').html(json).show();
            },
            "json"
        );
    });
 });

Body:
$(document).ready(function(){ is missing its closing brackets. Add }); at the end of your javascript.

$(document).ready(function(){

});


问:
How to get array with intersected elements?
I have an array, that contains another arrays with string id's. I need to get an array with string ids, that are exists in all arrays of parent.

Here is example:

```<code>const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

//some magic. Maybe use lodash instersection func

console.log(result) => ['test2']
</code>```

Important note! I don't know, how much arrays of elements in parent array, thats the problem that i cant understand how to use lodash intersection function:(

答:
Lodash solution:

const parentArray=[["test1","test2","test3"],["test2","test4","test5"],["test3","test2","test6"]];

const result = parentArray.reduce((acc, arr) => _.intersection(acc, arr));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height: 100%!important; top: 0}</code>```

```

Body:
I have an array, that contains another arrays with string id's. I need to get an array with string ids, that are exists in all arrays of parent.

Here is example:

const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

//some magic. Maybe use lodash instersection func

console.log(result) => ['test2']

Important note! I don't know, how much arrays of elements in parent array, thats the problem that i cant understand how to use lodash intersection function:(

Body:
Lodash solution:

const parentArray=[["test1","test2","test3"],["test2","test4","test5"],["test3","test2","test6"]];

const result = parentArray.reduce((acc, arr) => _.intersection(acc, arr));

console.log(result);

.as-console-wrapper{min-height: 100%!important; top: 0}

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>


问:
SQL Server 2017 STRING_AGG Order By
I'm using SQL Server 2017 Microsoft SQL Server 2017 (RTM-GDR) (KB4583456) - 14.0.2037.2 (X64)   Nov  2 2020 19:19:59   Copyright (C) 2017 Microsoft Corporation  Developer Edition (64-bit) on Windows 10 Pro 10.0  (Build 19042: ).

I'm trying to sort the results of the STRING_AGG function.

This works fine

```<code>SELECT STRING_AGG(Category,', ') AS Result
FROM LegacyReviews_Categories
</code>```

This gives me the error "Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '('."

```<code>SELECT STRING_AGG(Category,', ') WITHIN GROUP ( ORDER BY Category ASC) AS Result
FROM LegacyReviews_Categories
</code>```

答:
I can repro this on SQL Server 2019 build 15.0.4198.2 too.

It just requires the query to be run in the context of a database set to COMPATIBILITY_LEVEL of 100 (2008).

All other (later) compatibility levels work.

The documentation states

STRING_AGG is available in any compatibility level.

And doesn't mention this.

If you are unable to change the compatibility level of the database to something higher then possibly you will need to fall back to the old XML PATH method of concatenating ordered results.

Title: SQL Server 2017 STRING_AGG Order By

Body:
I'm using SQL Server 2017 Microsoft SQL Server 2017 (RTM-GDR) (KB4583456) - 14.0.2037.2 (X64)   Nov  2 2020 19:19:59   Copyright (C) 2017 Microsoft Corporation  Developer Edition (64-bit) on Windows 10 Pro 10.0  (Build 19042: ).

I'm trying to sort the results of the STRING_AGG function.

This works fine

SELECT STRING_AGG(Category,', ') AS Result
FROM LegacyReviews_Categories

This gives me the error "Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '('."

SELECT STRING_AGG(Category,', ') WITHIN GROUP ( ORDER BY Category ASC) AS Result
FROM LegacyReviews_Categories


问:
DD_INSERT in the update strategy transformation
Informatica automatically inserts all the rows to the target...so why do we have to use update strategy transformation (DD_INSERT) to insert the records???</p>

答:
While it is true that insert is the default behavior, it may be changed on session properties. See the Treat Source Rows As property documentation.

Only when you want to build a logic and decide what to do with a particular row, you should use Data Driven property value and then use DD_INSERT and other values according to your needs.


问:
Android Bumblebee NavController drawer menu corrupted
After upgrade do Android Studio Bumblebee and Graddle 7.2 (i belive) and navigation-safe-args-gradle-plugin:2.5.0-alpha01 my navigation component went crazy.

When I open a fragment from option menu it works fine, but when I open fragment from drawer then it somehow "overrides" bottom menu and I cannot open fragment from bottom menu on which I opened fragment from drawer. To "unlock" bottom menu I have to use back arrow, and only after that the fragment from bottom menu can be reopened. I don't have any particular order of fragments in nav_graph. Any fragment can be opened in any order. I want to make bottom menu to workd such way that I can always open 1 of 4 main fragments no matter what other fragment is currently opened - without need of clicking "back".

I have bottom, drawer and options navigation. I have 4 main fragments that are accesible from bottom menu. All other fragments are accesible from options or drawer and all fragments have global action in nav_graph that includes:

```<code>app:popUpTo="@id/homeFragment"
app:popUpToInclusive="true"
</code>```

I want always go to homeFragment inclusive from any other fragment despite of the order of opening fragments
My code:

```<code>val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.findNavController()

// List of fragments without 'back arrow' - accesible from bottom menu
appBarConfiguration = AppBarConfiguration(
    setOf(R.id.homeFragment, R.id.settingsFragment, R.id.logFragment, R.id.mapFragment),
    bind.drawerLayout
)

setSupportActionBar(bind.toolbar)
setupActionBarWithNavController(navController, appBarConfiguration)
bind.bottomNav.setupWithNavController(navController)
bind.drawerView.setupWithNavController(navController)

// Drawer menu
val navView: NavigationView = findViewById(R.id.drawerView)

// Click on item in navigation drawer
navView.menu.findItem(R.id.drawerItemOpen).setOnMenuItemClickListener {
    navController.navigate(R.id.listFragment)
    bind.drawerLayout.close()
    true
}

override fun onSupportNavigateUp(): Boolean { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() }
override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.options_menu, menu) return true }
override fun onOptionsItemSelected(item: MenuItem): Boolean { return item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item) }
</code>```

Is something wrong with this code ?
Thank you

答:
I revert to version 2.3.0

```<code>androidx.navigation:navigation-fragment-ktx:2.3.0
androidx.navigation:navigation-ui-ktx:2.3.0'
</code>```

It seems that newer version 2.4.0 works differently.

I also changed a way of calling navigate action from:

```<code>navController.navigate(R.id.listFragment)
</code>```

to

```<code>navController.navigate(PlanListFragmentDirections.actionGlobalPlanListFragment())
</code>```

Body:
After upgrade do Android Studio Bumblebee and Graddle 7.2 (i belive) and navigation-safe-args-gradle-plugin:2.5.0-alpha01 my navigation component went crazy.

When I open a fragment from option menu it works fine, but when I open fragment from drawer then it somehow "overrides" bottom menu and I cannot open fragment from bottom menu on which I opened fragment from drawer. To "unlock" bottom menu I have to use back arrow, and only after that the fragment from bottom menu can be reopened. I don't have any particular order of fragments in nav_graph. Any fragment can be opened in any order. I want to make bottom menu to workd such way that I can always open 1 of 4 main fragments no matter what other fragment is currently opened - without need of clicking "back".

I have bottom, drawer and options navigation. I have 4 main fragments that are accesible from bottom menu. All other fragments are accesible from options or drawer and all fragments have global action in nav_graph that includes:

app:popUpTo="@id/homeFragment"
app:popUpToInclusive="true"

I want always go to homeFragment inclusive from any other fragment despite of the order of opening fragments
My code:

val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.findNavController()

// List of fragments without 'back arrow' - accesible from bottom menu
appBarConfiguration = AppBarConfiguration(
    setOf(R.id.homeFragment, R.id.settingsFragment, R.id.logFragment, R.id.mapFragment),
    bind.drawerLayout
)

setSupportActionBar(bind.toolbar)
setupActionBarWithNavController(navController, appBarConfiguration)
bind.bottomNav.setupWithNavController(navController)
bind.drawerView.setupWithNavController(navController)

// Drawer menu
val navView: NavigationView = findViewById(R.id.drawerView)

// Click on item in navigation drawer
navView.menu.findItem(R.id.drawerItemOpen).setOnMenuItemClickListener {
    navController.navigate(R.id.listFragment)
    bind.drawerLayout.close()
    true
}

override fun onSupportNavigateUp(): Boolean { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() }
override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.options_menu, menu) return true }
override fun onOptionsItemSelected(item: MenuItem): Boolean { return item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item) }

Is something wrong with this code ?
Thank you

Body:
I revert to version 2.3.0

androidx.navigation:navigation-fragment-ktx:2.3.0
androidx.navigation:navigation-ui-ktx:2.3.0'

It seems that newer version 2.4.0 works differently.

I also changed a way of calling navigate action from:

navController.navigate(R.id.listFragment)

to

navController.navigate(PlanListFragmentDirections.actionGlobalPlanListFragment())


问:
Aggregating data with automatic selection
I am trying to summarize my data. Below you can see my example of data

```<code>data = {'id':['1','2','3','4','5'],
        'name': ['Company1', 'Company1', 'Company3', 'Company4', 'Company5'],
        'employee': [10.2, 3.5, 5, 1, 0],
        'sales': [10, 10, 55, 1, 0],
        'streets':['1a', '3b', 5, 1, 0],
       }
df = pd.DataFrame(data, columns = ['id','name', 'employee','sales','streets'])
</code>```

Now I want to summarize all numerical values from my dataset. I summarize with lines below:

```<code>df = df.groupby(['id','name',]).agg({'employee':sum,
                                    'sales':sum,
                                    }).reset_index()
</code>```

But this is only a small example, usually, I have a dataset with around 10 numerical values to summarize so can anybody help me how to aggregate all of this data in a simple way?

I try with this code below

```<code>df = df.groupby(['id','name',]).agg({df.select_dtypes(include = ['float64', 'int64'])
                                    }).reset_index()
</code>```

but I received error unhashable type: 'DataFrame'

So can anybody help me how to solve this problem?

答:
Maybe a bit late but if you want to use agg, you can also use:

```<code>numeric_cols = df.columns[df.dtypes.isin([float, int])]
out = df.groupby(['id', 'name'], as_index=False)[numeric_cols] \
        .agg({'employee': sum, 'sales': sum})
</code>```

Output:

```<code>>>> out
  id      name  employee  sales
0  1  Company1      10.2     10
1  2  Company1       3.5     10
2  3  Company3       5.0     55
3  4  Company4       1.0      1
4  5  Company5       0.0      0

>>> numeric_cols
Index(['employee', 'sales'], dtype='object')
</code>```

Body:
I am trying to summarize my data. Below you can see my example of data

data = {'id':['1','2','3','4','5'],
        'name': ['Company1', 'Company1', 'Company3', 'Company4', 'Company5'],
        'employee': [10.2, 3.5, 5, 1, 0],
        'sales': [10, 10, 55, 1, 0],
        'streets':['1a', '3b', 5, 1, 0],
       }
df = pd.DataFrame(data, columns = ['id','name', 'employee','sales','streets'])

Now I want to summarize all numerical values from my dataset. I summarize with lines below:

df = df.groupby(['id','name',]).agg({'employee':sum,
                                    'sales':sum,
                                    }).reset_index()

But this is only a small example, usually, I have a dataset with around 10 numerical values to summarize so can anybody help me how to aggregate all of this data in a simple way?

I try with this code below

df = df.groupby(['id','name',]).agg({df.select_dtypes(include = ['float64', 'int64'])
                                    }).reset_index()

but I received error unhashable type: 'DataFrame'

So can anybody help me how to solve this problem?

Body:
Maybe a bit late but if you want to use agg, you can also use:

numeric_cols = df.columns[df.dtypes.isin([float, int])]
out = df.groupby(['id', 'name'], as_index=False)[numeric_cols] \
        .agg({'employee': sum, 'sales': sum})

Output:

>>> out
  id      name  employee  sales
0  1  Company1      10.2     10
1  2  Company1       3.5     10
2  3  Company3       5.0     55
3  4  Company4       1.0      1
4  5  Company5       0.0      0

>>> numeric_cols
Index(['employee', 'sales'], dtype='object')


问:
Object evaluating in java
I don't understand, why Java acts the way it does.

I have two classes,

Class A:

```<code>public class A {
  public String s = null;

  public A(int s) {
    this.s = "a";
  }

  public A(String s) {
    this.s = "b";
  }

  public int f(A p) {
    return 2;
  }
}
</code>```

Class B:

```<code>public class B extends A {
  public String s = "c";
  public B() {
    super(null);
  }
  public B (String s) {
    this (0);
    this . s = s ;
  }
  public B (int x) {
    super ("d");
  this . s = this . s + x ;
  }
  public int f (A p) {
    return 3;
  }
  public int f(B p) {
    return 4;
}
</code>```

If I know have my main class, in which I run the following code:

public class Test {
  Public static main(String[] args) {
    B b1 = new B("g");
    A ab = new B(6);
    System.out.println(ab.f(b1));
  }
}
```

Why am I getting 3 as an result, and not 2 or 4, like I would expect?
Normally I would assume, if I run the method f of the object ab, and give f the object b1 as a parameter, it would either return 2, not compile (since the only method f in Class A uses an Object A and not an Object B) or it would look for another method f in Class B, that uses an Object B as a parameter and would execute that, in which case the program should return 4.

答:
I think it calls your f method in class B that returns 3 because, even though b1 is of class B, class B is a subclass of A.  Since :

```<code>public int f (A p) {
   return 3;
}
</code>```

comes before the other f method, it checks that first.  It says is b1 of type A? And the answer is yes, because all Bs are As. So it uses that function, returns 3 and completes the method call.

Title: Object evaluating in java

Body:
I don't understand, why Java acts the way it does.

I have two classes,

Class A:

public class A {
  public String s = null;

  public A(int s) {
    this.s = "a";
  }

  public A(String s) {
    this.s = "b";
  }

  public int f(A p) {
    return 2;
  }
}

Class B:

public class B extends A {
  public String s = "c";
  public B() {
    super(null);
  }
  public B (String s) {
    this (0);
    this . s = s ;
  }
  public B (int x) {
    super ("d");
  this . s = this . s + x ;
  }
  public int f (A p) {
    return 3;
  }
  public int f(B p) {
    return 4;
}

If I know have my main class, in which I run the following code:

public class Test {
  Public static main(String[] args) {
    B b1 = new B("g");
    A ab = new B(6);
    System.out.println(ab.f(b1));
  }
}

Why am I getting 3 as an result, and not 2 or 4, like I would expect?
Normally I would assume, if I run the method f of the object ab, and give f the object b1 as a parameter, it would either return 2, not compile (since the only method f in Class A uses an Object A and not an Object B) or it would look for another method f in Class B, that uses an Object B as a parameter and would execute that, in which case the program should return 4.

Body:
I think it calls your f method in class B that returns 3 because, even though b1 is of class B, class B is a subclass of A.  Since :

public int f (A p) {
   return 3;
}

comes before the other f method, it checks that first.  It says is b1 of type A? And the answer is yes, because all Bs are As. So it uses that function, returns 3 and completes the method call.


问:
What does the second number in Pester's coverage % mean?
When I run pester I get this output

Covered 100% / 75%. 114 analyzed Commands in 1 File

What does the 75% mean? I haven't been able to find it anywhere in the documentation.

答:
It is the value of $PesterPreference.CodeCoverage.CoveragePercentTarget.Value, i.e the minimum amount of test coverage you want to achieve. This is set to 75% by default.

It's mentioned on the page describing New-PesterConfiguration:

https://pester-docs.netlify.app/docs/commands/New-PesterConfiguration

CoveragePercentTarget: Target percent of code coverage that you want
to achieve, default 75%.   Default value: 75

But it was quite hard to figure out, and it could do with being added to the documentation page about test coverage. I ended up searching through the source code and found that the message you listed is output here:

https://github.com/pester/Pester/blob/1515194f4868f6aaae82d7d376a8a776afe0ebf4/src/functions/Output.ps1

```<code>CoverageMessage   = 'Covered {2:0.##}% / {5:0.##}%. {3:N0} analyzed {0} in {4:N0} {1}.'
</code>```

Which is populated with values here:

```<code>$coverageMessage = $ReportStrings.CoverageMessage -f $command, $file, $executedPercent, $totalCommandCount, $fileCount, $PesterPreference.CodeCoverage.CoveragePercentTarget.Value
</code>```

Body:
It is the value of $PesterPreference.CodeCoverage.CoveragePercentTarget.Value, i.e the minimum amount of test coverage you want to achieve. This is set to 75% by default.

It's mentioned on the page describing New-PesterConfiguration:

https://pester-docs.netlify.app/docs/commands/New-PesterConfiguration

CoveragePercentTarget: Target percent of code coverage that you want
to achieve, default 75%.   Default value: 75

But it was quite hard to figure out, and it could do with being added to the documentation page about test coverage. I ended up searching through the source code and found that the message you listed is output here:

https://github.com/pester/Pester/blob/1515194f4868f6aaae82d7d376a8a776afe0ebf4/src/functions/Output.ps1

CoverageMessage   = 'Covered {2:0.##}% / {5:0.##}%. {3:N0} analyzed {0} in {4:N0} {1}.'

Which is populated with values here:

$coverageMessage = $ReportStrings.CoverageMessage -f $command, $file, $executedPercent, $totalCommandCount, $fileCount, $PesterPreference.CodeCoverage.CoveragePercentTarget.Value


问:
How to store/save Timer/Threads instances running in WCF service
I'm trying to make a simple scheduler service that will automatically send emails, etc.

For now I have simple WCF service in which I create an instance of a timer, set a callback and do some work in the callback. Now this part works fine, with the callback being called and the work in it being done as expected.

The issue is I need to make some change to the timer, say change the interval or maybe just stop it.

But I can't seem to figure out a way to store/get the instance of that timer that I created. As each time I create a new proxy and access the service, I get a new instance of the service...

I know I could use a static variable but that kind of makes it a 'singleton' service, and the service host I am using at the current time does not support that...

So how can I get that instance of a timer/thread that I actually created in a previous call? Or am I just going about this the wrong way?

答: Static isn't all that bad of an idea here. Maybe that static is a dictionary keyed by a Guid and the Guid is returned to the client. Subsequent client calls use the Guid parameter, so new instances of your service lookup the timer using the Guid.</p>


问:
Ruby On Rails 7.0 invalid? set true in console but not in view
I´m trying to avoid to update an empty name for @post.
I´m beginner in RoR and I don´t understand why in terminal I got @post.invalid? => true but in my view edit.html.erb @post.invalid? => false

posts_controller.rb

class PostsController < ApplicationController

  before_action :set_post, :only => [:edit, :show, :update, :destroy]

  def index
    @posts = Post.all
    respond_to do |format|
      format.html
      format.json { render json: @posts }
    end
  end

  def show
    respond_to do |format|
      format.html
      format.json { render json: @post }
    end
  end

  def edit
  end

  def update
    if @post.update(post_params)
      redirect_to posts_path, success: "Post updated"
    else
      puts @post.invalid? # write true
      render 'edit'
    end
  end

  def new
    @post = Post.new
  end

  def create
    post = Post.create(post_params)
    redirect_to post_path(post.id), success: "Post created"
  end

  def destroy
    @post.destroy

    redirect_to posts_path, success: "Post deleted"
  end

  private

  def post_params
    params.require(:post).permit(:name, :content)
  end

  def set_post
    @post = Post.find(params[:id])
  end

end
```
<h2>post.rb</h2>
<pre class="lang-rb prettyprint-override"><code>class Post < ApplicationRecord

  validates :name, presence: true

  def as_json(options = nil)
    super(only: [:name, :id, :created_at] )
  end
end
</code>```

edit.html.erb

Editer l´article

<%= @post.invalid? %>

<% if @post.invalid? %>

    <% @post.errors.full_messages.each do |message| %>
      <%= message %>
    <% end %>

<% end %>

<%= form_for @post do |f| %>

    Titre de l´article
    <%= f.text_field :name, class: 'form-control' %>

    Contenu de l´article
    <%= f.text_area :content, class: 'form-control' %>

    <%= f.submit "Modifier l´article", class: 'btn btn-primary' %>

<% end %>
```

I´m confused, someone has got an idea ?

答:
The solution I found was a combination of @rewritten´s answer and this one.

So...

```<code><h1>Editer l´article</h1>

<% if @post.errors.present? %>
  <div class="alert alert-danger">
    <% @post.errors.full_messages.each do |message| %>
      <%= message %>
    <% end %>
  </div>
<% end %>

<%= form_for @post, data: { turbo: false} do |f| %>
  <div class="form-group">
    <label>Titre de l´article</label>
    <%= f.text_field :name, class: 'form-control' %>
  </div>
  <div class="form-group">
    <label>Contenu de l´article</label>
    <%= f.text_area :content, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.submit "Modifier l´article", class: 'btn btn-primary' %>
  </div>
<% end %>
</code>```

Body:
I´m trying to avoid to update an empty name for @post.
I´m beginner in RoR and I don´t understand why in terminal I got @post.invalid? => true but in my view edit.html.erb @post.invalid? => false

posts_controller.rb

class PostsController < ApplicationController

  before_action :set_post, :only => [:edit, :show, :update, :destroy]

  def index
    @posts = Post.all
    respond_to do |format|
      format.html
      format.json { render json: @posts }
    end
  end

  def show
    respond_to do |format|
      format.html
      format.json { render json: @post }
    end
  end

  def edit
  end

  def update
    if @post.update(post_params)
      redirect_to posts_path, success: "Post updated"
    else
      puts @post.invalid? # write true
      render 'edit'
    end
  end

  def new
    @post = Post.new
  end

  def create
    post = Post.create(post_params)
    redirect_to post_path(post.id), success: "Post created"
  end

  def destroy
    @post.destroy

    redirect_to posts_path, success: "Post deleted"
  end

  private

  def post_params
    params.require(:post).permit(:name, :content)
  end

  def set_post
    @post = Post.find(params[:id])
  end

end

post.rb

class Post < ApplicationRecord

  validates :name, presence: true

  def as_json(options = nil)
    super(only: [:name, :id, :created_at] )
  end
end

edit.html.erb

Editer l´article

<%= @post.invalid? %>

<% if @post.invalid? %>

    <% @post.errors.full_messages.each do |message| %>
      <%= message %>
    <% end %>

<% end %>

<%= form_for @post do |f| %>

    Titre de l´article
    <%= f.text_field :name, class: 'form-control' %>

    Contenu de l´article
    <%= f.text_area :content, class: 'form-control' %>

    <%= f.submit "Modifier l´article", class: 'btn btn-primary' %>

<% end %>

I´m confused, someone has got an idea ?

Body:
The solution I found was a combination of @rewritten´s answer and this one.

So...

<h1>Editer l´article</h1>

<% if @post.errors.present? %>
  <div class="alert alert-danger">
    <% @post.errors.full_messages.each do |message| %>
      <%= message %>
    <% end %>
  </div>
<% end %>

<%= form_for @post, data: { turbo: false} do |f| %>
  <div class="form-group">
    <label>Titre de l´article</label>
    <%= f.text_field :name, class: 'form-control' %>
  </div>
  <div class="form-group">
    <label>Contenu de l´article</label>
    <%= f.text_area :content, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.submit "Modifier l´article", class: 'btn btn-primary' %>
  </div>
<% end %>


问:
How to handle null attributes while fetching data from dynamodb
I have a simple table where primary key is ID and other attributes are name and balance. Now there are some rows where balance can be NULL. When I am fetching those attributes using Lambda function it cannot handle it. I want to handle these cases so that when a NULL attribute is detected it can show some message.</p>
```<code>import json
import boto3
def lambda_handler(event, context):
    client = boto3.resource("dynamodb")
    table = client.Table("demoTable")
    response = table.get_item(
    Key = {
            'ID': '9898'
    }

    )
    item = str(response['Item']['balance'])
    print(item)
</code>```

答:
Your problem is in:

response['Item']['balance']

Generally, using square brackets to access dictionary members (response is a dictionary) is considered a bad practice. You can use it when you're absolutely sure that the item you're trying to get exists, but a better way is to use get() since it can handle situations where the item does not exist.

```<code>response.get('Item', dictionary()).get('balance', 0)
</code>```

In case the item does not exist, or balance is null, you'll get a 0 as a result

Body:
I have a simple table where primary key is ID and other attributes are name and balance. Now there are some rows where balance can be NULL. When I am fetching those attributes using Lambda function it cannot handle it. I want to handle these cases so that when a NULL attribute is detected it can show some message.

import json
import boto3
def lambda_handler(event, context):
    client = boto3.resource("dynamodb")
    table = client.Table("demoTable")
    response = table.get_item(
    Key = {
            'ID': '9898'
    }

    )
    item = str(response['Item']['balance'])
    print(item)

Body:
Your problem is in:

response['Item']['balance']

Generally, using square brackets to access dictionary members (response is a dictionary) is considered a bad practice. You can use it when you're absolutely sure that the item you're trying to get exists, but a better way is to use get() since it can handle situations where the item does not exist.

response.get('Item', dictionary()).get('balance', 0)

In case the item does not exist, or balance is null, you'll get a 0 as a result