问:
React how to resume counter from the moment I stopped
```<code>class Pomodoro extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      breakLength : 5,
      sessionLength : 25,
      clockMode: 'Session',
      clicked: 'timerOff',
      timeMin: '25',
      timeSec: '00'
    }

    this.incBreakLength = this.incBreakLength.bind(this);
    this.decBreakLength = this.decBreakLength.bind(this);
    this.incSessionLength = this.incSessionLength.bind(this);
    this.decSessionLength = this.decSessionLength.bind(this);
    this.handleTimer = this.handleTimer.bind(this);
    this.onTimer = this.onTimer.bind(this);
    this.offTimer = this.offTimer.bind(this);
    this.init = this.init.bind(this);
  }

  incBreakLength() {
    this.state.breakLength >= 60 ?
      this.setState({
        breakLength: 60
      })
    :
      this.setState({
        breakLength: this.state.breakLength + 1
      })
  }

  decBreakLength() {
    this.state.breakLength <= 1 ?
      this.setState({
        breakLength: 1
      })
    :
      this.setState({
        breakLength: this.state.breakLength - 1
      })
  }

  incSessionLength() {
    this.state.sessionLength >= 60 ?
      this.setState({
        sessionLength: 60,
        timeMin: '60'
      })
    :
      this.setState({
        sessionLength: this.state.sessionLength + 1,
        timeMin: this.state.sessionLength + 1
      })
  }

  decSessionLength() {
    this.state.sessionLength <= 1 ?
      this.setState({
        sessionLength: 1,
        timeMin: '1'
      })
    :
      this.setState({
        sessionLength: this.state.sessionLength - 1,
        timeMin: this.state.sessionLength - 1
      })
  }

  onTimer() {
    let totalSec = this.state.sessionLength * 60;

    this.timer = setInterval(() => {
      let min = Math.floor(totalSec / 60);
      let sec = Math.floor(totalSec % 60);

      totalSec -= 1;

      this.setState({
        timeMin: min.toString(),
        timeSec: sec > 9 ? sec.toString() : '0' + sec.toString()
      })

      if(totalSec < 0) {
        if(this.state.clockMode === 'Session') {
          this.setState({
            clockMode: 'Break'
          })
          totalSec = this.state.breakLength * 60;
        } else {
          this.setState({
            clockMode: 'Session'
          })
          totalSec = this.state.sessionLength * 60;
        }
      }
    }, 1000);
  }

  offTimer() {
    clearInterval(this.timer)
  }

  handleTimer() {
    if(this.state.clicked === 'timerOff') {
      this.setState({
        clicked : 'timerOn'
      })

      this.onTimer();
    }
    else {
      this.setState({
        clicked : 'timerOff'
      })

      this.offTimer();
    }
  }

  init() {
    this.offTimer();

    this.setState({
      breakLength : 5,
      sessionLength : 25,
      clockMode: 'Session',
      clicked: 'timerOff',
      timeMin: '25',
      timeSec: '00'
    })
  }

  render() {
    return (
      <div>
        <div id='break-label'>
          <div id='break-length'>Break/{this.state.breakLength}</div>
          <button id='break-increment' onClick={this.incBreakLength}>+1</button>
          <button id='break-decrement' onClick={this.decBreakLength}>-1</button>
        </div>

        <div id='session-label'>
          <div id='session-length'>Session/{this.state.sessionLength}</div>
          <button id='session-increment' onClick={this.incSessionLength}>+1</button>
          <button id='session-decrement' onClick={this.decSessionLength}>-1</button>
        </div>

        <div id='time-label'>
          {this.state.clockMode}/{this.state.clicked}
          <div id='time-left'>{this.state.timeMin}:{this.state.timeSec}</div>
        </div>

        <button id='start_stop' onClick={this.handleTimer}>Start / Pause</button>
        <button id='reset' onClick={this.init}>Reset</button>
      </div>
    )
  }
}

ReactDOM.render(<Pomodoro />, document.getElementById('app'));
</code>```

I am writing the code to make Pomodoro Clock through FreeCodeCamp.
The counter should decrement from the sessionLength I set.

I should be able to stop and resume the counter with one button.
What I have been trying to do is I made the method called handleTimer deciding whether timer is on or off, and I made onTimer and offTimer method.

Where I am stuck is to resume the counter from the moment I stop. I think I need to make a state global.
but I cannot come up with any idea now. Any idea would help me.

答:
Here is one way of doing it, I just added a state paused (boolean) and removed clicked. If the state paused is true, I skip all the part inside the setInterval. If it's not i continue. I also set this.timer to null after the clear interval to use it inside the handleTimer function, if the timer is null we need to call onTimer to initialize it, if timer is not null, we just do nothing because onTimer have been already called.

class Pomodoro extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      breakLength: 5,
      sessionLength: 25,
      clockMode: 'Session',
      timeMin: '25',
      timeSec: '00',
      paused: true,
    }

    this.incBreakLength = this.incBreakLength.bind(this);
    this.decBreakLength = this.decBreakLength.bind(this);
    this.incSessionLength = this.incSessionLength.bind(this);
    this.decSessionLength = this.decSessionLength.bind(this);
    this.handleTimer = this.handleTimer.bind(this);
    this.onTimer = this.onTimer.bind(this);
    this.offTimer = this.offTimer.bind(this);
    this.init = this.init.bind(this);
  }

  incBreakLength() {
    this.state.breakLength >= 60 ?
      this.setState({
        breakLength: 60
      }) :
      this.setState({
        breakLength: this.state.breakLength + 1
      })
  }

  decBreakLength() {
    this.state.breakLength <= 1 ?
      this.setState({
        breakLength: 1
      }) :
      this.setState({
        breakLength: this.state.breakLength - 1
      })
  }

  incSessionLength() {
    this.state.sessionLength >= 60 ?
      this.setState({
        sessionLength: 60,
        timeMin: '60'
      }) :
      this.setState({
        sessionLength: this.state.sessionLength + 1,
        timeMin: this.state.sessionLength + 1
      })
  }

  decSessionLength() {
    this.state.sessionLength <= 1 ?
      this.setState({
        sessionLength: 1,
        timeMin: '1'
      }) :
      this.setState({
        sessionLength: this.state.sessionLength - 1,
        timeMin: this.state.sessionLength - 1
      })
  }

  onTimer() {
    let totalSec = this.state.sessionLength * 60;

    this.timer = setInterval(() => {
      if (this.state.paused)
        return;
      let min = Math.floor(totalSec / 60);
      let sec = Math.floor(totalSec % 60);

      totalSec -= 1;

      this.setState({
        timeMin: min.toString(),
        timeSec: sec > 9 ? sec.toString() : '0' + sec.toString()
      })

      if (totalSec < 0) {
        if (this.state.clockMode === 'Session') {
          this.setState({
            clockMode: 'Break'
          })
          totalSec = this.state.breakLength * 60;
        } else {
          this.setState({
            clockMode: 'Session'
          })
          totalSec = this.state.sessionLength * 60;
        }
      }
    }, 1000);
  }

  offTimer() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null;
    }
  }

  handleTimer() {
    this.setState(prev => ({
      ...prev,
      paused: !prev.paused,
    }), () => !this.timer && this.onTimer()
);
  }

  init() {
    this.offTimer();

    this.setState({
      breakLength: 5,
      sessionLength: 25,
      clockMode: 'Session',
      paused: true,
      timeMin: '25',
      timeSec: '00'
    })
  }

  render() {
    return ( <
      div >
      <
      div id = 'break-label' >
      <
      div id = 'break-length' > Break / {
        this.state.breakLength
      }
 <
      button id = 'break-increment'
      onClick = {
        this.incBreakLength
      } > +1 < /button> <
      button id = 'break-decrement'
      onClick = {
        this.decBreakLength
      } > -1 < /button> <
      /div>

      <
      div id = 'session-label' >
      <
      div id = 'session-length' > Session / {
        this.state.sessionLength
      }
 <
      button id = 'session-increment'
      onClick = {
        this.incSessionLength
      } > +1 < /button> <
      button id = 'session-decrement'
      onClick = {
        this.decSessionLength
      } > -1 < /button> <
      /div>

      <
      div id = 'time-label' > {
        this.state.clockMode
      }
      /{this.state.clicked} <
      div id = 'time-left' > {
        this.state.timeMin
      }: {
        this.state.timeSec
      }
 <
      /div>

      <
      button id = 'start_stop'
      onClick = {
        this.handleTimer
      } > Start / Pause < /button> <
      button id = 'reset'
      onClick = {
        this.init
      } > Reset < /button> <
      /div>
    )
  }
}

ReactDOM.render( < Pomodoro / > , document.getElementById('app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div></code>```

Body:
class Pomodoro extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      breakLength : 5,
      sessionLength : 25,
      clockMode: 'Session',
      clicked: 'timerOff',
      timeMin: '25',
      timeSec: '00'
    }

    this.incBreakLength = this.incBreakLength.bind(this);
    this.decBreakLength = this.decBreakLength.bind(this);
    this.incSessionLength = this.incSessionLength.bind(this);
    this.decSessionLength = this.decSessionLength.bind(this);
    this.handleTimer = this.handleTimer.bind(this);
    this.onTimer = this.onTimer.bind(this);
    this.offTimer = this.offTimer.bind(this);
    this.init = this.init.bind(this);
  }

  incBreakLength() {
    this.state.breakLength >= 60 ?
      this.setState({
        breakLength: 60
      })
    :
      this.setState({
        breakLength: this.state.breakLength + 1
      })
  }

  decBreakLength() {
    this.state.breakLength <= 1 ?
      this.setState({
        breakLength: 1
      })
    :
      this.setState({
        breakLength: this.state.breakLength - 1
      })
  }

  incSessionLength() {
    this.state.sessionLength >= 60 ?
      this.setState({
        sessionLength: 60,
        timeMin: '60'
      })
    :
      this.setState({
        sessionLength: this.state.sessionLength + 1,
        timeMin: this.state.sessionLength + 1
      })
  }

  decSessionLength() {
    this.state.sessionLength <= 1 ?
      this.setState({
        sessionLength: 1,
        timeMin: '1'
      })
    :
      this.setState({
        sessionLength: this.state.sessionLength - 1,
        timeMin: this.state.sessionLength - 1
      })
  }

  onTimer() {
    let totalSec = this.state.sessionLength * 60;

    this.timer = setInterval(() => {
      let min = Math.floor(totalSec / 60);
      let sec = Math.floor(totalSec % 60);

      totalSec -= 1;

      this.setState({
        timeMin: min.toString(),
        timeSec: sec > 9 ? sec.toString() : '0' + sec.toString()
      })

      if(totalSec < 0) {
        if(this.state.clockMode === 'Session') {
          this.setState({
            clockMode: 'Break'
          })
          totalSec = this.state.breakLength * 60;
        } else {
          this.setState({
            clockMode: 'Session'
          })
          totalSec = this.state.sessionLength * 60;
        }
      }
    }, 1000);
  }

  offTimer() {
    clearInterval(this.timer)
  }

  handleTimer() {
    if(this.state.clicked === 'timerOff') {
      this.setState({
        clicked : 'timerOn'
      })

      this.onTimer();
    }
    else {
      this.setState({
        clicked : 'timerOff'
      })

      this.offTimer();
    }
  }

  init() {
    this.offTimer();

    this.setState({
      breakLength : 5,
      sessionLength : 25,
      clockMode: 'Session',
      clicked: 'timerOff',
      timeMin: '25',
      timeSec: '00'
    })
  }

  render() {
    return (

Break/{this.state.breakLength}

          <button id='break-increment' onClick={this.incBreakLength}>+1</button>
          <button id='break-decrement' onClick={this.decBreakLength}>-1</button>

Session/{this.state.sessionLength}

          <button id='session-increment' onClick={this.incSessionLength}>+1</button>
          <button id='session-decrement' onClick={this.decSessionLength}>-1</button>

          {this.state.clockMode}/{this.state.clicked}

{this.state.timeMin}:{this.state.timeSec}

        <button id='start_stop' onClick={this.handleTimer}>Start / Pause</button>
        <button id='reset' onClick={this.init}>Reset</button>

    )
  }
}

ReactDOM.render(<Pomodoro />, document.getElementById('app'));

I am writing the code to make Pomodoro Clock through FreeCodeCamp.
The counter should decrement from the sessionLength I set.

I should be able to stop and resume the counter with one button.
What I have been trying to do is I made the method called handleTimer deciding whether timer is on or off, and I made onTimer and offTimer method.

Where I am stuck is to resume the counter from the moment I stop. I think I need to make a state global.
but I cannot come up with any idea now. Any idea would help me.

Body:
Here is one way of doing it, I just added a state paused (boolean) and removed clicked. If the state paused is true, I skip all the part inside the setInterval. If it's not i continue. I also set this.timer to null after the clear interval to use it inside the handleTimer function, if the timer is null we need to call onTimer to initialize it, if timer is not null, we just do nothing because onTimer have been already called.

class Pomodoro extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      breakLength: 5,
      sessionLength: 25,
      clockMode: 'Session',
      timeMin: '25',
      timeSec: '00',
      paused: true,
    }

    this.incBreakLength = this.incBreakLength.bind(this);
    this.decBreakLength = this.decBreakLength.bind(this);
    this.incSessionLength = this.incSessionLength.bind(this);
    this.decSessionLength = this.decSessionLength.bind(this);
    this.handleTimer = this.handleTimer.bind(this);
    this.onTimer = this.onTimer.bind(this);
    this.offTimer = this.offTimer.bind(this);
    this.init = this.init.bind(this);
  }

  incBreakLength() {
    this.state.breakLength >= 60 ?
      this.setState({
        breakLength: 60
      }) :
      this.setState({
        breakLength: this.state.breakLength + 1
      })
  }

  decBreakLength() {
    this.state.breakLength <= 1 ?
      this.setState({
        breakLength: 1
      }) :
      this.setState({
        breakLength: this.state.breakLength - 1
      })
  }

  incSessionLength() {
    this.state.sessionLength >= 60 ?
      this.setState({
        sessionLength: 60,
        timeMin: '60'
      }) :
      this.setState({
        sessionLength: this.state.sessionLength + 1,
        timeMin: this.state.sessionLength + 1
      })
  }

  decSessionLength() {
    this.state.sessionLength <= 1 ?
      this.setState({
        sessionLength: 1,
        timeMin: '1'
      }) :
      this.setState({
        sessionLength: this.state.sessionLength - 1,
        timeMin: this.state.sessionLength - 1
      })
  }

  onTimer() {
    let totalSec = this.state.sessionLength * 60;

    this.timer = setInterval(() => {
      if (this.state.paused)
        return;
      let min = Math.floor(totalSec / 60);
      let sec = Math.floor(totalSec % 60);

      totalSec -= 1;

      this.setState({
        timeMin: min.toString(),
        timeSec: sec > 9 ? sec.toString() : '0' + sec.toString()
      })

      if (totalSec < 0) {
        if (this.state.clockMode === 'Session') {
          this.setState({
            clockMode: 'Break'
          })
          totalSec = this.state.breakLength * 60;
        } else {
          this.setState({
            clockMode: 'Session'
          })
          totalSec = this.state.sessionLength * 60;
        }
      }
    }, 1000);
  }

  offTimer() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null;
    }
  }

  handleTimer() {
    this.setState(prev => ({
      ...prev,
      paused: !prev.paused,
    }), () => !this.timer && this.onTimer()
);
  }

  init() {
    this.offTimer();

    this.setState({
      breakLength: 5,
      sessionLength: 25,
      clockMode: 'Session',
      paused: true,
      timeMin: '25',
      timeSec: '00'
    })
  }

  render() {
    return ( <
      div >
      <
      div id = 'break-label' >
      <
      div id = 'break-length' > Break / {
        this.state.breakLength
      } < /div> <
      button id = 'break-increment'
      onClick = {
        this.incBreakLength
      } > +1 < /button> <
      button id = 'break-decrement'
      onClick = {
        this.decBreakLength
      } > -1 < /button> <
      /div>

      <
      div id = 'session-label' >
      <
      div id = 'session-length' > Session / {
        this.state.sessionLength
      } < /div> <
      button id = 'session-increment'
      onClick = {
        this.incSessionLength
      } > +1 < /button> <
      button id = 'session-decrement'
      onClick = {
        this.decSessionLength
      } > -1 < /button> <
      /div>

      <
      div id = 'time-label' > {
        this.state.clockMode
      }
      /{this.state.clicked} <
      div id = 'time-left' > {
        this.state.timeMin
      }: {
        this.state.timeSec
      } < /div> <
      /div>

      <
      button id = 'start_stop'
      onClick = {
        this.handleTimer
      } > Start / Pause < /button> <
      button id = 'reset'
      onClick = {
        this.init
      } > Reset < /button> <
      /div>
    )
  }
}

ReactDOM.render( < Pomodoro / > , document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>


来源: stackexchange

问:
The directory /home/vsts/work/1/s contains no Terraform configuration files. In Azure Devops trying to create Azure resource
I'm trying to create Azure virtual machine with Terraform and Azure Devops. I'm getting below error.

"The directory /home/vsts/work/1/s contains no Terraform configuration files."
Below is my .yml file.

```<code>resources:
- repo: self
steps:
- task: TerraformInstaller@0
  inputs:
    terraformVersion: '0.12.3'
- task: TerraformTaskV1@0
  displayName: 'Init terraform'
  inputs:
      provider: 'azurerm'
      command: 'init'
      backendServiceArm: 'Free Trial'
      backendAzureRmResourceGroupName: 'terraformtest-rg'
      backendAzureRmStorageAccountName: 'terraformtestrgdiag'
      backendAzureRmContainerName: 'bootdiagnostics-terraform'
      backendAzureRmKey: 'terraform'
- task: TerraformTaskV1@0
  displayName: 'apply status'
  inputs:
      terraformFile: './terraform/terra/main2.tf'
      provider: 'azurerm'
      command: 'apply'
      environmentServiceNameAzureRM: 'Free Trial ()'
</code>```

答:
The directory /home/vsts/work/1/s contains no Terraform configuration files. In Azure Devops trying to create Azure resource

According to the error:

```<code>the directory /home/vsts/work/1/s contains no Terraform configuration files
</code>```

It seems you have run the command in the wrong folder. You have to be in the directory that contains your configuration files before running init.

So, you could add the arguments like workingDirectory in the first task TerraformTaskV1, like:

```<code>workingDirectory: '$(System.DefaultWorkingDirectory)\terraform\terra'
</code>```

Hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create Azure virtual machine with Terraform and Azure Devops. I'm getting below error.

"The directory /home/vsts/work/1/s contains no Terraform configuration files."
Below is my .yml file.

resources:
- repo: self
steps:
- task: TerraformInstaller@0
  inputs:
    terraformVersion: '0.12.3'
- task: TerraformTaskV1@0
  displayName: 'Init terraform'
  inputs:
      provider: 'azurerm'
      command: 'init'
      backendServiceArm: 'Free Trial'
      backendAzureRmResourceGroupName: 'terraformtest-rg'
      backendAzureRmStorageAccountName: 'terraformtestrgdiag'
      backendAzureRmContainerName: 'bootdiagnostics-terraform'
      backendAzureRmKey: 'terraform'
- task: TerraformTaskV1@0
  displayName: 'apply status'
  inputs:
      terraformFile: './terraform/terra/main2.tf'
      provider: 'azurerm'
      command: 'apply'
      environmentServiceNameAzureRM: 'Free Trial ()'

Body:
The directory /home/vsts/work/1/s contains no Terraform configuration files. In Azure Devops trying to create Azure resource

According to the error:

the directory /home/vsts/work/1/s contains no Terraform configuration files

It seems you have run the command in the wrong folder. You have to be in the directory that contains your configuration files before running init.

So, you could add the arguments like workingDirectory in the first task TerraformTaskV1, like:

workingDirectory: '$(System.DefaultWorkingDirectory)\terraform\terra'

Hope this helps.


问:
Image blending in numpy returns plain white image
I am trying to blend 2 different images using numpy and not an image library. Since numpy works with arrays I used the formula below to blend the images:

```<code>    alpha = 0.8
    img_blend = img_1* (1.0 - alpha) + img_2* alpha
    io.imshow(img_blend)
</code>```

For some reason I keep getting a plain white image.
Both images show normally, when I use io.imshow() on them, the problem arises when applying the formula.

Here is the output I playing with the alpha values:

alpha = 0.9995 :

alpha = 1:

alpha = 0:

答:
While typing the question I figured out what was wrong, so I am going to answer my own question in case anyone would benefit from it.

Adding the 2 numpy arrays was converting my array values from uint8 values to float64 values. The solution I found is by changing the type back to uint8.

```<code>img_blend = (img_1* (1.0 - alpha) + img_2* alpha).astype('uint8')
</code>```

The big give away was the color bar to the side. The final image is shown below:

Body:
I am trying to blend 2 different images using numpy and not an image library. Since numpy works with arrays I used the formula below to blend the images:

    alpha = 0.8
    img_blend = img_1* (1.0 - alpha) + img_2* alpha
    io.imshow(img_blend)

For some reason I keep getting a plain white image.
Both images show normally, when I use io.imshow() on them, the problem arises when applying the formula.

Here is the output I playing with the alpha values:

alpha = 0.9995 :

alpha = 1:

alpha = 0:

Body:
While typing the question I figured out what was wrong, so I am going to answer my own question in case anyone would benefit from it.

Adding the 2 numpy arrays was converting my array values from uint8 values to float64 values. The solution I found is by changing the type back to uint8.

img_blend = (img_1* (1.0 - alpha) + img_2* alpha).astype('uint8')

The big give away was the color bar to the side. The final image is shown below:


问:
How to return documents from firebase with specific variables?
I want to view documents only with Number is less than or equal to 10 (not to show all documents).
here is my code:

```<code>Future getHomeWsyl()async{
    var firestore = Firestore.instance;
    QuerySnapshot snapshot = await firestore.collection("HomePageWsyl").getDocuments();
    return snapshot.documents;
}
</code>```

what to correct in this code to do this?

enter image description here

答:
firestore.collection("HomePageWsyl").where("Number", isLessThanOrEqualTo: 10).getDocuments();
and in firebase "Number" should be number</p>

Body:
I want to view documents only with Number is less than or equal to 10 (not to show all documents).
here is my code:

Future getHomeWsyl()async{
    var firestore = Firestore.instance;
    QuerySnapshot snapshot = await firestore.collection("HomePageWsyl").getDocuments();
    return snapshot.documents;
}

what to correct in this code to do this?

enter image description here


问:
Why using Gatsby Wordpress plugin throws 404 error?
I'm setting up a Gatsby site that pulls data from an existing wordpress site that I host on my own server [Dreamhost].

After I set up the plugin according to the docs and when I run 'gatsby develop', this happens. No data object is returned.. the plugin I installed on the wordpress site seems to do nothng.

=START PLUGIN=====================================

Site URL: https://example.com

Site hosted on Wordpress.com: false

Using ACF: false

Auth: false

Verbose output: true

Mama Route URL: https://example.com/wp-json

⡀ source and transform nodes

Path: /wp-json

The server response was "404 Not Found"

error Plugin gatsby-source-wordpress returned an error

TypeError: Cannot read property 'data' of undefined

====================================================

I have the https://github.com/WP-API/Basic-Auth installed and activated.. and indeed, no /wp-json.

What am I missing?

I feel like the issue is with my WP-API plugin or Wordpress settings.

*the example.com is used for privacy sake in the above

Thanks in advance,
Jason

答:
Got the solution here.

I also faced similar problem in a local project. I used index.php after my project url and it worked.
  http://localhost/myproject/index.php/wp-json/wp/v2/posts

Try to access [yourwordpresssite.com]/index.php/wp-json/ and see if it works.

If yes then go to gatsby-config.js and ammend restApiRoutePrefix:"index.php/wp-json"


问:
create a new variable in the data frame based on multiple criteria in r
I have a data set which has

```<code>COl1 COl2 Col3
1     0     0
0     1     0
0     0     1
1     0     0
</code>```

Based on these three column i need to add new variable in the same table

Expected Output

```<code>COl1 COl2 Col3  New_variable
1     0     0     c1
0     1     0     c2
0     0     1     c3
1     0     0     c1
</code>```

答:
Here are some base R solutions:

```<code>df$New_variable <- paste0("c",seq(df)%*%t(df))
</code>```

or

```<code>df$New_variable <- paste0("c",rowSums(df*col(df)))
</code>```

or

```<code>df$New_variable <- paste0("c",which(t(df)==1,arr.ind = T)[,"row"])
</code>```

such that

```<code>> df
  COl1 COl2 Col3 New_variable
1    1    0    0           c1
2    0    1    0           c2
3    0    0    1           c3
4    1    0    0           c1
</code>```

DATA

```<code>df <- structure(list(COl1 = c(1L, 0L, 0L, 1L), COl2 = c(0L, 1L, 0L,
0L), Col3 = c(0L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA,
-4L))
</code>```

Body:
I have a data set which has

COl1 COl2 Col3
1     0     0
0     1     0
0     0     1
1     0     0

Based on these three column i need to add new variable in the same table

Expected Output

COl1 COl2 Col3  New_variable
1     0     0     c1
0     1     0     c2
0     0     1     c3
1     0     0     c1

Body:
Here are some base R solutions:

df$New_variable <- paste0("c",seq(df)%*%t(df))

or

df$New_variable <- paste0("c",rowSums(df*col(df)))

or

df$New_variable <- paste0("c",which(t(df)==1,arr.ind = T)[,"row"])

such that

> df
  COl1 COl2 Col3 New_variable
1    1    0    0           c1
2    0    1    0           c2
3    0    0    1           c3
4    1    0    0           c1

DATA

df <- structure(list(COl1 = c(1L, 0L, 0L, 1L), COl2 = c(0L, 1L, 0L,
0L), Col3 = c(0L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA,
-4L))


问:
Substring datafame string column
I have a dataframe with one column:

```<code>x = data.frame(col = c('PS-01','PS-02','PS-03','PS-04','PS-05','PS-06')

  )

</code>```

I want to substring it with stringr and get new dataframe with int after PS- which lookslike this:

```<code>x_new = data.frame(col = c(01,02,03,04,05,06)
</code>```

How could i do that?

答:
This should do

```<code>gsub("PS-", "", x)
</code>```

gsub() searches in x for the first argument("PS-") and replaces it with the second argument ("").

And here the stringr version:

```<code>library(stringr)

str_replace(x, "PS-", "")
</code>```

Title: Substring datafame string column

Body:
I have a dataframe with one column:

x = data.frame(col = c('PS-01','PS-02','PS-03','PS-04','PS-05','PS-06')

  )

I want to substring it with stringr and get new dataframe with int after PS- which lookslike this:

x_new = data.frame(col = c(01,02,03,04,05,06)

How could i do that?

Body:
This should do

gsub("PS-", "", x)

gsub() searches in x for the first argument("PS-") and replaces it with the second argument ("").

And here the stringr version:

library(stringr)

str_replace(x, "PS-", "")


问:
Read any key to continue Java
How can I implement the press ANY key to continue in Java. In C I use getch() and it works fine but Java I must press enter in every read method implement in every OutputStream class.

Thanks in advance.

答:
You can use following code if you're using windows.

new ProcessBuilder("cmd", "/c", "pause").inheritIO().start().waitFor();
```

<p>and import following package.</p>

<pre class="lang-java prettyprint-override"><code>import java.io.IOException;
</code>```

and change main function to this.

public static void main(String args[]) throws IOException, InterruptedException
```

ContentLicense: CC BY-SA 3.0

Title: Read any key to continue Java

Body:
You can use following code if you're using windows.

new ProcessBuilder("cmd", "/c", "pause").inheritIO().start().waitFor();

and import following package.

import java.io.IOException;

and change main function to this.

public static void main(String args[]) throws IOException, InterruptedException


问:
OS dev: triple fault when trying to enable paging
I am building a simple OS for learning purposes and I am (currently; I followed different tutorials earlier and customized something by myself) following this tutorial for enabling paging. I'm using QEMU instead of Bochs as my emulator.

If I keep paging disabled everything works fine (even the very basic kmalloc() I implemented), but as soon as I set the PG bit in the cr0 register (i.e. enable paging), everything crashes and QEMU reboots: I suspect that some of the structures (i.e. page directory, page tables, etc.) I have are not created or loaded properly, but I have no way of checking.

I've been trying to solve this problem since a while now, but haven't found a solution. Can anyone see where my mistake is?

Here you can find my complete code: https://github.com/davidedellagiustina/ScratchOS (commit 83b5c8c). Paging code is located in src/cpu/paging.*.

Edit: Setting up a super-basic page directory following exactly this tutorial results in working code. Basing on this simple example, I'm trying to build up the more complex structures (i.e. page_t, page_table_t, page_directory_t) in order to understand the mistake.

答:
I found out I was missing all the flags in the page directory entries (and especially the read/write and the kernel mode ones), as I was putting there just the page table address. I will keep my repository public and I will continue the development from now on, in case anyone needs it in the future.

Edit: Also, I forgot to initialize all the pages (with address and presence bit) when I created a new page table.


问:
How to convert timestamp date to java.util date(yyyy-mm-dd) in java
I am getting date from Oracle is in Timestamp but I need to convert it in to this format 2020-02-17 (yyyy-mm-dd) format, but currently in postman I am receiving date as "2020-02-17T09:40:37.850+0000" in this format.

Any help on this would be really appreciated

答:
You can easily convert a java.sql.Timestamp to a java.time.LocalDate and get a date String by formatting the LocalDate like this:

```<code>public static void main(String[] args) {
    // just a timestamp stub that takes "now"
    java.sql.Timestamp ts = java.sql.Timestamp.from(Instant.now());
    // convert it to a modern date object
    LocalDate justDate = ts.toLocalDateTime().toLocalDate();
    // print it using a suitable formatter
    System.out.println(justDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
</code>```

The output (today) is

2020-02-17
```

<p><strong>You just need Java 8 or higher for this or import a backport library.</strong></p>

<p><strong>EDIT</strong></p>

<p>If you don't need a <code>String</code> but a <code>java.util.Date</code>, do it with <code>Instant</code> only, like this:</p>

```public static void main(String[] args) {
    // just a timestamp stub that takes "now"
    Instant now = Instant.now();
    Timestamp ts = Timestamp.from(now);
    // create an Instant from the Timestamp
    Instant timestampInstant = ts.toInstant();
    // and then create a Date out from that Instant
    java.util.Date creationDate = java.util.Date.from(now);

    // do something with the Date here...
}
```

But please consider using java.time wherever possible, which might be in your domain class...

Body:
You can easily convert a java.sql.Timestamp to a java.time.LocalDate and get a date String by formatting the LocalDate like this:

public static void main(String[] args) {
    // just a timestamp stub that takes "now"
    java.sql.Timestamp ts = java.sql.Timestamp.from(Instant.now());
    // convert it to a modern date object
    LocalDate justDate = ts.toLocalDateTime().toLocalDate();
    // print it using a suitable formatter
    System.out.println(justDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}

The output (today) is

2020-02-17

You just need Java 8 or higher for this or import a backport library.

EDIT

If you don't need a String but a java.util.Date, do it with Instant only, like this:

public static void main(String[] args) {
    // just a timestamp stub that takes "now"
    Instant now = Instant.now();
    Timestamp ts = Timestamp.from(now);
    // create an Instant from the Timestamp
    Instant timestampInstant = ts.toInstant();
    // and then create a Date out from that Instant
    java.util.Date creationDate = java.util.Date.from(now);

    // do something with the Date here...
}

But please consider using java.time wherever possible, which might be in your domain class...


问:
VBA Object with variable or block variable not set error even when is already set
I am currently trying to set conditions such that when a CSV file is not found in the folder, it will continue to find other CSV files. However I'm facing the "object with variable or block variable not set" error at the 2nd private sub readdatavcap2 even when I've already set Set o_file = fs2.OpenTextFile for both 1st and 2nd sub. I'm confused because for the 1st sub, the error does not occurs at o_file.Close after the else statement while for 2nd sub it occurs. Does anybody knows why?

Private Sub readdatavcap1(filename As String, i As Integer)
    Application.ScreenUpdating = False

    Dim sl As String
    Dim first As Integer
    Dim second As Integer
    Dim j As Long
    Dim fs2 As New Scripting.FileSystemObject
    Dim o_file As Scripting.TextStream
    j = 2        'variable not defined at fs2

    If Dir(filename) <> "" Then
        Set fs2 = CreateObject("Scripting.FileSystemObject") 'FileSystemObject also called as FSO, provides an easy object based model to access computer's file system.
                                                             'o_file contains filename(csv file link)
        Set o_file = fs2.OpenTextFile(filename, 1, TristateFalse) '1=Open a file for reading only. You can't write to this file. TristateFalse means u get ascii file by default
                                                              '2=ForWriting, 8= Forappending

         'o_file contains filename(text file data)
         sl = o_file.readline 'Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.

         Do While Left(sl, 1) = "#"   'Left Function is used to extract N number of characters from a string from the left side.
             sl = o_file.readline
         Loop

         Do While o_file.atendofstream <> True 'atendofstream = Read-only property that returns True if the file pointer is at the end of a TextStream file; False if it is not.
             sl = o_file.readline
             first = InStr(32, sl, ",", 1) - 15 'INSTR function returns the position of the first occurrence of a substring in a string.

             second = InStr(first + 2, sl, ",", 1) 'syntax of InStr( [start], string, substring, [compare] )
                                              'start sets string position for each search, string = string being search, substring= string expression searched ,
                                              'eg:InStr(1, "Tech on the Net", "t") Result: 9    'Shows that search is case-sensitive
                                              'compare= optional 1= textcompare
                                              'searching for commas in the file in this case

             If second = 0 Then
                 second = Len(sl) + 1 'len=length of file string
             End If

             If tddb_vramp = True Then
                 ' write the Voltage Ramp to stress part
                 If i = 2 Then
                     ActiveWorkbook.Sheets("Ramp_current").Cells(j, 1) = Mid(sl, 2, first - 2)
                 End If

                 ActiveWorkbook.Sheets("Ramp_current").Cells(j, i) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
             Else
                 'Write the normal current trace
                 ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 3) = Mid(sl, 15, first - 14)

                 ' The MID function returns the specified number of characters in a text string, starting from a specified position (
                'ie. starting from a specified character number).
                'Use this function to extract a sub-string from any part of a text string. Syntax: MID(text_string, start_number, char_numbers).

                ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 2) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
            End If

            j = j + 1
        Loop

        If tddb_vramp = False Then
            myarray(i) = j - 1
        End If

        o_file.Close
    Else
        o_file.Close
    End If
End Sub

Private Sub readdatavcap2(filename As String, i As Integer)

    (rest of the code same as readdatavcap1)
    .
    .
    .

        o_file.Close
    Else
        o_file.Close <---error occurs here
    End If
End Sub
```

答:
I worked my way through your code but can't do more than confirm what GSerg already said in his first comment, i.e. you can't close a file that isn't open.

```<code>    Option Explicit

Sub Main()

    Dim SourceFolder As String
    Dim Fn As String                            ' Filoe name
    Dim i As Integer

    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = -1 Then                      ' if OK is pressed
            SourceFolder = .SelectedItems(1)
        End If
    End With

    If SourceFolder <> "" Then                  ' a folder was chosen
        i = 2
        Fn = Dir(SourceFolder & "\*.csv")
        Do While Len(Fn) > 0
            readdatavcap1 Fn, i
            Fn = Dir
        Loop
    End If
End Sub

    Private Sub readdatavcap1(filename As String, i As Integer)
        ' "filename" is a variable used by VBA
        ' your use of it may cause unexpected problems.
        ' to check, select the name and press F1.

        Dim sl As String
        Dim first As Integer
        Dim second As Integer
        Dim j As Long
        Dim fs2 As New Scripting.FileSystemObject
        Dim o_file As Scripting.TextStream
        Dim tddb_vramp As Boolean

        If Dir(filename) <> "" Then
            Application.ScreenUpdating = False
            j = 2                           'variable not defined at fs2

            ' FileSystemObject also called as FSO, provides an easy object based model
            '   to access computer's file system.
            Set fs2 = CreateObject("Scripting.FileSystemObject")

            ' o_file contains filename (csv file link)
            ' 1=Open a file for reading only. You can't write to this file.
            ' 2=ForWriting, 8= For appending
            '   TristateFalse means u get ascii file by default.
            Set o_file = fs2.OpenTextFile(filename, 1, TristateFalse)

             ' o_file contains filename(text file data)
             ' Reads an entire line (up to, but not including, the newline character)
             '  from a TextStream file and returns the resulting string.
             sl = o_file.readline
             Do While Left(sl, 1) = "#"
                ' Left Function is used to extract N number of characters from a string from the left side.
                 sl = o_file.readline
             Loop

            ' atendofstream = Read-only property that returns True if the file pointer
            '   is at the end of a TextStream file; False if it is not.
             Do While o_file.atendofstream <> True
                 sl = o_file.readline
                 ' INSTR function returns the position of the first occurrence of a substring in a string.

                ' syntax of InStr( [start], string, substring, [compare] )
                '   start sets string position for each search, string = string being search,
                '   substring= string expression searched ,
                '   eg:InStr(1, "Tech on the Net", "t") Result: 9
                '   Shows that search is case-sensitive
                '   compare= optional 1= textcompare
                '   searching for commas in the file in this case
                 first = InStr(32, sl, ",", 1) - 15     ' what if first is negative?
                 second = InStr(first + 2, sl, ",", 1)

                 If second = 0 Then
                     second = Len(sl) + 1               'len=length of file string
                 End If

                ' "ActiveWorkbook" seems not necessary unless you intend to have
                ' several workbooks, all having a sheet "Ramp_current" open at the
                ' same time, and none of them being ThisWorkbook.
                ' But if that's your intention "ActiveWorkbook" will lead to
                ' disaster sooner rather than later.
                 If tddb_vramp = True Then
                     ' write the Voltage Ramp to stress part
                     If i = 2 Then
                         ActiveWorkbook.Sheets("Ramp_current").Cells(j, 1) = Mid(sl, 2, first - 2)
                     End If

                     ActiveWorkbook.Sheets("Ramp_current").Cells(j, i) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
                 Else
                     'Write the normal current trace
                     ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 3) = Mid(sl, 15, first - 14)

                     ' The MID function returns the specified number of characters in a text string,
                     '  starting from a specified position (ie. starting from a specified character number).
                     '  Use this function to extract a sub-string from any part of a text string.
                     '  Syntax: MID(text_string, start_number, char_numbers).

                    ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 2) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
                End If

                j = j + 1
            Loop

            If tddb_vramp = False Then
                myarray(i) = j - 1
            End If

            o_file.Close
            Application.ScreenUpdating = True
        Else
            ' if Dir(filename) = "" The o_file doesn't exist
            MsgBox filename & " wasn't found.", _
                   vbInformation, "Reading failure"
        End If
    End Sub
</code>```

You should remove the Else condition from the above code. If you do that the code will do exactly nothing if the file isn't found. This fact would probably induce me to convert this procedure into a function that returns True if the file was found and False if it isn't. Perhaps that's helpful.

The point is that this procedure must be called by a Main proc which loops through all the files in a folder (for example) calling your proc with different file names. So, if your proc returns False the Main might issue a message saying that a file wasn't found. But even if you don't care for that, it's the Main that would select the next file after one has either been found and evaluated or not.

Body:
I worked my way through your code but can't do more than confirm what GSerg already said in his first comment, i.e. you can't close a file that isn't open.

    Option Explicit

Sub Main()

    Dim SourceFolder As String
    Dim Fn As String                            ' Filoe name
    Dim i As Integer

    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = -1 Then                      ' if OK is pressed
            SourceFolder = .SelectedItems(1)
        End If
    End With

    If SourceFolder <> "" Then                  ' a folder was chosen
        i = 2
        Fn = Dir(SourceFolder & "\*.csv")
        Do While Len(Fn) > 0
            readdatavcap1 Fn, i
            Fn = Dir
        Loop
    End If
End Sub

    Private Sub readdatavcap1(filename As String, i As Integer)
        ' "filename" is a variable used by VBA
        ' your use of it may cause unexpected problems.
        ' to check, select the name and press F1.

        Dim sl As String
        Dim first As Integer
        Dim second As Integer
        Dim j As Long
        Dim fs2 As New Scripting.FileSystemObject
        Dim o_file As Scripting.TextStream
        Dim tddb_vramp As Boolean

        If Dir(filename) <> "" Then
            Application.ScreenUpdating = False
            j = 2                           'variable not defined at fs2

            ' FileSystemObject also called as FSO, provides an easy object based model
            '   to access computer's file system.
            Set fs2 = CreateObject("Scripting.FileSystemObject")

            ' o_file contains filename (csv file link)
            ' 1=Open a file for reading only. You can't write to this file.
            ' 2=ForWriting, 8= For appending
            '   TristateFalse means u get ascii file by default.
            Set o_file = fs2.OpenTextFile(filename, 1, TristateFalse)

             ' o_file contains filename(text file data)
             ' Reads an entire line (up to, but not including, the newline character)
             '  from a TextStream file and returns the resulting string.
             sl = o_file.readline
             Do While Left(sl, 1) = "#"
                ' Left Function is used to extract N number of characters from a string from the left side.
                 sl = o_file.readline
             Loop

            ' atendofstream = Read-only property that returns True if the file pointer
            '   is at the end of a TextStream file; False if it is not.
             Do While o_file.atendofstream <> True
                 sl = o_file.readline
                 ' INSTR function returns the position of the first occurrence of a substring in a string.

                ' syntax of InStr( [start], string, substring, [compare] )
                '   start sets string position for each search, string = string being search,
                '   substring= string expression searched ,
                '   eg:InStr(1, "Tech on the Net", "t") Result: 9
                '   Shows that search is case-sensitive
                '   compare= optional 1= textcompare
                '   searching for commas in the file in this case
                 first = InStr(32, sl, ",", 1) - 15     ' what if first is negative?
                 second = InStr(first + 2, sl, ",", 1)

                 If second = 0 Then
                     second = Len(sl) + 1               'len=length of file string
                 End If

                ' "ActiveWorkbook" seems not necessary unless you intend to have
                ' several workbooks, all having a sheet "Ramp_current" open at the
                ' same time, and none of them being ThisWorkbook.
                ' But if that's your intention "ActiveWorkbook" will lead to
                ' disaster sooner rather than later.
                 If tddb_vramp = True Then
                     ' write the Voltage Ramp to stress part
                     If i = 2 Then
                         ActiveWorkbook.Sheets("Ramp_current").Cells(j, 1) = Mid(sl, 2, first - 2)
                     End If

                     ActiveWorkbook.Sheets("Ramp_current").Cells(j, i) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
                 Else
                     'Write the normal current trace
                     ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 3) = Mid(sl, 15, first - 14)

                     ' The MID function returns the specified number of characters in a text string,
                     '  starting from a specified position (ie. starting from a specified character number).
                     '  Use this function to extract a sub-string from any part of a text string.
                     '  Syntax: MID(text_string, start_number, char_numbers).

                    ActiveWorkbook.Sheets("currentPTN_STI").Cells(j, 2 * i - 2) = Abs(Mid(sl, first + 2, second - 2 - first)) + 0.000000000000001
                End If

                j = j + 1
            Loop

            If tddb_vramp = False Then
                myarray(i) = j - 1
            End If

            o_file.Close
            Application.ScreenUpdating = True
        Else
            ' if Dir(filename) = "" The o_file doesn't exist
            MsgBox filename & " wasn't found.", _
                   vbInformation, "Reading failure"
        End If
    End Sub

You should remove the Else condition from the above code. If you do that the code will do exactly nothing if the file isn't found. This fact would probably induce me to convert this procedure into a function that returns True if the file was found and False if it isn't. Perhaps that's helpful.

The point is that this procedure must be called by a Main proc which loops through all the files in a folder (for example) calling your proc with different file names. So, if your proc returns False the Main might issue a message saying that a file wasn't found. But even if you don't care for that, it's the Main that would select the next file after one has either been found and evaluated or not.


问:
Flask and Keras model Error ''_thread._local' object has no attribute 'value''?
I am using the following:
python 3.6.4

Flask = 1.1.1,

Keras = 2.3.0,

TensorFlow = 1.14.0,
I have a Flask server that gets pictures from the clients. using Keras model with a TensorFlow back-end I try to get a prediction from a pre-trained model.

I am using the following function to upload the model( as part of a class)

```<code>
 model_path = self.conf["model_path"] // path in conf to model
 self.model = load_model(model_path)  // uploading the model
 self.model._make_predict_function()
 p_log.info("model had been upload successfully ")
</code>```

and I use the following line for prediction:

```<code>cm_prediction = self.model.predict([face, reye, leye, fg])[0]
</code>```

Until today I didn't have any problem, always got a prediction.
now I get the following error:

```<code>Traceback (most recent call last):
  File "D:\code_project\path to project", line 75, in predict
    cm_prediction = self.model.predict([face, reye, leye, fg])[0]
  File "D:\code_project\path to project", line 1462, in predict
    callbacks=callbacks)
  File "D:\code_project\predictserver\venv\lib\site-packages\keras\engine\training_arrays.py", line 276, in predict_loop
    callbacks.model.stop_training = False
  File "D:\code_project\predictserver\venv\lib\site-packages\keras\engine\network.py", line 323, in __setattr__
    super(Network, self).__setattr__(name, value)
  File "D:\code_project\predictserver\venv\lib\site-packages\keras\engine\base_layer.py", line 1215, in __setattr__
    if not _DISABLE_TRACKING.value:
AttributeError: '_thread._local' object has no attribute 'value'
</code>```

I have a simple Flask server running:

```<code>if __name__ == '__main__':
    pre = predictor()
    # app.run(debug=True)
    app.run(host='0.0.0.0', port=12345)
</code>```

The model is always being uploaded.

If I am running the program without the Flask server, hence giving manually input, I get a prediction, but as soon as the server is on the error appears and I stop getting a predictions

I tried to look on the web for some similar problem but didnt found any, if someone knows what the problem and how to solve it, I will appreciate sharing it.

答:
I tried all the above and here's what I found:

downgrading Keras didn't work, even regular non-flask calls failed to load models

tb._SYMBOLIC_SCOPE.value = True didn't work either

finally threaded=False AND debug=False worked.

Body:
I am using the following:
python 3.6.4

Flask = 1.1.1,

Keras = 2.3.0,

TensorFlow = 1.14.0,
I have a Flask server that gets pictures from the clients. using Keras model with a TensorFlow back-end I try to get a prediction from a pre-trained model.

I am using the following function to upload the model( as part of a class)

 model_path = self.conf["model_path"] // path in conf to model
 self.model = load_model(model_path)  // uploading the model
 self.model._make_predict_function()
 p_log.info("model had been upload successfully ")

and I use the following line for prediction:

cm_prediction = self.model.predict([face, reye, leye, fg])[0]

Until today I didn't have any problem, always got a prediction.
now I get the following error:

Traceback (most recent call last):
  File "D:\code_project\path to project", line 75, in predict
    cm_prediction = self.model.predict([face, reye, leye, fg])[0]
  File "D:\code_project\path to project", line 1462, in predict
    callbacks=callbacks)
  File "D:\code_project\predictserver\venv\lib\site-packages\keras\engine\training_arrays.py", line 276, in predict_loop
    callbacks.model.stop_training = False
  File "D:\code_project\predictserver\venv\lib\site-packages\keras\engine\network.py", line 323, in __setattr__
    super(Network, self).__setattr__(name, value)
  File "D:\code_project\predictserver\venv\lib\site-packages\keras\engine\base_layer.py", line 1215, in __setattr__
    if not _DISABLE_TRACKING.value:
AttributeError: '_thread._local' object has no attribute 'value'

I have a simple Flask server running:

if __name__ == '__main__':
    pre = predictor()
    # app.run(debug=True)
    app.run(host='0.0.0.0', port=12345)

The model is always being uploaded.

If I am running the program without the Flask server, hence giving manually input, I get a prediction, but as soon as the server is on the error appears and I stop getting a predictions

I tried to look on the web for some similar problem but didnt found any, if someone knows what the problem and how to solve it, I will appreciate sharing it.


答:
If we want to assign variable based on presence of 1 in each row we can use max.col.

```<code>df$New_variable <- paste0('c', max.col(df))
df
#  COl1 COl2 Col3 New_variable
#1    1    0    0           c1
#2    0    1    0           c2
#3    0    0    1           c3
#4    1    0    0           c1
</code>```

In case of multiple 1's in a row check various ties.method in ?max.col.

If we need to assign unique ID to each row based we can row-wise paste the values and then use match to assign ID.

```<code>vals <- do.call(paste, c(df, sep = "-"))
df$New_variable <- paste0('c', match(vals, unique(vals)))
</code>```

Title: create a new variable in the data frame based on multiple criteria in r

Body:
If we want to assign variable based on presence of 1 in each row we can use max.col.

df$New_variable <- paste0('c', max.col(df))
df
#  COl1 COl2 Col3 New_variable
#1    1    0    0           c1
#2    0    1    0           c2
#3    0    0    1           c3
#4    1    0    0           c1

In case of multiple 1's in a row check various ties.method in ?max.col.

If we need to assign unique ID to each row based we can row-wise paste the values and then use match to assign ID.

vals <- do.call(paste, c(df, sep = "-"))
df$New_variable <- paste0('c', match(vals, unique(vals)))


问:
How to create a reusable Map
Is there a way to populate a Map once from the DB (through Mongo repository) data and reuse it when required from multiple classes instead of hitting the Database through the repository.</p>

答:
You can declare the map field as public static and this would allow application wide access to hit via ClassLoadingData.mapField

I think a better solution, if I understood the problem would be a memoized function, that is a function storing the value of its call. Here is a sketch of how this could be done (note this does not handle possible synchronization problem in a multi threaded environment):

class ClassLoadingData {

  private static Map<KeyType,ValueType> memoizedValues = new HashMap<>();

  public Map<KeyType,ValueType> getMyData() {

    if (memoizedData.isEmpty()) { // you can use more complex if to handle data refresh

     populateData(memoizedData);

    } else {
      return memoizedData;
    }

  }

  private void populateData() {

    // do your query, and assign result to memoizedData

  }

}

```

Title: How to create a reusable Map


问:
How to create a wrapper for Retrofit API using RxJava
I have two APIs say API 1 and API 2. API 1 get authentication token and API 2 get user profile info. I need to hit API 2 from ViewModel but if API 2 gives an authentication error, then I need to get new token first and then hit API 2(user info)

Currently, I use RxJava Single and Retrofit for all APIs but for APIs one by one. There are a lot of APIs that use authentication token and if it expires in any of the APIs then I need to call authentication API and get the token again and then call the APIs with a new authentication token.

What should be the best way to design a wrapper so that it can be used with all APIs with code reusability as well.

Thanks in advance.

答:
I have some idea. If you have basemodel for getting response for API, you can make custom getter for response code and check if response code in token_expired.

This is sample response that I got From API.

```<code>{
    response_code: "200",
    response_msg: "",
    result: ...
}
</code>```

And this is my BaseModel.

```<code>class BaseModel<T> {
    @SerializedName("response_code")
    var response_code: Int? = null
        get() {
            if(field == ErrorStatusCode.TOKEN_EXPIRE) {
                ErrorCodeHandler.requestNewToken()
            }
            return field
        },
    @SerializedName("response_msg")
    var response_msg: String? = null
    @SerializedName("result")
    var data: T? = null
}
</code>```

So whenever token expire, I will request Net token by call ErrorCodeHandler.requestNewToken()

But If you want to recall API that found token timeout I have no idea what to do too.

PS. Hope this help.

Body:
I have some idea. If you have basemodel for getting response for API, you can make custom getter for response code and check if response code in token_expired.

This is sample response that I got From API.

{
    response_code: "200",
    response_msg: "",
    result: ...
}

And this is my BaseModel.

class BaseModel<T> {
    @SerializedName("response_code")
    var response_code: Int? = null
        get() {
            if(field == ErrorStatusCode.TOKEN_EXPIRE) {
                ErrorCodeHandler.requestNewToken()
            }
            return field
        },
    @SerializedName("response_msg")
    var response_msg: String? = null
    @SerializedName("result")
    var data: T? = null
}

So whenever token expire, I will request Net token by call ErrorCodeHandler.requestNewToken()

But If you want to recall API that found token timeout I have no idea what to do too.

PS. Hope this help.


问:
no matches for kind "Deployment" in version "apps/v1"
I have minikube v0.26.0 version and kubectl v1.10.1 version and localKube v1.8.0

i get the following error when i try to deploy the kubeless ui

```<code>$ kubectl create -f https://raw.githubusercontent.com/kubeless/kubeless-ui/master/k8s.yaml
</code>```

ERROR:

unable to recognize "https://raw.githubusercontent.com/kubeless/kubeless-ui/master/k8s.yaml": no matches for kind "Deployment" in version "apps/v1"

答:
after a long R & D

```<code>minikube start --logtostderr --v=0 --bootstrapper=localkube --vm-driver virtualbox
</code>```

now it downloaded the latest localkube version, and this solved my problem.

Body:
I have minikube v0.26.0 version and kubectl v1.10.1 version and localKube v1.8.0

i get the following error when i try to deploy the kubeless ui

$ kubectl create -f https://raw.githubusercontent.com/kubeless/kubeless-ui/master/k8s.yaml

ERROR:

unable to recognize "https://raw.githubusercontent.com/kubeless/kubeless-ui/master/k8s.yaml": no matches for kind "Deployment" in version "apps/v1"

Body:
after a long R & D

minikube start --logtostderr --v=0 --bootstrapper=localkube --vm-driver virtualbox

now it downloaded the latest localkube version, and this solved my problem.


问:
How to check if pid is threads or process
To check if process id is exist I check

```<code>if (0 != kill(pid, 0))
    printf(" not exist");
</code>```

In /proc/pid/task I can see all threads id in process id

How can I determine if pid is process or threads in Linux?

答: Read /proc/$pid/stat or /proc/$pid/status. If the Tgid (thread group id) field is different from the Pid field, then $pid is just a thread id, not a process id. Otherwise, it's both a process id and the thread-id of the first thread in the process.

Body:
To check if process id is exist I check

if (0 != kill(pid, 0))
    printf(" not exist");

In /proc/pid/task I can see all threads id in process id

How can I determine if pid is process or threads in Linux?


问:
PayPal recurring payment plan modification
I have a PayPal billing plan for recurring payments. But I need to achieve a scenario where if a user subscribes to my billing plan in the middle of a month then he will be charged instantly and the next billing date will be the first day of next month. How this scenario can be solved?

答:
What type of billing plan for what type of recurring payments? There's like 5+ different APIs and versions.

With the the newest Subscriptions API, you could have a plan that charges a setup fee for your instant charge:

```<code>  "payment_preferences": {
    "setup_fee": {
      "value": "10",
      "currency_code": "USD"
    },
</code>```

and in billing cycles has a "tenure_type": "TRIAL" with no pricing_scheme that lasts XX amount of days, where XX is calculated by you to be the number of days remaining in the current month that you don't want to charge.  Then after the initial XX day trial there would be a "tenure_type": "REGULAR" for charging every month.

Body:
What type of billing plan for what type of recurring payments? There's like 5+ different APIs and versions.

With the the newest Subscriptions API, you could have a plan that charges a setup fee for your instant charge:

  "payment_preferences": {
    "setup_fee": {
      "value": "10",
      "currency_code": "USD"
    },

and in billing cycles has a "tenure_type": "TRIAL" with no pricing_scheme that lasts XX amount of days, where XX is calculated by you to be the number of days remaining in the current month that you don't want to charge.  Then after the initial XX day trial there would be a "tenure_type": "REGULAR" for charging every month.


问:
How To ALTER New Columns In Table by Items from ListBox
I Have Database worked perfect in MS Access 2010 with code that ALTER New Fields in Table all that from ListBox items that filling from another table by user code below:

```<code>Sub AlterTableX()
   Dim intLoop As Integer
   Dim strSQL As String
   Dim strSQL1 As String
   For intLoop = 0 To Me.field_row.ListCount - 1
   strSQL = "ALTER TABLE Emp_Sal ADD " & _
   Me.field_row.Column(0, [intLoop]) & "  LONG INTEGER"
   CurrentProject.Connection.Execute strSQL
   strSQL1 = "ALTER TABLE tbl_General ADD " & _
   Me.field_row.Column(0, [intLoop]) & "  LONG INTEGER"
   CurrentProject.Connection.Execute strSQL1
   Next intLoop
'  MsgBox "Success Adding Columns", vbOKOnly, "Success"
End Sub
</code>```

Well, Now I want to convert that VBA code to VB.NET 2012

I want your help.

答:
If you are just looking to execute the same commands in VB.NET, then try something like this.  It should get you started but best you read up on ADO.NET as sugested in comments</p>

```<code>    Using SqlCMD As New OleDb.OleDbCommand()
        SqlCMD.Connection = CurrentProject.Connection
        Try
            SqlCMD.Connection.Open()
            For intLoop As Integer = 0 To Me.field_row.ListCount - 1
                SqlCMD.CommandText = "ALTER TABLE Emp_Sal ADD " & Me.field_row.Column(0, [intLoop]) & "  LONG INTEGER"
                SqlCMD.ExecuteNonQuery()
                SqlCMD.CommandText = "ALTER TABLE tbl_General ADD " & Me.field_row.Column(0, [intLoop]) & "  LONG INTEGER"
                SqlCMD.ExecuteNonQuery()
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message, "ERROR ALTERING TABLE")
        Finally
            SqlCMD.Connection.Close()
        End Try
    End Using
</code>```

Body:
I Have Database worked perfect in MS Access 2010 with code that ALTER New Fields in Table all that from ListBox items that filling from another table by user code below:

Sub AlterTableX()
   Dim intLoop As Integer
   Dim strSQL As String
   Dim strSQL1 As String
   For intLoop = 0 To Me.field_row.ListCount - 1
   strSQL = "ALTER TABLE Emp_Sal ADD " & _
   Me.field_row.Column(0, [intLoop]) & "  LONG INTEGER"
   CurrentProject.Connection.Execute strSQL
   strSQL1 = "ALTER TABLE tbl_General ADD " & _
   Me.field_row.Column(0, [intLoop]) & "  LONG INTEGER"
   CurrentProject.Connection.Execute strSQL1
   Next intLoop
'  MsgBox "Success Adding Columns", vbOKOnly, "Success"
End Sub

Well, Now I want to convert that VBA code to VB.NET 2012

I want your help.

Body:
If you are just looking to execute the same commands in VB.NET, then try something like this.  It should get you started but best you read up on ADO.NET as sugested in comments

    Using SqlCMD As New OleDb.OleDbCommand()
        SqlCMD.Connection = CurrentProject.Connection
        Try
            SqlCMD.Connection.Open()
            For intLoop As Integer = 0 To Me.field_row.ListCount - 1
                SqlCMD.CommandText = "ALTER TABLE Emp_Sal ADD " & Me.field_row.Column(0, [intLoop]) & "  LONG INTEGER"
                SqlCMD.ExecuteNonQuery()
                SqlCMD.CommandText = "ALTER TABLE tbl_General ADD " & Me.field_row.Column(0, [intLoop]) & "  LONG INTEGER"
                SqlCMD.ExecuteNonQuery()
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message, "ERROR ALTERING TABLE")
        Finally
            SqlCMD.Connection.Close()
        End Try
    End Using


问:
Firebase RealTime Databse, No Returns?
New to firebase databases here, trying it out for a login. (wanna use username's instead of emails)

So using a Realtime Database, But I can't seem to get anything out of the database.
I can't see anything wrong with what i'm doing. At first thought it was because of the Rules, same results after setting them to auth == null.

Any idea's?

```<code> public FirebaseClient firebase = new FirebaseClient("https://MyApp.firebaseio.com/");
 private readonly string ChildName = "Users";

 public async Task<List<Userlogin>> GetAllUser()
        {

         return (await firebase
                .Child(ChildName)
                .OnceAsync<Userlogin>()).Select(item =>
                new Userlogin
                {
                    user_login = item.Object.user_login,
                    passwords = item.Object.passwords
                }).ToList();
        }

  public async Task<Userlogin> GetUser(string user_login)
        {
            try
            {
                var allUsers = await GetAllUser();
                await firebase
                .Child(ChildName)
                .OnceAsync<Userlogin>();
                return allUsers.Where(a => a.user_login == user_login).FirstOrDefault();
            }
            catch (Exception e)
            {
                Crashes.TrackError(e);
                return null;
            }
        }

private async void Login_Phase1()
{
            try
            {
                if (string.IsNullOrEmpty(Usernamelabel.Text) || string.IsNullOrEmpty(Password.Text))
                    await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
                else
                {
                    var user = await GetUser(Usernamelabel.Text);

                    if (user != null)
                        if (Usernamelabel.Text == user.user_login && Password.Text == user.passwords)
                        {
                            Login_Phase2();
                        }
                        else
                            await App.Current.MainPage.DisplayAlert("Login Fail", "Please enter correct Email and Password", "OK");
                    else
                        await App.Current.MainPage.DisplayAlert("Login Fail", "User not found", "OK");
                }

            }
            catch (Exception e)
            {
                Crashes.TrackError(e);
            }
}
</code>```

答:
Note:

This might not be the case always I believe

When Importing your Databse "Users" In my case if you import using a Json File.

For some odd reason I had to go create a Manual User on the database for it to register the other users on the Call.

Solution:

Just create a New Child on the Database With the correct properties.

Title: Firebase RealTime Databse, No Returns?

Body:
New to firebase databases here, trying it out for a login. (wanna use username's instead of emails)

So using a Realtime Database, But I can't seem to get anything out of the database.
I can't see anything wrong with what i'm doing. At first thought it was because of the Rules, same results after setting them to auth == null.

Any idea's?

 public FirebaseClient firebase = new FirebaseClient("https://MyApp.firebaseio.com/");
 private readonly string ChildName = "Users";

 public async Task<List<Userlogin>> GetAllUser()
        {

         return (await firebase
                .Child(ChildName)
                .OnceAsync<Userlogin>()).Select(item =>
                new Userlogin
                {
                    user_login = item.Object.user_login,
                    passwords = item.Object.passwords
                }).ToList();
        }

  public async Task<Userlogin> GetUser(string user_login)
        {
            try
            {
                var allUsers = await GetAllUser();
                await firebase
                .Child(ChildName)
                .OnceAsync<Userlogin>();
                return allUsers.Where(a => a.user_login == user_login).FirstOrDefault();
            }
            catch (Exception e)
            {
                Crashes.TrackError(e);
                return null;
            }
        }

private async void Login_Phase1()
{
            try
            {
                if (string.IsNullOrEmpty(Usernamelabel.Text) || string.IsNullOrEmpty(Password.Text))
                    await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
                else
                {
                    var user = await GetUser(Usernamelabel.Text);

                    if (user != null)
                        if (Usernamelabel.Text == user.user_login && Password.Text == user.passwords)
                        {
                            Login_Phase2();
                        }
                        else
                            await App.Current.MainPage.DisplayAlert("Login Fail", "Please enter correct Email and Password", "OK");
                    else
                        await App.Current.MainPage.DisplayAlert("Login Fail", "User not found", "OK");
                }

            }
            catch (Exception e)
            {
                Crashes.TrackError(e);
            }
}


问:
Why is my toFixed() function not working?
Here's the relevant code.  I've confirmed with the alert that the correct number is saved, it's just not being changed to 2 decimal places. </p>

```<code>if ($(this).attr('name') == 'time') {
    var value = $(this).val();
    parseFloat(value).toFixed(2);
    alert(value);
    editEntry.time = value;
}
</code>```

答:
I tried function toFixed(2) many times. Every time console shows "toFixed() is not a function".

but how I resolved is By using Math.round()

eg:

```<code>if ($(this).attr('name') == 'time') {
    var value = parseFloat($(this).val());
    value = Math.round(value*100)/100; // 10 defines 1 decimals, 100 for 2, 1000 for 3
    alert(value);
}
</code>```

this thing surely works for me and it might help you guys too...

Body:
Here's the relevant code.  I've confirmed with the alert that the correct number is saved, it's just not being changed to 2 decimal places.

if ($(this).attr('name') == 'time') {
    var value = $(this).val();
    parseFloat(value).toFixed(2);
    alert(value);
    editEntry.time = value;
}

Body:
I tried function toFixed(2) many times. Every time console shows "toFixed() is not a function".

but how I resolved is By using Math.round()

eg:

if ($(this).attr('name') == 'time') {
    var value = parseFloat($(this).val());
    value = Math.round(value*100)/100; // 10 defines 1 decimals, 100 for 2, 1000 for 3
    alert(value);
}

this thing surely works for me and it might help you guys too...


问:
UISegmentedControl register taps on selected segment
I have a segmented control where the user can select how to order a list. Works fine.

However, I would like that when an already selected segment is tapped, the order gets inverted. I have all the code in place, but I don't know how to register the taps on those segments. It seems the only control event you can use is UIControlEventValueChanged, but that isn't working (since the selected segment isn't actually changing).

Is there a solution for this? And if so, what is it?

Thanks in advance!

答:
Swift 5

```<code>class ReselectableSegmentedControl: UISegmentedControl {
    // Captures existing selected segment on touchesBegan.
    var oldValue: Int!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.oldValue = self.selectedSegmentIndex
        super.touchesBegan(touches, with: event)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)

        if self.oldValue == self.selectedSegmentIndex {
            self.sendActions(for: .valueChanged)
        }
    }
}
</code>```

From here

ContentLicense: CC BY-SA 2.5

Body:
Swift 5

class ReselectableSegmentedControl: UISegmentedControl {
    // Captures existing selected segment on touchesBegan.
    var oldValue: Int!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.oldValue = self.selectedSegmentIndex
        super.touchesBegan(touches, with: event)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)

        if self.oldValue == self.selectedSegmentIndex {
            self.sendActions(for: .valueChanged)
        }
    }
}

From here


问:
Angular 4 Portal/CdkPortal not working in new child window
I'm working in an Angular 4 app and I need to show a specific component in a new child window. So I research for a solution (i'm NOT looking for a solution with routing by url 'couse my server always redirec to index with window.open('some URL'), so window.open('') with ataching might be the solution) and I found this stackblitz example
StackBlitz Example

in that example, are using CdkPortal . The problem is apparently cdk portal is not in angular 4 (I'm not shure, but this error is showing @angular/cdk/portal"' has no exported member 'CdkPortal')

I just copy and paste the previous example 'couse is exactly what I need, but in my angular version is not working.

Is there some equivalent example for angular 4?

ADITIONAL

in the example, they are using this code fragment to show the window

```<code><window *ngIf="showPortal">
  <h2>Hello world from amother window!!</h2>
  <button (click)="this.showPortal = false">Close me!</button>
</window>
</code>```

so my question is... is posible to add other component inside the component that I want to atach in the portal? Something like this.

```<code><window *ngIf="showPortal">
  <my-other-component [currentValue]="someValue"></my-other-component>
</window>
</code>```

If it is posible, Would the component work correctly?

答:
Try this. This will generate a child window without use of CdkPortal.

I have used generic window.open method to open a new window. also i have used name property of window to get reference of opened window.

app.component.ts

```<code>import { Component,ComponentFactoryResolver, ViewChild, ViewContainerRef,Injector } from '@angular/core';
import { DynamicWindowComponent } from './dynamic-window/dynamic-window.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  injector: Injector;
  OpenWindow : any

  constructor(private resolver: ComponentFactoryResolver) { }

  open(): void {
    const componentFactory = this.resolver.resolveComponentFactory(DynamicWindowComponent);
    let componentRef  = componentFactory.create(this.injector);
    this.OpenWindow = window.open('', 'childwindow', 'width=400,height=400,left=150,top=200');
    this.OpenWindow.document.body.innerHTML = "";
    this.OpenWindow.document.body.appendChild(componentRef.location.nativeElement);
  }

  close(){
    this.OpenWindow.close()
  }
}
</code>```

app.component.html

```<code><button (click)="open()">Dynamically Add Component</button>
</code>```

dynamic-window.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dynamic-window',
  templateUrl: './dynamic-window.component.html',
  styleUrls: ['./dynamic-window.component.css']
})
export class DynamicWindowComponent{
  close(){
    // get refence of child window by its name and close it
    let existingWin = window.open('', 'childwindow');
    existingWin.close();
  }
}
</code>```

dynamic-window.component.html

```<code><p>Dynamic Component</p>
 <button (click)="close()">Close me!</button>
</code>```

Working example link

https://stackblitz.com/edit/angular-rbapx4?embed=1&file=src/app/app.component.ts

Body:
I'm working in an Angular 4 app and I need to show a specific component in a new child window. So I research for a solution (i'm NOT looking for a solution with routing by url 'couse my server always redirec to index with window.open('some URL'), so window.open('') with ataching might be the solution) and I found this stackblitz example
StackBlitz Example

in that example, are using CdkPortal . The problem is apparently cdk portal is not in angular 4 (I'm not shure, but this error is showing @angular/cdk/portal"' has no exported member 'CdkPortal')

I just copy and paste the previous example 'couse is exactly what I need, but in my angular version is not working.

Is there some equivalent example for angular 4?

ADITIONAL

in the example, they are using this code fragment to show the window

<window *ngIf="showPortal">

Hello world from amother window!!

  <button (click)="this.showPortal = false">Close me!</button>
</window>

so my question is... is posible to add other component inside the component that I want to atach in the portal? Something like this.

<window *ngIf="showPortal">
  <my-other-component [currentValue]="someValue"></my-other-component>
</window>

If it is posible, Would the component work correctly?

Body:
Try this. This will generate a child window without use of CdkPortal.

I have used generic window.open method to open a new window. also i have used name property of window to get reference of opened window.

app.component.ts

import { Component,ComponentFactoryResolver, ViewChild, ViewContainerRef,Injector } from '@angular/core';
import { DynamicWindowComponent } from './dynamic-window/dynamic-window.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  injector: Injector;
  OpenWindow : any

  constructor(private resolver: ComponentFactoryResolver) { }

  open(): void {
    const componentFactory = this.resolver.resolveComponentFactory(DynamicWindowComponent);
    let componentRef  = componentFactory.create(this.injector);
    this.OpenWindow = window.open('', 'childwindow', 'width=400,height=400,left=150,top=200');
    this.OpenWindow.document.body.innerHTML = "";
    this.OpenWindow.document.body.appendChild(componentRef.location.nativeElement);
  }

  close(){
    this.OpenWindow.close()
  }
}

app.component.html

<button (click)="open()">Dynamically Add Component</button>

dynamic-window.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dynamic-window',
  templateUrl: './dynamic-window.component.html',
  styleUrls: ['./dynamic-window.component.css']
})
export class DynamicWindowComponent{
  close(){
    // get refence of child window by its name and close it
    let existingWin = window.open('', 'childwindow');
    existingWin.close();
  }
}

dynamic-window.component.html

<p>Dynamic Component</p>
 <button (click)="close()">Close me!</button>

Working example link

https://stackblitz.com/edit/angular-rbapx4?embed=1&file=src/app/app.component.ts