问:
How to pass the state true or false from a child to the parent- React
I have two components, one parent (Widgets) and another son (Telefono). The "Telefono" component has the notInCall status and with it I paint or not a certain part of the code.
On the other hand I have the showComponent() function that is in the parent with which I show or not the child component (Telefono) and two other components.
I need to recover from the parent, in the showComponent() function the current status (true or false) of notInCall but I do not know how to do it.

Edit: I think I have not explained well. In the child I use a conditional this.state.notInCall to show or not part of the code. I need to pass the true or false response to the parent. If {this.state.notInCall ? (some code) : (another code)}. If this.state.notInCallon the child is true do one thing and if it is false do another

This is my parent component (Widgets)

```<code>class Widgets extends Component {
    constructor(props) {
        super(props);
        this.state = {
            componente: 1,
            //notInCall: false,
        };
        this.showComponent = this.showComponent.bind(this);
    }

    showComponent(componentName) {
        /*this.setState({
            notInCall: false,
        });*/
        if(this.state.notInCall === false){
            this.setState({
                componente: Telefono,
                addActive: Telefono,
            });
            alert(this.state.notInCall + ' running? Componente:' + componentName);
            console.log(this.state.notInCall);
        }else{
            alert('verdad');
            this.setState({
                componente: componentName,
                addActive: componentName,
            });
        }
        console.log(this.state.notInCall);
    }

    renderComponent(){
        switch(this.state.componente) {
            case "ChatInterno":
                return <ChatInterno />
            case "HistorialLlamadas":
                return <HistorialLlamadas />
            case "Telefono":
            default:
                return <Telefono showComponent={this.showComponent}/>
        }
    }

    render(){
        return (
            <div id="bq-comunicacion">
                <nav>
                    <ul>
                        <li><button onClick={() => this.showComponent('Telefono')} id="mn-telefono" className={this.state.addActive === 'Telefono' ? 'active' : ''}><Icon icon="telefono" className='ico-telefono'/></button></li>
                        <li><button onClick={() => this.showComponent('ChatInterno')} id="mn-chat" className={this.state.addActive === 'ChatInterno' ? 'active' : ''}><Icon icon="chat-interno" className='ico-chat-interno'/></button></li>
                        <li><button onClick={() => this.showComponent('HistorialLlamadas')} id="mn-llamadas" className={this.state.addActive === 'HistorialLlamadas' ? 'active' : ''}><Icon icon="historial-llamadas" className='ico-historial-llamadas'/></button></li>
                    </ul>
                </nav>
                <div className="content">
                    { this.renderComponent() }
                </div>
            </div>
        );
    }
}
</code>```

This is my child component (Telefono)

```<code>class Telefono extends Component {
    constructor(props) {
        super(props);

        this.inputTelephone = React.createRef();

        ["update", "reset", "deleteClickNumber", "closeAlert", "handleKeyPress",].forEach((method) => {
            this[method] = this[method].bind(this);
        });

        this.state = this.initialState = {
            notInCall: true,
            isRunning: false,
        };
    }

    phoneCall(e){
        e.preventDefault();
        this.props.showComponent(this.state.notInCall);

        if(this.state.inputContent.length < 2){
            this.setState({
                warningEmptyPhone: true,
            });

            this.change = setTimeout(() => {
                this.setState({
                    warningEmptyPhone: false
                })
            }, 5000)
        }else if(this.state.inputContent.length >= 2 ){
            this.setState({
                notInCall: !this.state.notInCall,
                isRunning: !this.state.isRunning,
                componente: 'Telefono',
            },
                () => {
                    this.state.isRunning ? this.startTimer() : clearInterval(this.timer);
                    //console.log(this.componente);
                });
        }
    }

    render(){
        return(
            <div className="pad sb-content">
                {this.state.notInCall
                    ? (
                        <>
                        <div className="dial-pad">
                            <div className="digits">
                                <Numbers numbers={this.state.numbers}
                                />
                            </div>
                        </div>
                        <div className="btn-call call" onClick={this.phoneCall.bind(this)}>
                            <Icon icon="telefono" className='ico-telefono'/>
                            <span>LLAMAR</span>
                        </div>
                        </>
                    )
                    : (
                        <div className="call-pad">
                            <div id="ca-number" className="ca-number">{this.state.inputContent}</div>
                            <TimeElapsed id="timer" timeElapsed={timeElapsed}/>
                        </div>

                    )}
            </div>
        );
    }
}
</code>```

Thanks for the help

答:
You can create a handle in parent, like:

handleNotInCall (notInCall) {
  // handle here
}

```

<p>And pass this handle to child:</p>

<pre class="lang-js prettyprint-override"><code><Telefono handleNotInCall={this.handleNotInCall} />

</code>```

In child you call like this:

this.props.handleNotInCall(<param here>)

```

<p><strong>UPDATE</strong></p>

<p>on parent:
<strong>On Parent:</strong></p>

<ul>
<li>put <code>notInCall</code> in state</li>
<li>create a handle for <code>notInCall</code></li>
<li>pass for child handle and state</li>
</ul>

<pre class="lang-js prettyprint-override"><code>// state
this.state = {
  componente: 1,
  notInCall: false,
};
// create a handle
handleNotInCall (notInCall) {
  this.setState({notInCall});
}
// pass both for child
<Telefono handleNotInCall={this.handleNotInCall} notInCall={this.state.notInCall}/>
</code>```

In child, where you do:

this.setState({
  notInCall: !this.state.notInCall,
  isRunning: !this.state.isRunning,
  componente: 'Telefono',
})
// change for
this.props.handleNotInCall(!this.props.notInCall)
this.setState({
  isRunning: !this.state.isRunning,
  componente: 'Telefono',
})

// where you use for compare
this.state.notInCall ?
// change for:
this.props.notInCall ?
```

Body:
I have two components, one parent (Widgets) and another son (Telefono). The "Telefono" component has the notInCall status and with it I paint or not a certain part of the code.
On the other hand I have the showComponent() function that is in the parent with which I show or not the child component (Telefono) and two other components.
I need to recover from the parent, in the showComponent() function the current status (true or false) of notInCall but I do not know how to do it.

Edit: I think I have not explained well. In the child I use a conditional this.state.notInCall to show or not part of the code. I need to pass the true or false response to the parent. If {this.state.notInCall ? (some code) : (another code)}. If this.state.notInCallon the child is true do one thing and if it is false do another

This is my parent component (Widgets)

class Widgets extends Component {
    constructor(props) {
        super(props);
        this.state = {
            componente: 1,
            //notInCall: false,
        };
        this.showComponent = this.showComponent.bind(this);
    }

    showComponent(componentName) {
        /*this.setState({
            notInCall: false,
        });*/
        if(this.state.notInCall === false){
            this.setState({
                componente: Telefono,
                addActive: Telefono,
            });
            alert(this.state.notInCall + ' running? Componente:' + componentName);
            console.log(this.state.notInCall);
        }else{
            alert('verdad');
            this.setState({
                componente: componentName,
                addActive: componentName,
            });
        }
        console.log(this.state.notInCall);
    }

    renderComponent(){
        switch(this.state.componente) {
            case "ChatInterno":
                return <ChatInterno />
            case "HistorialLlamadas":
                return <HistorialLlamadas />
            case "Telefono":
            default:
                return <Telefono showComponent={this.showComponent}/>
        }
    }

    render(){
        return (

<button onClick={() => this.showComponent('Telefono')} id="mn-telefono" className={this.state.addActive === 'Telefono' ? 'active' : ''}><Icon icon="telefono" className='ico-telefono'/></button>

<button onClick={() => this.showComponent('ChatInterno')} id="mn-chat" className={this.state.addActive === 'ChatInterno' ? 'active' : ''}><Icon icon="chat-interno" className='ico-chat-interno'/></button>

<button onClick={() => this.showComponent('HistorialLlamadas')} id="mn-llamadas" className={this.state.addActive === 'HistorialLlamadas' ? 'active' : ''}><Icon icon="historial-llamadas" className='ico-historial-llamadas'/></button>

                    { this.renderComponent() }

        );
    }
}

This is my child component (Telefono)

class Telefono extends Component {
    constructor(props) {
        super(props);

        this.inputTelephone = React.createRef();

        ["update", "reset", "deleteClickNumber", "closeAlert", "handleKeyPress",].forEach((method) => {
            this[method] = this[method].bind(this);
        });

        this.state = this.initialState = {
            notInCall: true,
            isRunning: false,
        };
    }

    phoneCall(e){
        e.preventDefault();
        this.props.showComponent(this.state.notInCall);

        if(this.state.inputContent.length < 2){
            this.setState({
                warningEmptyPhone: true,
            });

            this.change = setTimeout(() => {
                this.setState({
                    warningEmptyPhone: false
                })
            }, 5000)
        }else if(this.state.inputContent.length >= 2 ){
            this.setState({
                notInCall: !this.state.notInCall,
                isRunning: !this.state.isRunning,
                componente: 'Telefono',
            },
                () => {
                    this.state.isRunning ? this.startTimer() : clearInterval(this.timer);
                    //console.log(this.componente);
                });
        }
    }

    render(){
        return(

                {this.state.notInCall
                    ? (
                        <>

                                <Numbers numbers={this.state.numbers}
                                />

                            <Icon icon="telefono" className='ico-telefono'/>
                            LLAMAR

                        </>
                    )
                    : (

{this.state.inputContent}

                            <TimeElapsed id="timer" timeElapsed={timeElapsed}/>

                    )}

        );
    }
}

Thanks for the help

Body:
You can create a handle in parent, like:

handleNotInCall (notInCall) {
  // handle here
}

And pass this handle to child:

<Telefono handleNotInCall={this.handleNotInCall} />

In child you call like this:

this.props.handleNotInCall(<param here>)

UPDATE

on parent:
On Parent:

put notInCall in state

create a handle for notInCall

pass for child handle and state

// state
this.state = {
  componente: 1,
  notInCall: false,
};
// create a handle
handleNotInCall (notInCall) {
  this.setState({notInCall});
}
// pass both for child
<Telefono handleNotInCall={this.handleNotInCall} notInCall={this.state.notInCall}/>

In child, where you do:

this.setState({
  notInCall: !this.state.notInCall,
  isRunning: !this.state.isRunning,
  componente: 'Telefono',
})
// change for
this.props.handleNotInCall(!this.props.notInCall)
this.setState({
  isRunning: !this.state.isRunning,
  componente: 'Telefono',
})

// where you use for compare
this.state.notInCall ?
// change for:
this.props.notInCall ?


来源: stackexchange

问:
C# Selenium XPath data from row that contains a span
I am trying to grab data from a table that has two columns. The rows do not have a distinct identifier. But I can search the first column for specifics to find out if I should grab the second column's data.  There are multiple rows in the table although the example below I am just showing one row. </p>

```<code><table id="subtotals-marketplace-table" class="a-normal a-align-bottom a-spacing-none a-size-small">
<tbody><tr class="small-line-height">
<td>
    <span>
        Total:
    </span>
</td>
<td class="a-text-right aok-nowrap a-nowrap">
    $12.80
</td>
</tr>
</tbody></table>
</code>```

<p>I need to search for Total: and then grab the dollar amount in the next column.  I've tried multiple iterations of something along these lines but can't seem to find the correct syntax: </p>

```<code>driver.FindElement(
                    By.XPath(
                        "//*[@id='subtotals-marketplace-table']//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

driver.FindElement(
                    By.XPath(
                        "//table[@id='subtotals-marketplace-table']//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

driver.FindElement(
                    By.XPath(
                        "//table[@id='subtotals-marketplace-table']/tbody//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;
</code>```

答:
Here are different options.

Option 1:

```<code>//table[@id='subtotals-marketplace-table']//tr[td[normalize-space(.)='Total:']]/td[2]
</code>```

Option 2:

```<code>//table[@id='subtotals-marketplace-table']//td[normalize-space(.)='Total:']/following-sibling::td
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to grab data from a table that has two columns. The rows do not have a distinct identifier. But I can search the first column for specifics to find out if I should grab the second column's data.  There are multiple rows in the table although the example below I am just showing one row.

        Total:

    $12.80

I need to search for Total: and then grab the dollar amount in the next column.  I've tried multiple iterations of something along these lines but can't seem to find the correct syntax:

driver.FindElement(
                    By.XPath(
                        "//*[@id='subtotals-marketplace-table']//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

driver.FindElement(
                    By.XPath(
                        "//table[@id='subtotals-marketplace-table']//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

driver.FindElement(
                    By.XPath(
                        "//table[@id='subtotals-marketplace-table']/tbody//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

Body:
Here are different options.

Option 1:

//table[@id='subtotals-marketplace-table']//tr[td[normalize-space(.)='Total:']]/td[2]

Option 2:

//table[@id='subtotals-marketplace-table']//td[normalize-space(.)='Total:']/following-sibling::td


问:
Is Modifying the content of a file possible in mqfte using ant task?
I have to substitute the letter "A" with letter "C" in the content of a txt file.

Let test.txt be a txt file. The content is as follows:

Ace Apple

I need the content in the destination folder to be as :

Cce Cpple.

Is this possible in mqfte using ant tasks?

答:
The short answer is "yes."

The longer answer is that you can do anything with Ant that can be scripted, including calling other scripts.  The approach would be to use a post-destination call that would edit the file after it arrives.  This call won't fire if the file transfer fails.  If the transfer succeeds the post-destination call does fire and will run your task or script to edit the file.  Just remember that if you configure this to run as a monitor, it will fire on every file transfer.  If you want to run it as an ad-hoc transfer you will need to submit it from the command line since the GUI does not support the pre/post calls.

ContentLicense: CC BY-SA 3.0


问:
Zoom-IN/OUT canvas in pdf-reader, cause mouse coordinates to change it's position
I am currently implementing a functionality to place an canvas over pdf in pdf-reader so that we can draw on top of canvas, so the pdf in which canvas is placed can be zoomed-in and out to much extent, and I have to ensure that canvas should also resize as per the pdf, so that drawing on top of it remains intact, for resizing canvas I am using the canvas.style.width , drawing.style.height to resize it when pdf-resizes.

But now my concern is that on resizing mouse-pointer changes its position, for instance in the attached image my mouse is in bottom-right and it draws in top-left, due to shifting in mouse coordinates.

I am using RxJS for drawing, and capturing events, but I am not been able to figure out how to take care of mouse position in summary, I want coordinates to scale as per canvas resize.

```<code>  private captureEvents(canvasEl: HTMLCanvasElement) {
    // this will capture all mousedown events from the canvas element
    this.drawingSubscription = fromEvent(canvasEl, 'mousedown')
      .pipe(
        switchMap((e) => {

          // after a mouse down, we'll record all mouse moves
          return fromEvent(canvasEl, 'mousemove')
            .pipe(
              // we'll stop (and unsubscribe) once the user releases the mouse
              // this will trigger a 'mouseup' event
              takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) => {
                console.log('e', e.type, e);
                const prevPos = {
                  x: null,
                  y: null
                };
                this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
                console.log('coordinatesArray', this.coordinatesArray);
              })),
              // we'll also stop (and unsubscribe) once the mouse leaves the canvas (mouseleave event)
              takeUntil(fromEvent(canvasEl, 'mouseleave')),
              // pairwise lets us get the previous value to draw a line from
              // the previous point to the current point
              pairwise()
            )
        })
      )
      .subscribe((res: [MouseEvent, MouseEvent]) => {
        const rect = canvasEl.getBoundingClientRect();
        // previous and current position with the offset
        const prevPos = {
          x: res[0].clientX - rect.left,
          y: res[0].clientY - rect.top
        };

        const currentPos = {
          x: res[1].clientX - rect.left,
          y: res[1].clientY - rect.top
        };

        this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
        // console.log('coordinatesArray', this.coordinatesArray);
        this.drawOnCanvas(prevPos, currentPos);
      });
  }
</code>```

Moreover, I am not generating the new canvas on every zoom-in/out, I am just modifying the it's height/width as per dimensions of page on top of which it is present.

答:
I eventually solved it after spending a hell lot of time.
I have posted the answer in relevant thread that will be helpful to others going through the similar problem.

https://stackoverflow.com/a/56363476/5763627

Body:
I am currently implementing a functionality to place an canvas over pdf in pdf-reader so that we can draw on top of canvas, so the pdf in which canvas is placed can be zoomed-in and out to much extent, and I have to ensure that canvas should also resize as per the pdf, so that drawing on top of it remains intact, for resizing canvas I am using the canvas.style.width , drawing.style.height to resize it when pdf-resizes.

But now my concern is that on resizing mouse-pointer changes its position, for instance in the attached image my mouse is in bottom-right and it draws in top-left, due to shifting in mouse coordinates.

I am using RxJS for drawing, and capturing events, but I am not been able to figure out how to take care of mouse position in summary, I want coordinates to scale as per canvas resize.

  private captureEvents(canvasEl: HTMLCanvasElement) {
    // this will capture all mousedown events from the canvas element
    this.drawingSubscription = fromEvent(canvasEl, 'mousedown')
      .pipe(
        switchMap((e) => {

          // after a mouse down, we'll record all mouse moves
          return fromEvent(canvasEl, 'mousemove')
            .pipe(
              // we'll stop (and unsubscribe) once the user releases the mouse
              // this will trigger a 'mouseup' event
              takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) => {
                console.log('e', e.type, e);
                const prevPos = {
                  x: null,
                  y: null
                };
                this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
                console.log('coordinatesArray', this.coordinatesArray);
              })),
              // we'll also stop (and unsubscribe) once the mouse leaves the canvas (mouseleave event)
              takeUntil(fromEvent(canvasEl, 'mouseleave')),
              // pairwise lets us get the previous value to draw a line from
              // the previous point to the current point
              pairwise()
            )
        })
      )
      .subscribe((res: [MouseEvent, MouseEvent]) => {
        const rect = canvasEl.getBoundingClientRect();
        // previous and current position with the offset
        const prevPos = {
          x: res[0].clientX - rect.left,
          y: res[0].clientY - rect.top
        };

        const currentPos = {
          x: res[1].clientX - rect.left,
          y: res[1].clientY - rect.top
        };

        this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
        // console.log('coordinatesArray', this.coordinatesArray);
        this.drawOnCanvas(prevPos, currentPos);
      });
  }

Moreover, I am not generating the new canvas on every zoom-in/out, I am just modifying the it's height/width as per dimensions of page on top of which it is present.


答:
Try following Xpath.

```<code>//table[@id='subtotals-marketplace-table']//tr//td[@class='a-text-right aok-nowrap a-nowrap']
</code>```

OR

```<code>//table[@id='subtotals-marketplace-table']//tr//span[contains(.,'Total:')]/parent::td/following-sibling::td[@class='a-text-right aok-nowrap a-nowrap']
</code>```

Title: C# Selenium XPath data from row that contains a span

Body:
Try following Xpath.

//table[@id='subtotals-marketplace-table']//tr//td[@class='a-text-right aok-nowrap a-nowrap']

OR

//table[@id='subtotals-marketplace-table']//tr//span[contains(.,'Total:')]/parent::td/following-sibling::td[@class='a-text-right aok-nowrap a-nowrap']


问:
PowerShell If Statement Failure
I need another set of eyes because I'm certain this is simple but it's kicking my butt right now. I'm writing a script to install Windows roles/features on both Server 2008 and Server 2012 machines.

I know that 2008 uses Add-WindowsFeature whereas 2012 uses Install-WindowsFeature.  So my goal is to look at the OS and if it's 2008 create a variable called $Install with a value of Add-WindowsFeature and if it's not 2008 give it the value of Install-WindowsFeature.

This is what I have now:

```<code>$OS = (Get-WmiObject Win32_OperatingSystem).Name

if ($OS -like '2008') {
    $Install = 'Add-WindowsFeature'
} else {
    $Install = 'Install-WindowsFeature'
}
</code>```

Currently, when I call up the $OS variable I get a returned value of:

```
Microsoft Windows Server 2008 R2 Standard |C:\Windows|\Device\Harddisk0\Partition2
```

But when I call up the $Install variable I get a returned value of:

```
Install-WindowsFeature
```

I've also tried -contains instead of -like but I get the same result.  I've also tried eliminating the spaces before the curly brackets, but still no change.  What am I doing wrong?

答:
The -like operator is not a regular expression comparison. If you don't have any wildcards, the -like match is the same as an equality comparison.

You need to either include wildcards, like this:

```<code>if ($OS -like '*2008*') {
</code>```

do a contains check, like this:

```<code>if ($OS.Contains('2008')) {
</code>```

or use a regular expression match, like this:

```<code>if ($OS -match '2008') {
</code>```

Documentation is here:

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators

Title: PowerShell If Statement Failure

Body:
I need another set of eyes because I'm certain this is simple but it's kicking my butt right now. I'm writing a script to install Windows roles/features on both Server 2008 and Server 2012 machines.

I know that 2008 uses Add-WindowsFeature whereas 2012 uses Install-WindowsFeature.  So my goal is to look at the OS and if it's 2008 create a variable called $Install with a value of Add-WindowsFeature and if it's not 2008 give it the value of Install-WindowsFeature.

This is what I have now:

$OS = (Get-WmiObject Win32_OperatingSystem).Name

if ($OS -like '2008') {
    $Install = 'Add-WindowsFeature'
} else {
    $Install = 'Install-WindowsFeature'
}

Currently, when I call up the $OS variable I get a returned value of:

Microsoft Windows Server 2008 R2 Standard |C:\Windows|\Device\Harddisk0\Partition2

But when I call up the $Install variable I get a returned value of:

Install-WindowsFeature

I've also tried -contains instead of -like but I get the same result.  I've also tried eliminating the spaces before the curly brackets, but still no change.  What am I doing wrong?

Body:
The -like operator is not a regular expression comparison. If you don't have any wildcards, the -like match is the same as an equality comparison.

You need to either include wildcards, like this:

if ($OS -like '*2008*') {

do a contains check, like this:

if ($OS.Contains('2008')) {

or use a regular expression match, like this:

if ($OS -match '2008') {

Documentation is here:

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators


问:
Writing subscript in Mathjax?
I want to type this .

I have tried like this

```<code>$$\lambda=\frac{0.693}{t_\frac{1}{2}}$$
</code>```

Also,

```<code>$$\lambda=\frac{0.693}{{t}_\frac{1}{2}}$$
</code>```

Also,

```<code>$$\lambda=\frac{0.693}{t_{\frac{1}{2}}}$$
</code>```

But it don't work it display something like this

This code

also gives something that we don't want

Mathjax Configuration

```<code><div class="layout"><script type="text/x-mathjax-config">
MathJax.Hub.Config({
  TeX: {extensions: ["AMSmath.js","AMSsymbols.js","mhchem.js","noErrors.js","noUndefined.js"]},
  tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
      processEscapes: true
    },
});
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"></script>
</code>```

Browser= Google Chrome
OS= Windows 8.1

答:
Use _{}

_{YOUR EXPRESSION}

Example:

```<code>$$Y_n = Y_{n-1}+{{(d/n)}sin(θ\pm n*Δ)}.$$
</code>```

Result:

Title: Writing subscript in Mathjax?

Body:
I want to type this .

I have tried like this

$$\lambda=\frac{0.693}{t_\frac{1}{2}}$$

Also,

$$\lambda=\frac{0.693}{{t}_\frac{1}{2}}$$

Also,

$$\lambda=\frac{0.693}{t_{\frac{1}{2}}}$$

But it don't work it display something like this

This code

also gives something that we don't want

Mathjax Configuration

Browser= Google Chrome
OS= Windows 8.1

Body:
Use _{}

_{YOUR EXPRESSION}

Example:

$$Y_n = Y_{n-1}+{{(d/n)}sin(θ\pm n*Δ)}.$$

Result:


问:
bulk delete - cascading delete performance killer?
My SQL Server 2008R2 database has a lot of large, related tables:

master

detail-1

detail-2

detail-2-A

all foreign keys are cascading:

master -> detail1

master -> detail2

detail2- > detail-2-A

So when I delete a record from master, all the related details follow.
Deleting takes a very long time. E.g. one master can have 1.2 million records in detail2 and 60 million records in detail2A.

Would it a more efficient to create a stored procedure that deletes first the detail2A, then detail2 etc. Or is there a better approach.

DB is not partioned.

答:
We don't allow delete cascade on our systems because you have no control over locking table when a large delete is done. If you have large numbers of records to delete frequently, there are several choices. First, do you really need to delete or should you just make them as inactive?  This is probably the most efficient way to handle.

Or you can process in batches. Move all the id values you want to delte to a staging table and then delete them 1000 (or 20000 or 200 the actual number can only be determined by the system for performance reasons.) at a time and loop through until all the records are deleted. You still might want to experiement with deleting the records one table at a time, rather than deleting in a cascade.

Or you can mark the records for deletion and do the actual deletes overnight during the low usage periods of the database to avoid blocking other users.

One thing to consider with cascade delete is do you really want to delete the record if child records exist? Foreign keys exist, in part, to stop you from doing that and cascade delete overrides that behavior. So if your child records are something like orders, under no circumstances do you want to delete them automatically in a cascade delete or you will lose financial information you need even if the customer is no longer active.


问:
check port status on a server using q scripts
I have written a small script to check port status using q. It checks for the ports and runs an email if connection is refused, which works fine. Then I used an optional timeout for a port so it would not hang there waiting. Though it comes back with the comment "timeout" if a port is timed out, it also seems to kick me out of the function and does not get into sendemail[] part.

```<code>ProcessChecks:{[port]
            V:{@[value;("hopen (`::",(string x),";5000)");enlist]} [port];
            .keh.V:V;               :
            mail_body:(string V)," at .z.T time: ",(string .z.T);
            .keh.mail:mail_body;

  $[-6h=type V;"port accepted";SendEmail2[mail_body;"connection refused port: ",(string port)]];
</code>```

The name space .keh.mail does not change and SendEmail2[] does not get sent, which is just a unix mailx command.

I will get .keh.V = "timeout"

```<code>    .keh.mail = " at .z.T time whatever the time is"
</code>```

5000 is 5 second wait time and its introduction causes the problem.

答:
Your issue is being caused by a stray : in the third line of your script. This is causing your function to return early. Try the following:

```<code>ProcessChecks:{[port]
  V:{@[value;("hopen (`::",(string x),";5000)");enlist]} [port];
  .keh.V:V;
  mail_body:(string V)," at .z.T time: ",(string .z.T);
  .keh.mail:mail_body;
  $[-6h=type V;"port accepted";SendEmail2[mail_body;"connection refused port: ",(string port)]];
  }
</code>```

Body:
I have written a small script to check port status using q. It checks for the ports and runs an email if connection is refused, which works fine. Then I used an optional timeout for a port so it would not hang there waiting. Though it comes back with the comment "timeout" if a port is timed out, it also seems to kick me out of the function and does not get into sendemail[] part.

ProcessChecks:{[port]
            V:{@[value;("hopen (`::",(string x),";5000)");enlist]} [port];
            .keh.V:V;               :
            mail_body:(string V)," at .z.T time: ",(string .z.T);
            .keh.mail:mail_body;

  $[-6h=type V;"port accepted";SendEmail2[mail_body;"connection refused port: ",(string port)]];

The name space .keh.mail does not change and SendEmail2[] does not get sent, which is just a unix mailx command.

I will get .keh.V = "timeout"

    .keh.mail = " at .z.T time whatever the time is"

5000 is 5 second wait time and its introduction causes the problem.

Body:
Your issue is being caused by a stray : in the third line of your script. This is causing your function to return early. Try the following:

ProcessChecks:{[port]
  V:{@[value;("hopen (`::",(string x),";5000)");enlist]} [port];
  .keh.V:V;
  mail_body:(string V)," at .z.T time: ",(string .z.T);
  .keh.mail:mail_body;
  $[-6h=type V;"port accepted";SendEmail2[mail_body;"connection refused port: ",(string port)]];
  }


问:
Drag-And-Drop-Methods won't fire
I have a button and a stackpane. I now want to be able to drag that button onto that stackpane:

For testing purposes, I added all possible dragging events onto both components:

FXML:

```<code><AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.TestController">
   <children>
      <Button fx:id="source" layoutX="119.0" layoutY="172.0" mnemonicParsing="false" onDragDetected="#dragDetected" onDragDone="#dragDone" onDragDropped="#dragDropped" onDragEntered="#dragEntered" onDragExited="#dragExited" onDragOver="#dragOver" onMouseDragEntered="#mouseDragEntered" onMouseDragExited="#mouseDragExited" onMouseDragOver="#mouseDragOver" onMouseDragReleased="#mouseDragReleased" text="Drag Me!" />
      <StackPane fx:id="stackPane" layoutX="237.0" layoutY="110.0" onDragDetected="#dragDetected" onDragDone="#dragDone" onDragDropped="#dragDropped" onDragEntered="#dragEntered" onDragExited="#dragExited" onDragOver="#dragOver" onMouseDragEntered="#mouseDragEntered" onMouseDragExited="#mouseDragExited" onMouseDragOver="#mouseDragOver" onMouseDragReleased="#mouseDragReleased" prefHeight="150.0" prefWidth="200.0" style="-fx-border-color: black; -fx-background-color: lightgray;" />
   </children>
</AnchorPane>
</code>```

Controller:

```<code>package controller;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.input.DragEvent;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;

public class TestController implements Initializable {

    @FXML
    private Button source;
    @FXML
    private StackPane stackPane;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
    }

    @FXML
    private void mouseDragEntered(MouseDragEvent event) {
        System.out.println("mouseDragEntered");
    }

    @FXML
    private void mouseDragExited(MouseDragEvent event) {
        System.out.println("mouseDragExited");
    }

    @FXML
    private void mouseDragReleased(MouseDragEvent event) {
        System.out.println("mouseDragReleased");
    }

    @FXML
    private void mouseDragOver(MouseDragEvent event) {
        System.out.println("mouseDragOver");
    }

    @FXML
    private void dragDetected(MouseEvent event) {
        System.out.println("dragDetected");
    }

    @FXML
    private void dragEntered(DragEvent event) {
        System.out.println("dragEntered");
    }

    @FXML
    private void dragDone(DragEvent event) {
        System.out.println("dragDone");
    }

    @FXML
    private void dragExited(DragEvent event) {
        System.out.println("dragExited");
    }

    @FXML
    private void dragOver(DragEvent event) {
        System.out.println("dragOver");
    }

    @FXML
    private void dragDropped(DragEvent event) {
        System.out.println("dragDropped");
    }

}
</code>```

When I drag and drop the button, only the dragDetected-function is fired. All following steps (i.e. dragOver, dragDone etc.) won't be recognized.

答:
Add

```<code>Dragboard db = source.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putString(source.getText());
db.setContent(content);
event.consume();
</code>```

to dragDetected.

Title: Drag-And-Drop-Methods won't fire

Body:
I have a button and a stackpane. I now want to be able to drag that button onto that stackpane:

For testing purposes, I added all possible dragging events onto both components:

FXML:

<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.TestController">
   <children>
      <Button fx:id="source" layoutX="119.0" layoutY="172.0" mnemonicParsing="false" onDragDetected="#dragDetected" onDragDone="#dragDone" onDragDropped="#dragDropped" onDragEntered="#dragEntered" onDragExited="#dragExited" onDragOver="#dragOver" onMouseDragEntered="#mouseDragEntered" onMouseDragExited="#mouseDragExited" onMouseDragOver="#mouseDragOver" onMouseDragReleased="#mouseDragReleased" text="Drag Me!" />
      <StackPane fx:id="stackPane" layoutX="237.0" layoutY="110.0" onDragDetected="#dragDetected" onDragDone="#dragDone" onDragDropped="#dragDropped" onDragEntered="#dragEntered" onDragExited="#dragExited" onDragOver="#dragOver" onMouseDragEntered="#mouseDragEntered" onMouseDragExited="#mouseDragExited" onMouseDragOver="#mouseDragOver" onMouseDragReleased="#mouseDragReleased" prefHeight="150.0" prefWidth="200.0" style="-fx-border-color: black; -fx-background-color: lightgray;" />
   </children>
</AnchorPane>

Controller:

package controller;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.input.DragEvent;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;

public class TestController implements Initializable {

    @FXML
    private Button source;
    @FXML
    private StackPane stackPane;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
    }

    @FXML
    private void mouseDragEntered(MouseDragEvent event) {
        System.out.println("mouseDragEntered");
    }

    @FXML
    private void mouseDragExited(MouseDragEvent event) {
        System.out.println("mouseDragExited");
    }

    @FXML
    private void mouseDragReleased(MouseDragEvent event) {
        System.out.println("mouseDragReleased");
    }

    @FXML
    private void mouseDragOver(MouseDragEvent event) {
        System.out.println("mouseDragOver");
    }

    @FXML
    private void dragDetected(MouseEvent event) {
        System.out.println("dragDetected");
    }

    @FXML
    private void dragEntered(DragEvent event) {
        System.out.println("dragEntered");
    }

    @FXML
    private void dragDone(DragEvent event) {
        System.out.println("dragDone");
    }

    @FXML
    private void dragExited(DragEvent event) {
        System.out.println("dragExited");
    }

    @FXML
    private void dragOver(DragEvent event) {
        System.out.println("dragOver");
    }

    @FXML
    private void dragDropped(DragEvent event) {
        System.out.println("dragDropped");
    }

}

When I drag and drop the button, only the dragDetected-function is fired. All following steps (i.e. dragOver, dragDone etc.) won't be recognized.

Body:
Add

Dragboard db = source.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putString(source.getText());
db.setContent(content);
event.consume();

to dragDetected.


问:
Invalid non-ASCII or control character in header on redirect
I'm using asp.net core 2.1 and I have a problem on redirect.
My URL is like:

HTTP://localhost:60695/ShowProduct/2/شال-آبی

the last parameter is in Persian.
and it throws below error:

```<code>InvalidOperationException: Invalid non-ASCII or control character in header: 0x0634
</code>```

but when I change the last parameter in English like:

```<code>HTTP://localhost:60695/ShowProduct/2/scarf-blue
</code>```

it works and everything is OK.
I'm using below codes for redirecting:

```<code>[HttpPost]
[Route("Login")]
public IActionResult Login(LoginViewModel login, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View(login);
    }
    //SignIn Codes is hidden
    if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl))
    {
        return Redirect(returnUrl);
    }
    if (permissionService.CheckUserIsInRole(user.UserId, "Admin"))
    {
        return Redirect("/Admin/Dashboard");
    }
    ViewBag.IsSuccess = true;
    return View();
}
</code>```

how can I fix the problem?

答:
Another simpler option (works for me):</p>

```<code>    var uri = new Uri(urlStr);
    return Redirect(uri.AbsoluteUri);
</code>```

Body:
I'm using asp.net core 2.1 and I have a problem on redirect.
My URL is like:

HTTP://localhost:60695/ShowProduct/2/شال-آبی

the last parameter is in Persian.
and it throws below error:

InvalidOperationException: Invalid non-ASCII or control character in header: 0x0634

but when I change the last parameter in English like:

HTTP://localhost:60695/ShowProduct/2/scarf-blue

it works and everything is OK.
I'm using below codes for redirecting:

[HttpPost]
[Route("Login")]
public IActionResult Login(LoginViewModel login, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View(login);
    }
    //SignIn Codes is hidden
    if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl))
    {
        return Redirect(returnUrl);
    }
    if (permissionService.CheckUserIsInRole(user.UserId, "Admin"))
    {
        return Redirect("/Admin/Dashboard");
    }
    ViewBag.IsSuccess = true;
    return View();
}

how can I fix the problem?

Body:
Another simpler option (works for me):

    var uri = new Uri(urlStr);
    return Redirect(uri.AbsoluteUri);


问:
Incorrect syntax near 'PIVOT'
I'm running SQL Server 2008 R2.  I'm trying to build a table that takes data from a table structured like this:

```<code>company | ded_id | descr

10          1      MEDINS
10          2      LIFE
10          3      PENSN
...
10         50      DOMREL
</code>```

And I need to build a temp table it out to a format like this:

```<code>company | DESC1 | DESC2 | DESC3 ... | DESC50
10        MEDINS  LIFE    PENSN       DOMREL
</code>```

So I built the following query:

    SELECT *
    FROM (
    SELECT company,'DESC'+CAST(ded_id as VARCHAR(2)) AS DedID,descr
    FROM deduction
    ) deds
    PIVOT (MAX(descr)FOR DedID IN([DESC1],[DESC2],[DESC3])) descs
```

So running this gives the following error:

Msg 325, Level 15, State 1, Line 6
  Incorrect syntax near 'PIVOT'. You may need to set the compatibility level of the current database to a higher value to enable this feature. See help for the SET COMPATIBILITY_LEVEL option of ALTER DATABASE.

I double checked the compatibility level on the database and it is already set to 100 so that can't be the issue.  Can you think of any other setting that might be causing this behavior?

答:
i faced the same problem... while using "Pivot" and "Format" and "Convert" command inside sql query.

one thing that worked for me was
instead of importing sqlite
i imported pyodbc
so my code changed

from :
import sqlite3
conn = sqlite3.connect('/Users/****/Desktop/****.sqlite')

to:
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};''Server=@@@@;''Database=****;'      'Trusted_Connection=yes;')

Title: Incorrect syntax near 'PIVOT'

Body:
I'm running SQL Server 2008 R2.  I'm trying to build a table that takes data from a table structured like this:

company | ded_id | descr

10          1      MEDINS
10          2      LIFE
10          3      PENSN
...
10         50      DOMREL

And I need to build a temp table it out to a format like this:

company | DESC1 | DESC2 | DESC3 ... | DESC50
10        MEDINS  LIFE    PENSN       DOMREL

So I built the following query:

    SELECT *
    FROM (
    SELECT company,'DESC'+CAST(ded_id as VARCHAR(2)) AS DedID,descr
    FROM deduction
    ) deds
    PIVOT (MAX(descr)FOR DedID IN([DESC1],[DESC2],[DESC3])) descs

So running this gives the following error:

Msg 325, Level 15, State 1, Line 6
  Incorrect syntax near 'PIVOT'. You may need to set the compatibility level of the current database to a higher value to enable this feature. See help for the SET COMPATIBILITY_LEVEL option of ALTER DATABASE.

I double checked the compatibility level on the database and it is already set to 100 so that can't be the issue.  Can you think of any other setting that might be causing this behavior?


问:
How to fix "Undefined variable: img_name" error in laravel
i have a project on laravel 5.8; i have this error; please help me :
Undefined variable: img_name

this my html code :

```<code>    <div class="input-group control-group increment" >
      <input id="p_image" type="file" name="p_image" class="form-control">
      <div class="input-group-btn">
        <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
      </div>
    </div>
    <div class="clone hide">
      <div class="control-group input-group" style="margin-top:10px">
        <input id="p_image" type="file" name="p_image" class="form-control">
        <div class="input-group-btn">
          <button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
        </div>
      </div>
    </div>
</code>```

My Controller :

```<code>    public function store(Request $request)
    {
        $this->validate(request(), [

            'p_image' => 'image|mimes:jpg,jpeg,png|max:2048'

        ]);

        if($request->hasFile('p_image')){
            $img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
        }

         // awi sora s lfolder public/uploads
        if($request->hasFile('p_image')){
            $request->p_image->move(public_path('upload'), $img_name);
        }

        Image::create([
            'p_image' => $img_name,
            'post_id' => $post->id

        ]);

        return redirect('/posts');

    }
</code>```

I have this error, i dont understand, if you can explain me please; thank  you
Undefined variable: img_name

答:
If $request->hasFile('p_image') is false you don't define the $img_name variable.

But you always execute the code

```<code>Image::create([
    'p_image' => $img_name,
    'post_id' => $post->id
]);
</code>```

which is wrong. Change your code to

```<code>if($request->hasFile('p_image')){
    $img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
    $request->p_image->move(public_path('upload'), $img_name);
    Image::create([
        'p_image' => $img_name,
        'post_id' => $post->id
    ]);
}
</code>```

Body:
i have a project on laravel 5.8; i have this error; please help me :
Undefined variable: img_name

this my html code :

      <input id="p_image" type="file" name="p_image" class="form-control">

        <button class="btn btn-success" type="button">Add</button>

        <input id="p_image" type="file" name="p_image" class="form-control">

          <button class="btn btn-danger" type="button"> Remove</button>

My Controller :

    public function store(Request $request)
    {
        $this->validate(request(), [

            'p_image' => 'image|mimes:jpg,jpeg,png|max:2048'

        ]);

        if($request->hasFile('p_image')){
            $img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
        }

         // awi sora s lfolder public/uploads
        if($request->hasFile('p_image')){
            $request->p_image->move(public_path('upload'), $img_name);
        }

        Image::create([
            'p_image' => $img_name,
            'post_id' => $post->id

        ]);

        return redirect('/posts');

    }

I have this error, i dont understand, if you can explain me please; thank  you
Undefined variable: img_name

Body:
If $request->hasFile('p_image') is false you don't define the $img_name variable.

But you always execute the code

Image::create([
    'p_image' => $img_name,
    'post_id' => $post->id
]);

which is wrong. Change your code to

if($request->hasFile('p_image')){
    $img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
    $request->p_image->move(public_path('upload'), $img_name);
    Image::create([
        'p_image' => $img_name,
        'post_id' => $post->id
    ]);
}


答:
To locate the text Total and then extract the amount associated with $ you can use the following solution:

```<code>driver.FindElement(By.XPath("//table[@id='subtotals-marketplace-table']/tbody//td/span[contains(.,'Total:')]//following::td[1]")).GetAttribute("innerHTML");
</code>```

Update

As you are seeing the error as Unable to locate an element with the xpath expression, possibly you have to induce WebDriverWait for the element to be clickable and you can use the following solution:

```<code>new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.TextToBePresentInElementLocated(By.XPath("//table[@id='subtotals-marketplace-table']/tbody//td/span[contains(.,'Total:')]/following::td[1]"), "$")).GetAttribute("innerHTML");
</code>```

Body:
I am trying to grab data from a table that has two columns. The rows do not have a distinct identifier. But I can search the first column for specifics to find out if I should grab the second column's data.  There are multiple rows in the table although the example below I am just showing one row.

        Total:

    $12.80

I need to search for Total: and then grab the dollar amount in the next column.  I've tried multiple iterations of something along these lines but can't seem to find the correct syntax:

driver.FindElement(
                    By.XPath(
                        "//*[@id='subtotals-marketplace-table']//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

driver.FindElement(
                    By.XPath(
                        "//table[@id='subtotals-marketplace-table']//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

driver.FindElement(
                    By.XPath(
                        "//table[@id='subtotals-marketplace-table']/tbody//td[contains(text(),'Total:')]/following-sibling::td[1]"))
                    .Text;

Body:
To locate the text Total and then extract the amount associated with $ you can use the following solution:

driver.FindElement(By.XPath("//table[@id='subtotals-marketplace-table']/tbody//td/span[contains(.,'Total:')]//following::td[1]")).GetAttribute("innerHTML");

Update

As you are seeing the error as Unable to locate an element with the xpath expression, possibly you have to induce WebDriverWait for the element to be clickable and you can use the following solution:

new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.TextToBePresentInElementLocated(By.XPath("//table[@id='subtotals-marketplace-table']/tbody//td/span[contains(.,'Total:')]/following::td[1]"), "$")).GetAttribute("innerHTML");


问:
Requesting Cluster Computing framework for High Performance
I would like to build a cluster for getting high performance and to be used in a case of volunteer computing. I'm finding some volunteer computing platforms such as BOINC L, Beowulf cluster. I am a little bit familiar with Apache Hadoop, Spark cluster. Some of these cluster platforms would have to use MPI and other parallel processing libraries. However, I don't have any experiences with parallel prigramming. Moreover, I couldn't afford to write parallel programs for the cluster because I would like to make network simulations, image processing, programming testing etc. on my cluster.
Therefore, I am finding a cluster framework that can run any applications distributed among the nodes. I found that openMosix cluster framework will be suitable with my requirements but I found that it stopped its cluster development.
So, I would like to request respectfully some suggestions from the great seniors to direct me which kind of cluster framework is suitable to improve processing power in case of executing any applications.
Thank you so much.</p>

答:
(Disclosure: I am one of the BOINC developers, I also administer several BOINC projects)

As long as your applications are parallelizable (e.g. you can split the dataset or modify the application's command line parameters to split the search space), multiple simple options are available for you. If your nodes run Linux and you can SSH into them, simple tools like GNU Parallel might be suitable.

BOINC in general is tailored more to volunteer computing, aggregating heterogeneous resources. It has a bit of a learning curve, and focuses on security a lot (for example, all code running on the platform has to be signed, thus complicating deployment of "any" application). If you are looking at a real cluster-style use, where you will be running dozens of different apps, BOINC might not be for you (note that there exist ways to submit application binaries as part of work, but it is not trivial).

If you do decide to try BOINC, there is a somewhat old Virtual machine with BOINC server preinstalled, or just get a latest release of the code from Github.


问:
VB.NET 2005, Serial port, dispose problem, Windows CE
I write program for Windows CE that should work with Serial ports. I use object System.IO.Ports.SerialPort. Everything works well but when I close program and open it again, I receive error: Port is in use! At the end I write:

```<code>port.close()
port.dispose()
</code>```

And If I add this:

```<code>System.GC.collect()
</code>```

.. than everything begins to work

But problem is that computer gets stuck when garbage collector is called for each port. If I tried to use collector somewhere else, it doesnt "collect" ports and they look like used if program starts again.

Can someone help please?

答:
There are a few potential possibilities here.  First, just because you call Close, it doesn't mean the port is physically released - this is true even in C. It depends on the state of the UART and a whole lot on how the actual driver was written.  It may take time from the call to Close to the actual driver releasing the port.  This, I believe, is what you're actually seeing becasue you're actually manually calling close rather than waiting for the Finalizer to destroy your Port instance and implicitly close it - this would take even longer.

Of course this assumes that your Close call is actually being run.  If it's not, then you need to understand how object Finalization works in managed code.  This has nothing to do with OOP, it has to do with how memory is managed.  When an object does out of scope and has no more roots (references) it's available for collection, but that doesn't mean that it's immediately released.  In fact it can be quite some time before the finalizer runs, especially if the app continues to run.

Body:
I write program for Windows CE that should work with Serial ports. I use object System.IO.Ports.SerialPort. Everything works well but when I close program and open it again, I receive error: Port is in use! At the end I write:

port.close()
port.dispose()

And If I add this:

System.GC.collect()

.. than everything begins to work

But problem is that computer gets stuck when garbage collector is called for each port. If I tried to use collector somewhere else, it doesnt "collect" ports and they look like used if program starts again.

Can someone help please?


问:
How do you write a non-dymanic SQLQuery to only return records that fulfill multiple EXISTS clauses?
Here's the problem I'm running into. I have a query (that works) and what I want it to do is return only records where a user has records for each EXISTS clause. Like this:

```<code>select * from Users
WHERE EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 1)
        AND EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 2)
        AND EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 3)
</code>```

So in the case specifically, I only want users that have a session Id of 1 AND and session id of 2 AND and session id of 3. This query works but the session id's change and could be 1 or 20 different id's.

Right now I'm dynamically assembling the query as needed (in my server-side app) based on what session id's I need but I'm wondering if there's a way to write this query so I can just pass in the id's and not manually assemble it. Kinda like an IN clause but one that'll only return the records where a user appears in all numbers in the IN clause.

Every solution I run into seems to be a different version of this current query where I'm having to dynamically assemble the query depending on the session ids needed. Is there any way to make this not so dynamic?

答:
First, create a table type:

```<code>CREATE TYPE dbo.Ints AS TABLE(ID int PRIMARY KEY);
GO
</code>```

You can make that as an argument to your stored procedure (and adjust your server-side code to pass in a DataTable or List as a complex parameter, assuming C# or the like):

```<code>CREATE PROCEDURE dbo.GetSessionsThatMatchAllIDs
  @IDs dbo.Ints READONLY
AS
...
</code>```

But for now just for testing let's populate it manually:

```<code>DECLARE @IDs dbo.Ints;
INSERT @IDs VALUES(1),(2),(3); -- ...,(20)

DECLARE @min = COUNT(*) FROM @IDs;

SELECT Id, ...
  FROM dbo.Users AS u
  WHERE
  (
    SELECT COUNT(DISTINCT SessionID)
      FROM dbo.UserSessions
      WHERE UserID = u.ID
      AND SessionID IN (SELECT ID from @IDs)
  ) = @min;
</code>```

Body:
Here's the problem I'm running into. I have a query (that works) and what I want it to do is return only records where a user has records for each EXISTS clause. Like this:

select * from Users
WHERE EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 1)
        AND EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 2)
        AND EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 3)

So in the case specifically, I only want users that have a session Id of 1 AND and session id of 2 AND and session id of 3. This query works but the session id's change and could be 1 or 20 different id's.

Right now I'm dynamically assembling the query as needed (in my server-side app) based on what session id's I need but I'm wondering if there's a way to write this query so I can just pass in the id's and not manually assemble it. Kinda like an IN clause but one that'll only return the records where a user appears in all numbers in the IN clause.

Every solution I run into seems to be a different version of this current query where I'm having to dynamically assemble the query depending on the session ids needed. Is there any way to make this not so dynamic?

Body:
First, create a table type:

CREATE TYPE dbo.Ints AS TABLE(ID int PRIMARY KEY);
GO

You can make that as an argument to your stored procedure (and adjust your server-side code to pass in a DataTable or List as a complex parameter, assuming C# or the like):

CREATE PROCEDURE dbo.GetSessionsThatMatchAllIDs
  @IDs dbo.Ints READONLY
AS
...

But for now just for testing let's populate it manually:

DECLARE @IDs dbo.Ints;
INSERT @IDs VALUES(1),(2),(3); -- ...,(20)

DECLARE @min = COUNT(*) FROM @IDs;

SELECT Id, ...
  FROM dbo.Users AS u
  WHERE
  (
    SELECT COUNT(DISTINCT SessionID)
      FROM dbo.UserSessions
      WHERE UserID = u.ID
      AND SessionID IN (SELECT ID from @IDs)
  ) = @min;


问:
How to guarantee constrained values on a type in Coq?
If I have something like:

```<code>Record Version :=
  mkVersion { major:nat; minor:nat; branch:nat; hotfix:nat }.
</code>```

How could I add hard guarantees about values in this type, like:

```<code>hotfix v > 0 && hotfix v < 8
</code>```

And no one could create a Version with wrong values.

答:
You just have to add a field for the proof.  To tidy it up, you could wrap hotfix in its own type:

```<code>Record hotfix_t := Hotfix {
  hf_val : nat;
  hf_pf : hf_val > 0 /\ hf_val < 8
}.
Record Version := mkVersion {
  major : nat;
  minor : nat;
  branch : nat;
  hotfix : hotfix_t
}.
</code>```

Body:
If I have something like:

Record Version :=
  mkVersion { major:nat; minor:nat; branch:nat; hotfix:nat }.

How could I add hard guarantees about values in this type, like:

hotfix v > 0 && hotfix v < 8

And no one could create a Version with wrong values.

Body:
You just have to add a field for the proof.  To tidy it up, you could wrap hotfix in its own type:

Record hotfix_t := Hotfix {
  hf_val : nat;
  hf_pf : hf_val > 0 /\ hf_val < 8
}.
Record Version := mkVersion {
  major : nat;
  minor : nat;
  branch : nat;
  hotfix : hotfix_t
}.


问:
RENAME COLUMN IF EXISTS in H2
I have a H2 sql script file that is executed everytime the application is updated or when the database was not created previously.

So, everything inside the script file relies on "IF NOT EXISTS" or "IF EXISTS" verification check.

Because of that, I have problem creating SQL to rename columns and a cannot find a way to do this, because if the rename statement is executed more than once, I got an error about column inexistance.

I`ve tried the following:

ALTER TABLE X RENAME COLUMN IF NOT EXISTS Y TO Z;
```

答:
I`ve created one function to fill my needs, as follows. If you have a different approach, please let me know. tks!

DROP ALIAS IF EXISTS RENAME_COLUMN_IF_EXISTS;
CREATE ALIAS RENAME_COLUMN_IF_EXISTS AS  $$
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@CODE
void renameColumnIfExists(final Connection conn, final String tableName, final String cOld, final String cNew) throws SQLException {
    StringBuffer sql = new StringBuffer();
    sql.append("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = ?");

    PreparedStatement ps = conn.prepareStatement(sql.toString());

    try {
        ps.setString(1, tableName);
        ps.setString(2, cOld);

        ResultSet results = ps.executeQuery();

        if (results.next()) {
            if (results.getInt(1) > 0) {
                ps.close();

                sql = new StringBuffer()
                    .append("ALTER TABLE").append(" ")
                    .append(tableName).append(" ")
                    .append("RENAME COLUMN").append(" ")
                    .append(cOld).append(" ")
                    .append("TO").append(" ")
                    .append(cNew);
                ps = conn.prepareStatement(sql.toString());
                ps.executeUpdate();
            }
        }
    } finally {
        ps.close();
    }
}
$$;

CALL RENAME_COLUMN_IF_EXISTS ('X', 'Y', 'Z');
```

Title: RENAME COLUMN IF EXISTS in H2


问:
How can a lambda capture itself for an asynchronous call?
I have to make an asynchronous call inside a lambda, and once the asynchronous call is terminated I have to call the lambda itself.

I try to explain my problem with code:

typedef function<void(int id)> Callback;
```

<pre class="lang-cpp prettyprint-override"><code>AsyncWork1(Callback call, int id, string)
{
    //...
    call(id);
}

AsyncWork2(Callback call, int id, double, string)
{
    //...
    call(id);
}
</code>```

void AsyncWorks(Callback final_callback, int id)
{
    Callback lambda = [&lambda, final_callback, id](int next_work) -> void
        {
            if(next_work == 1)
            {
                //...
                AsyncWork1(lambda, 2, "bla bla");
            }
            else if(next_work == 2)
            {
                //...
                //the lambda variable no longer exists
                AsyncWork2(lambda, 3, 0.0, "bla bla");
            }
            else if(next_work == 3)
            {
                //...
                final_callback(id);
            }
        };

    lambda(1);
}
```

<pre class="lang-cpp prettyprint-override"><code>int main()
{
    AsyncWorks(...);

    AsyncWorks(...);

    AsyncWorks(...);

    AsyncWorks(...);

    return 0;
}
</code>```

The problem is that when the code exits from "AsyncWorks(...)" function, the local variable "lambda" no longer exists.

I've read several threads that talk about lambda recursive, but I haven't found any solution.

How can I solve this problem?

答:
The basic problem is that C++ doesn't expose the this pointer of a lambda to itself.

As it happens, there are many languages where during something's definition, you cannot refer to itself.  This is fixed in functional languages using a technique called the "Y Combinator".

A simple y combinator in C++ looks like:

```<code>template<class F>
struct y_combinator_t {
  F f;
  template<class...Args>
  auto operator()(Args&&...args)
  -> std::result_of_t< F&( y_combinator_t<F>&, Args&&... ) >
  {
    return f( *this, std::forward<Args>(args)... );
  }
};
template<class F>
y_combinator_t<std::decay_t<F>> y_combinate( F&& f ) {
  return {std::forward<F>(f)};
}
</code>```

I'm of two minds if we should f( *this or f( f, I sometimes do either.

Use:

```<code>void AsyncWorks(Callback final_callback, int id)
{
  Callback lambda = y_combinate(
    [final_callback, id]
    (auto& self, int next_work)
    -> void
    {
      if(next_work == 1) {
        //...
        AsyncWork1(self, 2, "bla bla");
      } else if(next_work == 2) {
        //...
        //the lambda variable no longer exists
        AsyncWork2(self, 3, 0.0, "bla bla");
      } else if(next_work == 3) {
        //...
        final_callback(id);
      }
    }
  );
  lambda(1);
}
</code>```

basically, I added an implicit self parameter to the lambda function body.  Caller of the operator() don't see this parameter.

Y combinator based off this post by myself with modifications.

Body:
I have to make an asynchronous call inside a lambda, and once the asynchronous call is terminated I have to call the lambda itself.

I try to explain my problem with code:

typedef function<void(int id)> Callback;

AsyncWork1(Callback call, int id, string)
{
    //...
    call(id);
}

AsyncWork2(Callback call, int id, double, string)
{
    //...
    call(id);
}

void AsyncWorks(Callback final_callback, int id)
{
    Callback lambda = [&lambda, final_callback, id](int next_work) -> void
        {
            if(next_work == 1)
            {
                //...
                AsyncWork1(lambda, 2, "bla bla");
            }
            else if(next_work == 2)
            {
                //...
                //the lambda variable no longer exists
                AsyncWork2(lambda, 3, 0.0, "bla bla");
            }
            else if(next_work == 3)
            {
                //...
                final_callback(id);
            }
        };

    lambda(1);
}

int main()
{
    AsyncWorks(...);

    AsyncWorks(...);

    AsyncWorks(...);

    AsyncWorks(...);

    return 0;
}

The problem is that when the code exits from "AsyncWorks(...)" function, the local variable "lambda" no longer exists.

I've read several threads that talk about lambda recursive, but I haven't found any solution.

How can I solve this problem?

Body:
The basic problem is that C++ doesn't expose the this pointer of a lambda to itself.

As it happens, there are many languages where during something's definition, you cannot refer to itself.  This is fixed in functional languages using a technique called the "Y Combinator".

A simple y combinator in C++ looks like:

template<class F>
struct y_combinator_t {
  F f;
  template<class...Args>
  auto operator()(Args&&...args)
  -> std::result_of_t< F&( y_combinator_t<F>&, Args&&... ) >
  {
    return f( *this, std::forward<Args>(args)... );
  }
};
template<class F>
y_combinator_t<std::decay_t<F>> y_combinate( F&& f ) {
  return {std::forward<F>(f)};
}

I'm of two minds if we should f( *this or f( f, I sometimes do either.

Use:

void AsyncWorks(Callback final_callback, int id)
{
  Callback lambda = y_combinate(
    [final_callback, id]
    (auto& self, int next_work)
    -> void
    {
      if(next_work == 1) {
        //...
        AsyncWork1(self, 2, "bla bla");
      } else if(next_work == 2) {
        //...
        //the lambda variable no longer exists
        AsyncWork2(self, 3, 0.0, "bla bla");
      } else if(next_work == 3) {
        //...
        final_callback(id);
      }
    }
  );
  lambda(1);
}

basically, I added an implicit self parameter to the lambda function body.  Caller of the operator() don't see this parameter.

Y combinator based off this post by myself with modifications.


问:
Error: Valid values for the strategy argument of `@scalarList` are: RELATION
Program pops up this -> (Valid values for the strategy argument of <code>@scalarList</code> are: RELATION.) after run prisma deploy. Any one knows why                                 ?                                             </p>

```<code>type User {
  id: ID! @id
  name: String!
  email: String! @unique
  password: String!
  age: Int
  img: String
  location: Location
  hostedEvents: [Event]! @relation(name: "HostedEvents", onDelete: CASCADE)
  joinedEvents: [Event]! @relation(name: "EventMembers", onDelete: CASCADE)
  pushNotificationTokens: [PushNotificationTokens]!
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
}
</code>```

```<code>type Event {
  id: ID! @id
  owner: User! @relation(name: "HostedEvents")
  name: String!
  imgs: [String]!
  description: String
  start: DateTime!
  end: DateTime!
  categories: [Category]!
  members: [User]! @relation(name: "EventMembers")
  chatRoom: GroupChatRoom!
  pendingRequests: [PendingRequest]!
  locations: [Location]!
  comments: [Comment]!
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
}
</code>```

答:
According with docs, when we need to create Fields as Array or List, the directive @scalarlist directive is required, in your case the correct model definition should be with the table/column imgs

```<code>type Event {
  id: ID! @id
  owner: User! @relation(name: "HostedEvents")
  name: String!
  imgs: [String!]! @scalarList(strategy: RELATION)
  description: String
  start: DateTime!
  end: DateTime!
  categories: [Category]!
  members: [User]! @relation(name: "EventMembers")
  chatRoom: GroupChatRoom!
  pendingRequests: [PendingRequest]!
  locations: [Location]!
  comments: [Comment]!
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
}
</code>```

Docs link -> https://www.prisma.io/docs/datamodel-and-migrations/datamodel-MYSQL-knul/#@scalarlist

Body:
Program pops up this -> (Valid values for the strategy argument of @scalarList are: RELATION.) after run prisma deploy. Any one knows why                                 ?

type User {
  id: ID! @id
  name: String!
  email: String! @unique
  password: String!
  age: Int
  img: String
  location: Location
  hostedEvents: [Event]! @relation(name: "HostedEvents", onDelete: CASCADE)
  joinedEvents: [Event]! @relation(name: "EventMembers", onDelete: CASCADE)
  pushNotificationTokens: [PushNotificationTokens]!
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
}

type Event {
  id: ID! @id
  owner: User! @relation(name: "HostedEvents")
  name: String!
  imgs: [String]!
  description: String
  start: DateTime!
  end: DateTime!
  categories: [Category]!
  members: [User]! @relation(name: "EventMembers")
  chatRoom: GroupChatRoom!
  pendingRequests: [PendingRequest]!
  locations: [Location]!
  comments: [Comment]!
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
}

Body:
According with docs, when we need to create Fields as Array or List, the directive @scalarlist directive is required, in your case the correct model definition should be with the table/column imgs

type Event {
  id: ID! @id
  owner: User! @relation(name: "HostedEvents")
  name: String!
  imgs: [String!]! @scalarList(strategy: RELATION)
  description: String
  start: DateTime!
  end: DateTime!
  categories: [Category]!
  members: [User]! @relation(name: "EventMembers")
  chatRoom: GroupChatRoom!
  pendingRequests: [PendingRequest]!
  locations: [Location]!
  comments: [Comment]!
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
}

Docs link -> https://www.prisma.io/docs/datamodel-and-migrations/datamodel-MYSQL-knul/#@scalarlist


问:
Android browser blocks a web site?
A user of my web site recently started getting this error -- "Data Connectivity Problem - The server failed to communicate. Try again later." -- when hitting my site from their Android phone.  The site works fine from my Android phone, and works fine from other devices.  The web logs show no evidence of his user ID hitting the site from an Android device, which suggests to me that his requests aren't even getting to my server.

I sent him a list of things to try and here was his response:

Did all the things you suggested except the wifi and problem still existed. When I get the error message, it comes almost immediately after initiating going to the site--it doesn't seem like a time out. On a lark, I tried using Firefox (had been using the internet app from Google that comes preinstalled on the phone) and your site loaded just like it should.

So I  went back to the internet app and cleared the cache, cookies, history--everything except form data and passwords--rebooted the phone, used the internet app to access your site and still got the error message. It's a mystery but at least it's operating correctly with Firefox. The problem must be with the internet app.

He's using an HTC Incredible on Verizon.  I was tempted to blame Verizon's network, but obviously that can't be the problem if it works for him with the Firefox browser.

Has anybody ever seen anything like this before?  What could be causing this?  Thanks.

答:
If you're using SSL, it may well be this bug. It looks like it is caused by using a proxy server for SSL pages. It looks like the 'fix' is to turn off proxy settings.

In this case, the good news is, it's not your bug, and the bad news, you can't fix it. You might be be able to go with a lightweight WebView app that disables the proxy, if you want to go down the custom app route.

Hope this helps,

Phil Lello

Title: Android browser blocks a web site?


问:
Create new lists inside of a list based on object names
I have a list of objects, similar pattern to the following list. The list only consists of the names of said objects, for simplicity.

```<code>List1
    A1_B1.C1
    A1_B2.C2
    A1_B3.C3
    A2_B1.C1
    A2_B2.C2
    A2_B3.C3
    A3_B1.C1
    A3_B2.C2
    A3_B3.C3
</code>```

I would like to concatenate all the similar B data into new lists.

```<code>List2
  B1
    A1_B1.C1
    A2_B1.C1
    A3_B1.C1
  B2
    A1_B2.C1
    A2_B2.C2
    A3_B2.C3
  B3
    A1_B3.C1
    A2_B3.C2
    A3_B3.C3
</code>```

I have played around with some regex codes to try and split the names of the objects by before and after the . but am not having much success.

Any help would be very appreciated.

答:
An option would be split using the extracted substring of 'B'

```<code>split(v1, gsub("A\\d+_|\\.C\\d+", "", v1))
#$B1
#[1] "A1_B1.C1" "A2_B1.C1" "A3_B1.C1"

#$B2
#[1] "A1_B2.C2" "A2_B2.C2" "A3_B2.C2"

#$B3
#[1] "A1_B3.C3" "A2_B3.C3" "A3_B3.C3"
</code>```

NOTE: It is not clear whether these are object identifiers or not

The OP uses a different string pattern

```<code>split(v2, gsub("^[^_]+\\_|\\..*$", "", v2))
</code>```

data

```<code>v1 <- c("A1_B1.C1", "A1_B2.C2", "A1_B3.C3", "A2_B1.C1", "A2_B2.C2",
 "A2_B3.C3", "A3_B1.C1", "A3_B2.C2", "A3_B3.C3")

v2 <- "GenetypeA_Drug1.ValueA"
</code>```

Body:
I have a list of objects, similar pattern to the following list. The list only consists of the names of said objects, for simplicity.

List1
    A1_B1.C1
    A1_B2.C2
    A1_B3.C3
    A2_B1.C1
    A2_B2.C2
    A2_B3.C3
    A3_B1.C1
    A3_B2.C2
    A3_B3.C3

I would like to concatenate all the similar B data into new lists.

List2
  B1
    A1_B1.C1
    A2_B1.C1
    A3_B1.C1
  B2
    A1_B2.C1
    A2_B2.C2
    A3_B2.C3
  B3
    A1_B3.C1
    A2_B3.C2
    A3_B3.C3

I have played around with some regex codes to try and split the names of the objects by before and after the . but am not having much success.

Any help would be very appreciated.

Body:
An option would be split using the extracted substring of 'B'

split(v1, gsub("A\\d+_|\\.C\\d+", "", v1))
#$B1
#[1] "A1_B1.C1" "A2_B1.C1" "A3_B1.C1"

#$B2
#[1] "A1_B2.C2" "A2_B2.C2" "A3_B2.C2"

#$B3
#[1] "A1_B3.C3" "A2_B3.C3" "A3_B3.C3"

NOTE: It is not clear whether these are object identifiers or not

The OP uses a different string pattern

split(v2, gsub("^[^_]+\\_|\\..*$", "", v2))

data

v1 <- c("A1_B1.C1", "A1_B2.C2", "A1_B3.C3", "A2_B1.C1", "A2_B2.C2",
 "A2_B3.C3", "A3_B1.C1", "A3_B2.C2", "A3_B3.C3")

v2 <- "GenetypeA_Drug1.ValueA"


问:
Jinja2 - Problem while looping a dictionary that uses hexadecimal numbers as key
I'm trying to loop over the following python dictionary using Jinja2 a 'for loop'

```<code>eg. {'0x1007c': '1'}.
</code>```

However Jinja complains about the hex value. Any ideas how can I fix it ?

I tried to escape the value but I'm not sure if this is the right way to fix the problem.

```<code>{% extends 'layout.html' %}

{% block body %}
    <h1>Devices</h1>
    <ul class="list.group">
        {% for device in devices %}
            <li class="list.group">{{ device.0x1007c }}</li>
        {% endfor %}
    </ul>
{% endblock %}
</code>```

The error message that I'm receiving is this:

jinja2.exceptions.TemplateSyntaxError: expected token 'end of print
  statement', got 'x1007c'

I was expecting retrieve the value 1.

答:
If devices is a list and its each element device is a dict, then it should be {{device['0x1007c']}}.

If devices is dict, then device is the key, so it should be {{devices[device]}}.

Body:
I'm trying to loop over the following python dictionary using Jinja2 a 'for loop'

eg. {'0x1007c': '1'}.

However Jinja complains about the hex value. Any ideas how can I fix it ?

I tried to escape the value but I'm not sure if this is the right way to fix the problem.

{% extends 'layout.html' %}

{% block body %}

Devices

        {% for device in devices %}

{{ device.0x1007c }}

        {% endfor %}

{% endblock %}

The error message that I'm receiving is this:

jinja2.exceptions.TemplateSyntaxError: expected token 'end of print
  statement', got 'x1007c'

I was expecting retrieve the value 1.


问:
Cleaning/Changing url
Exporting XML with hyperlinked fields from MsAccess leads to "url's" with a starting en ending "#" how do i remove them from the URL part and the text part with Xslt so how do i clean:

#https://web.site.nl/dataset#
```

So how to wipe the #

答:
If you know that the first and the last character are extraneous, just remove them:</p>

```<code><xsl:template match="a">
    <xsl:variable name="url" select="substring(@href, 2, string-length(@href) - 2)" />
    <a href="{$url}">
        <xsl:value-of select="$url"/>
    </a>
</xsl:template>
</code>```

Title: Cleaning/Changing url

Body:
Exporting XML with hyperlinked fields from MsAccess leads to "url's" with a starting en ending "#" how do i remove them from the URL part and the text part with Xslt so how do i clean:

#https://web.site.nl/dataset#

So how to wipe the #

Body:
If you know that the first and the last character are extraneous, just remove them:

<xsl:template match="a">
    <xsl:variable name="url" select="substring(@href, 2, string-length(@href) - 2)" />
    <a href="{$url}">
        <xsl:value-of select="$url"/>
    </a>
</xsl:template>


问:
Multiple PHP Version
I'm want to make a multiple php in my cpanel, i have a laravel apps and other sites (using wordpress).
My wordpress sites will not work if i'm using php version 7.3. The PHP version must 5.5 for my wordpress sites.

And then if the PHP version is 5.5 my app with laravel will not work and then showing 500 Error.

The suitable solution for my case is multiple PHP version with htaccess. Do you can give me a example code for multiple using htaccess? Because i'm using this code is not work for me

```<code> <IfModule mime_module>
 AddHandler application/x-httpd-alt-php72___lsphp .php .php5 .phtml
 AddHandler application/x-httpd-php72 .php
</IfModule>

<FilesMatch "\.(php4|php5|php7|php3|php2|php|phtml)$">

 SetHandler application/x-lsphp73

 </FilesMatch>
</code>```

答:
Add this lines to your htaccess for multi php.

To switch to PHP 4.4:
AddHandler application/x-httpd-php4 .php

To switch to PHP 5.0:
AddHandler application/x-httpd-php5 .php

To switch to PHP 5.1:
AddHandler application/x-httpd-php51 .php

To switch to PHP 5.2:
AddHandler application/x-httpd-php52 .php

To switch to PHP 5.3:
AddHandler application/x-httpd-php53 .php

To switch to PHP 5.4:
AddHandler application/x-httpd-php54 .php

To switch to PHP 5.5:
AddHandler application/x-httpd-php55 .php

To switch to PHP 5.6:
AddHandler application/x-httpd-php56 .php

To switch to PHP 7:
AddHandler application/x-httpd-php7 .php

To switch to PHP 7.1:
AddHandler application/x-httpd-php71 .php

duplicate question here

Title: Multiple PHP Version

Body:
I'm want to make a multiple php in my cpanel, i have a laravel apps and other sites (using wordpress).
My wordpress sites will not work if i'm using php version 7.3. The PHP version must 5.5 for my wordpress sites.

And then if the PHP version is 5.5 my app with laravel will not work and then showing 500 Error.

The suitable solution for my case is multiple PHP version with htaccess. Do you can give me a example code for multiple using htaccess? Because i'm using this code is not work for me

 <IfModule mime_module>
 AddHandler application/x-httpd-alt-php72___lsphp .php .php5 .phtml
 AddHandler application/x-httpd-php72 .php
</IfModule>

<FilesMatch "\.(php4|php5|php7|php3|php2|php|phtml)$">

 SetHandler application/x-lsphp73

 </FilesMatch>


问:
Break Promise in Vuex Action on API error
This is probably an issue of using the wrong pattern to accomplish what I'm needing, so either an answer of what pattern (and what that pattern is) I should be using or what would solve my current pattern would be greatly appreciated!

I have use case where I need to wait for 1 to many API calls to successfully complete before routing the user to a different page/view... Here's what I'm doing:

```<code>// Vuex action
[POST_NEW_INVOICE_UPDATE]: ({ commit }, update) => {
    return apiEndpoints
      .postNewInvoiceUpdate(update)
      .then(() => {
        app.$Progress.finish()
        app.$Toastr.success('Invoice flagged')
      })
      .catch((error) => {
        console.error(error)
        app.$Progress.fail()
        app.$Toastr.error('There was an issue submitting your request', 'Request error')
      })
},
</code>```

```<code>// In component
flag () {
    // ... simplifying for TLDR
    const promises = []
    flagSelections.forEach(selection => {
        // ... simplifying for TLDR
        promises.push(this.$store.dispatch('POST_NEW_INVOICE_UPDATE', parameters))
    })

    Promise.all(promises)
        .then(() => {
            // Route to next invoice in previous search, if search exists
            // ... simplifying for TLDR
        })
        .catch((error) => {
            console.error(error)
        })
},
</code>```

I'm creating an array of the action, POST_NEW_INVOICE_UPDATE, and calling Promise.all on that array. I want the .then chain to break when an error is caught by the .catch in the action, becuase I don't want to route my users until the APIs have been successful.

I believe I read in MDN that .then continues to chain even if an error is caught, but I obviously need something to prevent my user from being routed before the APIs are all successful.

I imagine I'm just using a dumb, self-created pattern and am not using Vuex actions correctly, so any help in the right direction would be appreciated!

EDIT: I forgot something important! If I take the code from the action and put it in promises.push instead of the dispatch, the code operates as needed, but I hate breaking the pattern of using Vuex for a single use-case.

答:
First off, I wouldn't use Vuex purely to make API calls. The purpose of Vuex is to manage a global state, and I can see here that you're not even using commit to mutate the state at all. You can abstract your API into your own objects or functions without needing Vuex. But it's possible you just trimmed the code down and you actually are calling commit, so I'll stick with that assumption.

Furthermore, it's anti-pattern for Vuex to be making calls like app.$Progress.fail(). Vuex should know nothing about your components or UI, its sole job is to manage global state.

Here's how I would structure it:

```<code>async flag() {
  const promises = [];

  flagSelections.forEach(selection => {
    promises.push(postNewInvoiceUpdate(parameters));
  });

  try {
    await Promise.all(promises);
    app.$Progress.finish();
    app.$Toastr.success('Invoice flagged');
  } catch (e) {
    console.error(error);
    app.$Progress.fail();
    app.$Toastr.error(
      'There was an issue submitting your request',
      'Request error'
    );
  }
},
</code>```

If any of the Promises fail, the code in the catch block will be executed. Promise.all means all Promises must resolve, not just some of them. And I would just import postNewInvoiceUpdate from a separate module. There's no need to use Vuex for this.

Body:
This is probably an issue of using the wrong pattern to accomplish what I'm needing, so either an answer of what pattern (and what that pattern is) I should be using or what would solve my current pattern would be greatly appreciated!

I have use case where I need to wait for 1 to many API calls to successfully complete before routing the user to a different page/view... Here's what I'm doing:

// Vuex action
[POST_NEW_INVOICE_UPDATE]: ({ commit }, update) => {
    return apiEndpoints
      .postNewInvoiceUpdate(update)
      .then(() => {
        app.$Progress.finish()
        app.$Toastr.success('Invoice flagged')
      })
      .catch((error) => {
        console.error(error)
        app.$Progress.fail()
        app.$Toastr.error('There was an issue submitting your request', 'Request error')
      })
},

// In component
flag () {
    // ... simplifying for TLDR
    const promises = []
    flagSelections.forEach(selection => {
        // ... simplifying for TLDR
        promises.push(this.$store.dispatch('POST_NEW_INVOICE_UPDATE', parameters))
    })

    Promise.all(promises)
        .then(() => {
            // Route to next invoice in previous search, if search exists
            // ... simplifying for TLDR
        })
        .catch((error) => {
            console.error(error)
        })
},

I'm creating an array of the action, POST_NEW_INVOICE_UPDATE, and calling Promise.all on that array. I want the .then chain to break when an error is caught by the .catch in the action, becuase I don't want to route my users until the APIs have been successful.

I believe I read in MDN that .then continues to chain even if an error is caught, but I obviously need something to prevent my user from being routed before the APIs are all successful.

I imagine I'm just using a dumb, self-created pattern and am not using Vuex actions correctly, so any help in the right direction would be appreciated!

EDIT: I forgot something important! If I take the code from the action and put it in promises.push instead of the dispatch, the code operates as needed, but I hate breaking the pattern of using Vuex for a single use-case.

Body:
First off, I wouldn't use Vuex purely to make API calls. The purpose of Vuex is to manage a global state, and I can see here that you're not even using commit to mutate the state at all. You can abstract your API into your own objects or functions without needing Vuex. But it's possible you just trimmed the code down and you actually are calling commit, so I'll stick with that assumption.

Furthermore, it's anti-pattern for Vuex to be making calls like app.$Progress.fail(). Vuex should know nothing about your components or UI, its sole job is to manage global state.

Here's how I would structure it:

async flag() {
  const promises = [];

  flagSelections.forEach(selection => {
    promises.push(postNewInvoiceUpdate(parameters));
  });

  try {
    await Promise.all(promises);
    app.$Progress.finish();
    app.$Toastr.success('Invoice flagged');
  } catch (e) {
    console.error(error);
    app.$Progress.fail();
    app.$Toastr.error(
      'There was an issue submitting your request',
      'Request error'
    );
  }
},

If any of the Promises fail, the code in the catch block will be executed. Promise.all means all Promises must resolve, not just some of them. And I would just import postNewInvoiceUpdate from a separate module. There's no need to use Vuex for this.


问:
Oracle SQL - Using CASE WHEN to select a proper date field
I have a complicated problem and I cannot for the life of me figure out the logic in my head.

I am trying to tackle the issue of building a query reporting the proper dates for a material event. Essentially, my company is trying to track inventory management by seeing when we buy (quantity+) a part, when we manufacture (quantity+) a part, when we sell (quantity-) a part, or when we use that part to build a higher assembly part (quantity-).

The table structures I am working with look like this:

Where there can be 4 types of events, each having their own unique identifier, and each having a date on which that event occurs.

I then have the "Happenings" table, which actually has the list of transactions, that looks like this:

(Note I have eliminated some irrelevant field names).

What I am trying to accomplish is using a CASE...WHEN statement to select the proper date based on if the current line's foreign key.

So something to the effect of:

```<code>CASE
    WHEN Type = "Purchase Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.PO_ID)
    WHEN TYPE = "Make Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.MO_ID)
    WHEN TYPE = "Sale" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.Sale_ID)
    WHEN TYPE = "Create Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.CO_ID)
    ELSE NULL AS Event_Date
</code>```

Unfortunately, I cannot post too much data as it is company proprietary, but that is the gist of what I am trying to accomplish; using CASE...WHEN to properly select a value from another table when my current row contains the unique identifier.

答:
Try a case on the join condition</p>

```<code>select e1.date
from events e1
inner join happenings h2
on e1.Number = case when e1.type = 'Purchase' then h2.PO_ID
                    when e1.type = 'Make' then h2.MO_ID
                    ...
               end
</code>```

Body:
I have a complicated problem and I cannot for the life of me figure out the logic in my head.

I am trying to tackle the issue of building a query reporting the proper dates for a material event. Essentially, my company is trying to track inventory management by seeing when we buy (quantity+) a part, when we manufacture (quantity+) a part, when we sell (quantity-) a part, or when we use that part to build a higher assembly part (quantity-).

The table structures I am working with look like this:

Where there can be 4 types of events, each having their own unique identifier, and each having a date on which that event occurs.

I then have the "Happenings" table, which actually has the list of transactions, that looks like this:

(Note I have eliminated some irrelevant field names).

What I am trying to accomplish is using a CASE...WHEN statement to select the proper date based on if the current line's foreign key.

So something to the effect of:

CASE
    WHEN Type = "Purchase Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.PO_ID)
    WHEN TYPE = "Make Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.MO_ID)
    WHEN TYPE = "Sale" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.Sale_ID)
    WHEN TYPE = "Create Order" THEN (SELECT Date FROM Events WHERE Events.Number = Happenings.CO_ID)
    ELSE NULL AS Event_Date

Unfortunately, I cannot post too much data as it is company proprietary, but that is the gist of what I am trying to accomplish; using CASE...WHEN to properly select a value from another table when my current row contains the unique identifier.

Body:
Try a case on the join condition

select e1.date
from events e1
inner join happenings h2
on e1.Number = case when e1.type = 'Purchase' then h2.PO_ID
                    when e1.type = 'Make' then h2.MO_ID
                    ...
               end


问:
Singleton initialization
I implemented the Singleton design pattern in my code.

Suppose it is:

```<code>class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};
</code>```

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

```<code>SingletonPointer* SingletonClass::s (0);
</code>```

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir

答: In the initialization code, you're not accessing Singleton::s, you're defining it.

Title: Singleton initialization

Body:
I implemented the Singleton design pattern in my code.

Suppose it is:

class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

SingletonPointer* SingletonClass::s (0);

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir


问:
regex to match white space and one
I am a beginner when it comes to writing a regular expression, I want o write regex which can match the following lines

```<code> 0 x0_0                            1                 -228900  Result - true
 0 x2_0                            0                 -228900  Result - false
 0 x3_0                            0                 -128900  Result - false
</code>```

Actually I want regex to return true if it has

```<code>x<AnyDigit>_<AnyDigit> <WhiteSpace>  1
</code>```

I have written below expression

```<code>x(\d+)_(\d+)[\s1]
</code>```

but it is returning true in below case as well

```<code>0 x3_0                           0                 -128900
</code>```

答:
[\s1] is a character class that matches a single character that is either whitespace or the digit 1.

In the line

```<code>0 x3_0                           0                 -128900
</code>```

we have x(\d+)_(\d+)[\s1] (at the end of the regex) matching x3_0:

x matches itself.

the first \d+ group matches 3

_ matches itself

the second \d+ group matches 0

[\s1] matches the space after 0

A literal regex translation of your requirements would be

```<code>x\d_\d\s+1
</code>```

which matches x, followed by a digit, followed by _, followed by a digit, followed by one or more whitespace characters, followed by 1.

Title: regex to match white space and one

Body:
I am a beginner when it comes to writing a regular expression, I want o write regex which can match the following lines

 0 x0_0                            1                 -228900  Result - true
 0 x2_0                            0                 -228900  Result - false
 0 x3_0                            0                 -128900  Result - false

Actually I want regex to return true if it has

x<AnyDigit>_<AnyDigit> <WhiteSpace>  1

I have written below expression

x(\d+)_(\d+)[\s1]

but it is returning true in below case as well

0 x3_0                           0                 -128900

Body:
[\s1] is a character class that matches a single character that is either whitespace or the digit 1.

In the line

0 x3_0                           0                 -128900

we have x(\d+)_(\d+)[\s1] (at the end of the regex) matching x3_0:

x matches itself.

the first \d+ group matches 3

_ matches itself

the second \d+ group matches 0

[\s1] matches the space after 0

A literal regex translation of your requirements would be

x\d_\d\s+1

which matches x, followed by a digit, followed by _, followed by a digit, followed by one or more whitespace characters, followed by 1.


问:
"Getting SSLError while trying to 'get' content using 'requests' from a 'HTTPS' url"
I am trying to call a HTTPS url using requests.get(). But getting SSLError.

It is on my local machine.

Python version is 3.7. I am using VS Code.

If I try to pass verify=False to request.get() call succeeds with a warning.

Here is the line of code:

resp = requests.get('https://statesymbolsusa.org/sites/statesymbolsusa.org/files/primary-images/irisflowersclassicpurple.jpg')
```

Why am I getting SSL error? How to fix it?

Please someone explain this behavior.

答:
It's seems like an untrusted SSL certificate

Have you tried setting verify=True ?

That will force the certificate to be validated against the library's own trusted certificate authorities (CA)

Body:
I am trying to call a HTTPS url using requests.get(). But getting SSLError.

It is on my local machine.

Python version is 3.7. I am using VS Code.

If I try to pass verify=False to request.get() call succeeds with a warning.

Here is the line of code:

resp = requests.get('https://statesymbolsusa.org/sites/statesymbolsusa.org/files/primary-images/irisflowersclassicpurple.jpg')

Why am I getting SSL error? How to fix it?

Please someone explain this behavior.