问:
Basics of PyQt5 and PyOpenGL
I'm trying to learn how to use PyQt5 and PyOpenGL to do a simple gui for display some shapes. I searched a lot but i didnt find any example/tutorial that show me the basics. I just want to draw simple shapes in the widget of this mainwindow. Here is the code from the ui.py</p>

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.openGLWidget = QtWidgets.QOpenGLWidget(self.centralwidget)
        self.openGLWidget.setGeometry(QtCore.QRect(110, 50, 591, 451))
        self.openGLWidget.setObjectName("openGLWidget")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

答:
Based on code from Trying to get PyQt5 and OpenGL working. I found it using Google.

You assign own method to self.openGLWidget.paintGL and draw OpenGL inside this method.

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.uic import *

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.openGLWidget = QtWidgets.QOpenGLWidget(self.centralwidget)
        self.openGLWidget.setGeometry(QtCore.QRect(110, 50, 591, 451))
        self.openGLWidget.setObjectName("openGLWidget")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

        self.openGLWidget.initializeGL()
        self.openGLWidget.resizeGL(651,551)
        self.openGLWidget.paintGL = self.paintGL

        timer = QTimer(self.centralwidget)
        timer.timeout.connect(self.openGLWidget.update)
        timer.start(1000)

    def paintGL(self):
        glClear(GL_COLOR_BUFFER_BIT)
        glColor3f(1,0,0);
        glBegin(GL_TRIANGLES);
        glVertex3f(-0.5,-0.5,0);
        glVertex3f(0.5,-0.5,0);
        glVertex3f(0.0,0.5,0);
        glEnd()

        gluPerspective(45, 651/551, 0.1, 50.0)
        glTranslatef(0.0,0.0, -5)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

Title: Basics of PyQt5 and PyOpenGL

Body:
I'm trying to learn how to use PyQt5 and PyOpenGL to do a simple gui for display some shapes. I searched a lot but i didnt find any example/tutorial that show me the basics. I just want to draw simple shapes in the widget of this mainwindow. Here is the code from the ui.py

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.openGLWidget = QtWidgets.QOpenGLWidget(self.centralwidget)
        self.openGLWidget.setGeometry(QtCore.QRect(110, 50, 591, 451))
        self.openGLWidget.setObjectName("openGLWidget")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Body:
Based on code from Trying to get PyQt5 and OpenGL working. I found it using Google.

You assign own method to self.openGLWidget.paintGL and draw OpenGL inside this method.

from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.uic import *

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.openGLWidget = QtWidgets.QOpenGLWidget(self.centralwidget)
        self.openGLWidget.setGeometry(QtCore.QRect(110, 50, 591, 451))
        self.openGLWidget.setObjectName("openGLWidget")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

        self.openGLWidget.initializeGL()
        self.openGLWidget.resizeGL(651,551)
        self.openGLWidget.paintGL = self.paintGL

        timer = QTimer(self.centralwidget)
        timer.timeout.connect(self.openGLWidget.update)
        timer.start(1000)

    def paintGL(self):
        glClear(GL_COLOR_BUFFER_BIT)
        glColor3f(1,0,0);
        glBegin(GL_TRIANGLES);
        glVertex3f(-0.5,-0.5,0);
        glVertex3f(0.5,-0.5,0);
        glVertex3f(0.0,0.5,0);
        glEnd()

        gluPerspective(45, 651/551, 0.1, 50.0)
        glTranslatef(0.0,0.0, -5)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


来源: stackexchange

问:
How to use Lodash debounce in VueJs watch with Typescript
In VueJS (Javascript) I can do this:

```<code>import debounce from "lodash/debounce";

...

watch: {
  variable: debounce(function() {
    console.log('wow');
  }, 500)
}
</code>```

In VueJS (Typescript) I try:

```<code>npm i lodash-es
npm i @types/lodash-es -D
</code>```

In component:

```<code>import { Component, Vue, Watch } from "vue-property-decorator";
import debounce from "lodash-es/debounce";

...

@Watch("variable")
debounce(function() {
  console.log('wow');
}, 500)
</code>```

But I get errors:

'debounce', which lacks return-type annotation, implicitly has an 'any' return type.

Member '500' implicitly has an 'any' type.

P.S. This works fine:

```<code>func = debounce(() => {
    console.log('wow');
}, 500)
</code>```

答:
You can use this: https://www.npmjs.com/package/vue-debounce-decorator

And then do this:

```<code>  @Watch('value')
  @Debounce(300)
  private onValueChanged (val: string): void {
    // do your thing here
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In VueJS (Javascript) I can do this:

import debounce from "lodash/debounce";

...

watch: {
  variable: debounce(function() {
    console.log('wow');
  }, 500)
}

In VueJS (Typescript) I try:

npm i lodash-es
npm i @types/lodash-es -D

In component:

import { Component, Vue, Watch } from "vue-property-decorator";
import debounce from "lodash-es/debounce";

...

@Watch("variable")
debounce(function() {
  console.log('wow');
}, 500)

But I get errors:

'debounce', which lacks return-type annotation, implicitly has an 'any' return type.

Member '500' implicitly has an 'any' type.

P.S. This works fine:

func = debounce(() => {
    console.log('wow');
}, 500)

Body:
You can use this: https://www.npmjs.com/package/vue-debounce-decorator

And then do this:

  @Watch('value')
  @Debounce(300)
  private onValueChanged (val: string): void {
    // do your thing here
  }


问:
How to change values in a div created dinamically in React
I have some data that is being store in an array called cards in my component state props.
When I get data from the API I put the results in this array and for each element of the array I render a  with the data of the respective element. One of the properties of this data is called quantity that always starts at 1.

The problem is, at that div, I want to increment or decrement this value of each individual  element, but I don't know how. The only way I know is to change the value in the state property using this.setValue(), but this is in the Component properties, not the individual element of the array.

So how can I update the value of a dinamically generated div without using setState()?

This is my div. When I click in the buttons nothing happens. Nothing is shown on the console either.

Here is my array definition:

```<code>constructor(props) {
    super(props);
    this.state = {
        value: '',
        list: [],
        cards: [],//this will store the data from the API
    };
    this.handleChange = this.handleChange.bind(this);
}
</code>```

This is the function that insert the result of the GET request into my cards array:

```<code>searchCard = () => {
    const response = axios.get("https://api.scryfall.com/cards/search?q=".concat(this.state.value)).then(result => {
        let cardsArray = [];
        result.data.data.map((element) => {
            element.quantity = 1;
            cardsArray.push(element)
        });
        this.setState({ cards: cardsArray });
        console.log(this.state.cards);
    }).catch(error => console.log(error));
}
</code>```

And this is my automatically generated divs:

```<code>addCardToPool = (element) => {
    if (element.quantity <= 3) {
        element.quantity += 1;
    }

}
removeCardFromPool=(element) => {
    if (element.quantity >= 1) {
        element.quantity -= 1;
    }
}
<div className="card-thumbnail-container">
                {this.state.cards.length > 0 ? //if the cards array is not empty
                    this.state.cards.map((element, key) =>
                        <div className="card-thumbnail" key={key}>
                            <div className="card-image"><img src={element.image_uris.normal} /></div>
                            <div className="quantity buttons">
                                <button className="button is-small is-danger" onClick={this.addCardToPool(element)}>Rem.</button>
                                <div><button className="button is-success is-info">Add: {element.quantity}</button></div>
                                <button className="button is-small is-info" onClick={this.removeCardFromPool(element)}>Add.</button>
                            </div>
                        </div>
                    )
           :<div></div>}
    </div>
</code>```

答:
One feature of React that's often over-looked is that you build components from other components, this concept is known as composition.

So in your example, rather than trying to do everything in one component, split it into 2.  Maybe called Cards & Card.

This has the advantage that Card will have it's own state, so becomes trivial to maintain updates.

Below is an example, it uses Hooks, but the same concept would apply if you use the component method instead,. I've also included a pretend remote database get, that then will show a please wait message.

const {useState, useEffect} = React;

//pretend async get cards
function getCards() {
  return new Promise((r, x) => {
    setTimeout(() => {
      const cards = [
        {name:'one', qty: 1},
        {name:'two', qty: 1},
        {name:'three', qty: 1}
      ]
      r(cards);
    }, 500);
  });
}

function Card(props) {
  const [card, setCard] = useState(props.card);
  function btAdd(value) {
    return () => {
      const newQty = card.qty + value;
      if (newQty < 1 || newQty > 4) return;
      setCard({...card, qty: newQty});
    }
  }
  return

    <button onClick={btAdd(-1)}>-</button>

      {card.name} = {card.qty}

    <button onClick={btAdd(+1)}>+</button>

;
}

function Cards() {
  const [cards, setCards] = useState([]);
  useEffect(() => {
    getCards().then(c => setCards(c));
  }, []);
  return cards.length
    ? cards.map((card, ix) =>
      <Card key={ix} card={card}/>)
    :
Loading please wait..
;
}

ReactDOM.render(<Cards/>, document.querySelector('#mount'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="mount"></div></code>```

Body:
I have some data that is being store in an array called cards in my component state props.
When I get data from the API I put the results in this array and for each element of the array I render a  with the data of the respective element. One of the properties of this data is called quantity that always starts at 1.

The problem is, at that div, I want to increment or decrement this value of each individual  element, but I don't know how. The only way I know is to change the value in the state property using this.setValue(), but this is in the Component properties, not the individual element of the array.

So how can I update the value of a dinamically generated div without using setState()?

This is my div. When I click in the buttons nothing happens. Nothing is shown on the console either.

Here is my array definition:

constructor(props) {
    super(props);
    this.state = {
        value: '',
        list: [],
        cards: [],//this will store the data from the API
    };
    this.handleChange = this.handleChange.bind(this);
}

This is the function that insert the result of the GET request into my cards array:

searchCard = () => {
    const response = axios.get("https://api.scryfall.com/cards/search?q=".concat(this.state.value)).then(result => {
        let cardsArray = [];
        result.data.data.map((element) => {
            element.quantity = 1;
            cardsArray.push(element)
        });
        this.setState({ cards: cardsArray });
        console.log(this.state.cards);
    }).catch(error => console.log(error));
}

And this is my automatically generated divs:

addCardToPool = (element) => {
    if (element.quantity <= 3) {
        element.quantity += 1;
    }

}
removeCardFromPool=(element) => {
    if (element.quantity >= 1) {
        element.quantity -= 1;
    }
}

                {this.state.cards.length > 0 ? //if the cards array is not empty
                    this.state.cards.map((element, key) =>

                                <button className="button is-small is-danger" onClick={this.addCardToPool(element)}>Rem.</button>

<button className="button is-success is-info">Add: {element.quantity}</button>

                                <button className="button is-small is-info" onClick={this.removeCardFromPool(element)}>Add.</button>

                    )
           :

}

Body:
One feature of React that's often over-looked is that you build components from other components, this concept is known as composition.

So in your example, rather than trying to do everything in one component, split it into 2.  Maybe called Cards & Card.

This has the advantage that Card will have it's own state, so becomes trivial to maintain updates.

Below is an example, it uses Hooks, but the same concept would apply if you use the component method instead,. I've also included a pretend remote database get, that then will show a please wait message.

const {useState, useEffect} = React;

//pretend async get cards
function getCards() {
  return new Promise((r, x) => {
    setTimeout(() => {
      const cards = [
        {name:'one', qty: 1},
        {name:'two', qty: 1},
        {name:'three', qty: 1}
      ]
      r(cards);
    }, 500);
  });
}

function Card(props) {
  const [card, setCard] = useState(props.card);
  function btAdd(value) {
    return () => {
      const newQty = card.qty + value;
      if (newQty < 1 || newQty > 4) return;
      setCard({...card, qty: newQty});
    }
  }
  return <div>
    <button onClick={btAdd(-1)}>-</button>
    <div style={{margin: "0 10px", width: "70px", display: "inline-block"}}>
      {card.name} = {card.qty}</div>
    <button onClick={btAdd(+1)}>+</button>
  </div>;
}

function Cards() {
  const [cards, setCards] = useState([]);
  useEffect(() => {
    getCards().then(c => setCards(c));
  }, []);
  return cards.length
    ? cards.map((card, ix) =>
      <Card key={ix} card={card}/>)
    : <div>Loading please wait..</div>;
}

ReactDOM.render(<Cards/>, document.querySelector('#mount'));

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="mount"></div>


问:
Using Sled, how do I serialize and deserialize?
I'm playing around with the crate sled and attempting a simple serialization and deserialization exercise using bincode just to get a handle on usage.

While I can get insertion to work, attempting to get a range of results seems more difficult. Here I attempt to put in two records: a key of 42 with the value of "Alice" and a key of 69 with a value of "Bob and then retrieve and print them. I'm having a hard time reconciling deserialization of the vectors that come out:

use crate::db::Database;
use sled::Db;
use bincode;

pub struct SledDatabase {
    db: Db,
}

impl Database for SledDatabase {
    fn create(&self) {
        // Not handling errors; just an example.
        let key: i64 = 42;
        println!("ser {:?}", bincode::serialize(&key).unwrap());
        self.db.insert(bincode::serialize(&key).unwrap(), bincode::serialize("Alice").unwrap());
        let key2: i64 = 69;
        self.db.insert(bincode::serialize(&key2).unwrap(), bincode::serialize("Bob").unwrap());
    }

    fn query(&self, value : i64) {
        let range = value.to_ne_bytes();
        let mut iter = self.db.range(range..);
        while let Some(item) = iter.next() {
            let (k, v) = item.unwrap();
            println!("res {:?}", k);
            let key: i64 = bincode::deserialize(&k).unwrap();
            let value: String = bincode::deserialize(&v).unwrap();
            println!("age = {}", key);
            println!("name = {}", value);
        }
    }
}

impl SledDatabase {
    pub fn connect() -> SledDatabase {
        // use sled::{ConfigBuilder, Error};
        // let config = ConfigBuilder::new().temporary(true).build();
        SledDatabase { db: Db::open("sled.db").unwrap() }
    }
}
```

<p>Attempting to interact with this using a console entry listener I've pieced together, I get the following output:</p>

```ser [42, 0, 0, 0, 0, 0, 0, 0]
>> 1
res [42]
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Io(Custom { kind: UnexpectedEof, error: "failed to fill whole buffer" })', src/libcore/result.rs:1084:5
```

This occurs on either attempt to deserialize (either the String or the i64 value. Interestingly, the output seems to indicate that either sled or bincode are truncating the key value.

The examples of sled usage don't seem to address retrieving values, but looking through some documentation and parts of the source, I get the sense that serde serialization is a valid way of getting things in and out of sled.

答:
I cannot reproduce this issue with the code given above, I'm unsure if the sled implementation has perhaps changed a size of something related to the range function, and now match the expectations of the code, or if this was just a bug.

None the less, I ran into this error message due to some carelessness on my part.

```<code>fn main() -> Result<(), Error> {
    let db = sled::open("foo.sled_db").unwrap();
    let codec = bincode::config();

    db.insert("uhoh", codec.serialize(&0)?)?;
    let ser = &db.get("uhoh")?.unwrap();
    let de1: i32 = codec.deserialize(ser)?;
    println!("ok... {}", de1);
    let de2: usize = codec.deserialize(ser)?;
    println!("not ok {}", de2);
}
</code>```

I've omitted implementations of From<sled::Error> and From<bincode::Error> for Error, to simplify things.

ok... 0

Error: Bincode(Io(Custom { kind: UnexpectedEof, error: "failed to fill whole  buffer" })

The thing to note here is that (as you say) value which was serialized is smaller,
than the type we attempt to deserialize into.

```<code>println!(
       "{} {}",
       core::mem::size_of::<usize>(),
       core::mem::size_of_val(&0)
);

println!(
        "{} {}",
        core::mem::size_of::<usize>(),
        core::mem::size_of::<i32>()
);
</code>```

8 4

8 4

To fix this I serialized this with the value &0usize instead of &0.
Using serde serialization for sled keys and values indeed does seem fine, but you do need to be careful about the inferred size of values.

Body:
I'm playing around with the crate sled and attempting a simple serialization and deserialization exercise using bincode just to get a handle on usage.

While I can get insertion to work, attempting to get a range of results seems more difficult. Here I attempt to put in two records: a key of 42 with the value of "Alice" and a key of 69 with a value of "Bob and then retrieve and print them. I'm having a hard time reconciling deserialization of the vectors that come out:

use crate::db::Database;
use sled::Db;
use bincode;

pub struct SledDatabase {
    db: Db,
}

impl Database for SledDatabase {
    fn create(&self) {
        // Not handling errors; just an example.
        let key: i64 = 42;
        println!("ser {:?}", bincode::serialize(&key).unwrap());
        self.db.insert(bincode::serialize(&key).unwrap(), bincode::serialize("Alice").unwrap());
        let key2: i64 = 69;
        self.db.insert(bincode::serialize(&key2).unwrap(), bincode::serialize("Bob").unwrap());
    }

    fn query(&self, value : i64) {
        let range = value.to_ne_bytes();
        let mut iter = self.db.range(range..);
        while let Some(item) = iter.next() {
            let (k, v) = item.unwrap();
            println!("res {:?}", k);
            let key: i64 = bincode::deserialize(&k).unwrap();
            let value: String = bincode::deserialize(&v).unwrap();
            println!("age = {}", key);
            println!("name = {}", value);
        }
    }
}

impl SledDatabase {
    pub fn connect() -> SledDatabase {
        // use sled::{ConfigBuilder, Error};
        // let config = ConfigBuilder::new().temporary(true).build();
        SledDatabase { db: Db::open("sled.db").unwrap() }
    }
}

Attempting to interact with this using a console entry listener I've pieced together, I get the following output:

ser [42, 0, 0, 0, 0, 0, 0, 0]
>> 1
res [42]
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Io(Custom { kind: UnexpectedEof, error: "failed to fill whole buffer" })', src/libcore/result.rs:1084:5

This occurs on either attempt to deserialize (either the String or the i64 value. Interestingly, the output seems to indicate that either sled or bincode are truncating the key value.

The examples of sled usage don't seem to address retrieving values, but looking through some documentation and parts of the source, I get the sense that serde serialization is a valid way of getting things in and out of sled.

Body:
I cannot reproduce this issue with the code given above, I'm unsure if the sled implementation has perhaps changed a size of something related to the range function, and now match the expectations of the code, or if this was just a bug.

None the less, I ran into this error message due to some carelessness on my part.

fn main() -> Result<(), Error> {
    let db = sled::open("foo.sled_db").unwrap();
    let codec = bincode::config();

    db.insert("uhoh", codec.serialize(&0)?)?;
    let ser = &db.get("uhoh")?.unwrap();
    let de1: i32 = codec.deserialize(ser)?;
    println!("ok... {}", de1);
    let de2: usize = codec.deserialize(ser)?;
    println!("not ok {}", de2);
}

I've omitted implementations of From<sled::Error> and From<bincode::Error> for Error, to simplify things.

ok... 0

Error: Bincode(Io(Custom { kind: UnexpectedEof, error: "failed to fill whole  buffer" })

The thing to note here is that (as you say) value which was serialized is smaller,
than the type we attempt to deserialize into.

println!(
       "{} {}",
       core::mem::size_of::<usize>(),
       core::mem::size_of_val(&0)
);

println!(
        "{} {}",
        core::mem::size_of::<usize>(),
        core::mem::size_of::<i32>()
);

8 4

8 4

To fix this I serialized this with the value &0usize instead of &0.
Using serde serialization for sled keys and values indeed does seem fine, but you do need to be careful about the inferred size of values.


问:
Combining Multiple Dataframes with Unique Name
I have for example 2 data frames with user and their rating for each place such as:

Dataframe 1:

```<code>Name    Golden Gate
Adam    1
Susan   4
Mike    5
John    4
</code>```

Dataframe 2:

```<code>Name    Botanical Garden
Jenny   1
Susan   4
Leslie  5
John    3
</code>```

I want to combine them into a single data frame with the result:

Combined Dataframe:

```<code>Name    Golden Gate   Botanical Garden
Adam    1             NA
Susan   4             4
Mike    5             NA
John    4             3
Jenny   NA            1
Leslie  NA            5
</code>```

How to do that?

Thank you.

答:
You need to perform an outer join or a concatenation along an axis:

```<code>final_df = df1.merge(df2,how='outer',on='Name')
</code>```

Output:

```<code>     Name  Golden Gate  Botanical Garden
0    Adam          1.0               NaN
1   Susan          4.0               4.0
2    Mike          5.0               NaN
3    John          4.0               3.0
4   Jenny          NaN               1.0
5  Leslie          NaN               5.0
</code>```

Body:
I have for example 2 data frames with user and their rating for each place such as:

Dataframe 1:

Name    Golden Gate
Adam    1
Susan   4
Mike    5
John    4

Dataframe 2:

Name    Botanical Garden
Jenny   1
Susan   4
Leslie  5
John    3

I want to combine them into a single data frame with the result:

Combined Dataframe:

Name    Golden Gate   Botanical Garden
Adam    1             NA
Susan   4             4
Mike    5             NA
John    4             3
Jenny   NA            1
Leslie  NA            5

How to do that?

Thank you.

Body:
You need to perform an outer join or a concatenation along an axis:

final_df = df1.merge(df2,how='outer',on='Name')

Output:

     Name  Golden Gate  Botanical Garden
0    Adam          1.0               NaN
1   Susan          4.0               4.0
2    Mike          5.0               NaN
3    John          4.0               3.0
4   Jenny          NaN               1.0
5  Leslie          NaN               5.0


问:
I don't know only first element getting picked up by my sql query
I am using sqlite3. I am working on IMDB database. I want to extract the movies with a rating of 10.0 but it's only giving me the first result. Although, I can extract the movie_id but can't reproduce the title.</p>

```<code>sqlite> .schema
CREATE TABLE movies (
                    id INTEGER,
                    title TEXT NOT NULL,
                    year NUMERIC,
                    PRIMARY KEY(id)
                );
CREATE TABLE stars (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE directors (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE ratings (
                movie_id INTEGER NOT NULL,
                rating REAL NOT NULL,
                votes INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id)
            );
CREATE TABLE people (
                id INTEGER,
                name TEXT NOT NULL,
                birth NUMERIC,
                PRIMARY KEY(id)
            );
sqlite> SELECT movie_id from ratings WHERE rating = 10.0;
movie_id
10176328
10342460
10544422
10716326
10914342
11099860
2632430
2633610
3525174
5390098
8035236
8563656
sqlite> SELECT title FROM movies WHERE id = (SELECT movie_id from ratings WHERE rating = 10.0);
title
Exteriores: Mulheres Brasileiras na Diplomacia
sqlite> SELECT title FROM movies where id = '10176328';
title
Exteriores: Mulheres Brasileiras na Diplomacia
sqlite>
</code>```

答:
You want in instead of an equality condition:

```<code>SELECT m.title
FROM movies m
WHERE m.id IN (SELECT r.movie_id from ratings r WHERE r.rating = 10.0)
</code>```

That is because the subquery does return more that one row. In many databases, this would generate a runtime error, however it seems like sqlite is flex enough to handle this without error (but still not doing what you want).

Body:
I am using sqlite3. I am working on IMDB database. I want to extract the movies with a rating of 10.0 but it's only giving me the first result. Although, I can extract the movie_id but can't reproduce the title.

sqlite> .schema
CREATE TABLE movies (
                    id INTEGER,
                    title TEXT NOT NULL,
                    year NUMERIC,
                    PRIMARY KEY(id)
                );
CREATE TABLE stars (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE directors (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE ratings (
                movie_id INTEGER NOT NULL,
                rating REAL NOT NULL,
                votes INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id)
            );
CREATE TABLE people (
                id INTEGER,
                name TEXT NOT NULL,
                birth NUMERIC,
                PRIMARY KEY(id)
            );
sqlite> SELECT movie_id from ratings WHERE rating = 10.0;
movie_id
10176328
10342460
10544422
10716326
10914342
11099860
2632430
2633610
3525174
5390098
8035236
8563656
sqlite> SELECT title FROM movies WHERE id = (SELECT movie_id from ratings WHERE rating = 10.0);
title
Exteriores: Mulheres Brasileiras na Diplomacia
sqlite> SELECT title FROM movies where id = '10176328';
title
Exteriores: Mulheres Brasileiras na Diplomacia
sqlite>

Body:
You want in instead of an equality condition:

SELECT m.title
FROM movies m
WHERE m.id IN (SELECT r.movie_id from ratings r WHERE r.rating = 10.0)

That is because the subquery does return more that one row. In many databases, this would generate a runtime error, however it seems like sqlite is flex enough to handle this without error (but still not doing what you want).


问:
python why in my json array each json element have the same value
So I have a json template and I am reading from a csv to update the some of the value of the json properties. I then put all the json in a array to write to a file. but in my file, all the json elements have the same value.
The issue is the old values are being overwritten some how. How should I fix that?

```<code>def main():
    df = pd.read_csv("Daily_EXRATE.csv")
    df = df.loc[df['Field1'] == '04']
    opdb = {
      "sell_rate": 1.2676,
      "type": "currency_exchange",
      "version": "1"
    }
    opdbarray = []
    for index, rowsr in df.iterrows():
        data = {}
        data = rowsr.to_json()
        data = json.loads(data)
        opdb["sell_rate"] = data["Field11"]
        opdbarray.append(opdb)
        print(json.dumps(opdb, indent = 4 ))

    # now write output to a file
    jsonDataFile = open("ccData_1.json", "w")
    jsonDataFile.write(json.dumps(opdbarray, indent=4, sort_keys=True))
    jsonDataFile.close()
</code>```

outputs are all the same

```<code>[
{
    "sell_rate": "2.1058000000",
    "type": "currency_exchange",
    "version": "1"
},
{
    "sell_rate": "2.1058000000",
    "type": "currency_exchange",
    "version": "1"
},
{
    "sell_rate": "2.1058000000",
    "type": "currency_exchange",
    "version": "1"
},
</code>```

答:
You're appending the same obdb dictionary to apdbarray each time through the loop, just replacing its sell_rate element. You need to create a new dictionary each time.

```<code>def main():
    df = pd.read_csv("Daily_EXRATE.csv")
    df = df.loc[df['Field1'] == '04']
    opdbarray = []
    for index, rowsr in df.iterrows():
        data = {}
        data = rowsr.to_json()
        data = json.loads(data)
        opdb = {
          "sell_rate": 1.2676,
          "type": "currency_exchange",
          "version": "1",
          "sell_rate": data["Field11"]
        }
        opdbarray.append(opdb)
        print(json.dumps(opdb, indent = 4 ))

    # now write output to a file
    jsonDataFile = open("ccData_1.json", "w")
    jsonDataFile.write(json.dumps(opdbarray, indent=4, sort_keys=True))
    jsonDataFile.close()
</code>```

Body:
So I have a json template and I am reading from a csv to update the some of the value of the json properties. I then put all the json in a array to write to a file. but in my file, all the json elements have the same value.
The issue is the old values are being overwritten some how. How should I fix that?

def main():
    df = pd.read_csv("Daily_EXRATE.csv")
    df = df.loc[df['Field1'] == '04']
    opdb = {
      "sell_rate": 1.2676,
      "type": "currency_exchange",
      "version": "1"
    }
    opdbarray = []
    for index, rowsr in df.iterrows():
        data = {}
        data = rowsr.to_json()
        data = json.loads(data)
        opdb["sell_rate"] = data["Field11"]
        opdbarray.append(opdb)
        print(json.dumps(opdb, indent = 4 ))

    # now write output to a file
    jsonDataFile = open("ccData_1.json", "w")
    jsonDataFile.write(json.dumps(opdbarray, indent=4, sort_keys=True))
    jsonDataFile.close()

outputs are all the same

[
{
    "sell_rate": "2.1058000000",
    "type": "currency_exchange",
    "version": "1"
},
{
    "sell_rate": "2.1058000000",
    "type": "currency_exchange",
    "version": "1"
},
{
    "sell_rate": "2.1058000000",
    "type": "currency_exchange",
    "version": "1"
},

Body:
You're appending the same obdb dictionary to apdbarray each time through the loop, just replacing its sell_rate element. You need to create a new dictionary each time.

def main():
    df = pd.read_csv("Daily_EXRATE.csv")
    df = df.loc[df['Field1'] == '04']
    opdbarray = []
    for index, rowsr in df.iterrows():
        data = {}
        data = rowsr.to_json()
        data = json.loads(data)
        opdb = {
          "sell_rate": 1.2676,
          "type": "currency_exchange",
          "version": "1",
          "sell_rate": data["Field11"]
        }
        opdbarray.append(opdb)
        print(json.dumps(opdb, indent = 4 ))

    # now write output to a file
    jsonDataFile = open("ccData_1.json", "w")
    jsonDataFile.write(json.dumps(opdbarray, indent=4, sort_keys=True))
    jsonDataFile.close()


问:
Why does the C# compiler allow a duplicated variable in nested scope?
Historically, when developing in .Net I could not duplicate the name of variable in nested scope. However, after recently updating Visual Studio 2019 to version 16.4.2 I have noticed that variable names can be duplicated in nested scope.

For example:

```<code>var test = "hello";
Console.WriteLine(test);
var things = new []{"one", "two", "three"};
things.Select(test => // <- test is duplicated here, normally this breaks compilation
{
    Console.WriteLine(test);
    return test;
}).ToList();

// output:
// hello
// one
// two
// three
</code>```

https://dotnetfiddle.net/h85BK4

Why is this suddenly allowed?

Follow up question: If this is a new language "feature", is there a way to configure Visual Studio to continue to break when a variable is duplicated in nested scope?

答:
my guess is that the select function is being compiled as static since it has no connections to the host method body. it just prints and returns the item in question. this does not require any access to the method and as such, it can for optimization reasons be moved out of the method body and put on its own within the global scope.

and in this case, that test variable is its own variable and has no connections to the above test variable.

as for preventing this, you can't tell vs to throw an error when it occurs, you will just have manually change the variable name.

Body:
Historically, when developing in .Net I could not duplicate the name of variable in nested scope. However, after recently updating Visual Studio 2019 to version 16.4.2 I have noticed that variable names can be duplicated in nested scope.

For example:

var test = "hello";
Console.WriteLine(test);
var things = new []{"one", "two", "three"};
things.Select(test => // <- test is duplicated here, normally this breaks compilation
{
    Console.WriteLine(test);
    return test;
}).ToList();

// output:
// hello
// one
// two
// three

https://dotnetfiddle.net/h85BK4

Why is this suddenly allowed?

Follow up question: If this is a new language "feature", is there a way to configure Visual Studio to continue to break when a variable is duplicated in nested scope?


问:
OperationalError: database is locked
I have made some repetitive operations in my application (testing it), and suddenly I’m getting a weird error:

```<code>OperationalError: database is locked
</code>```

I've restarted the server, but the error persists. What can it be all about?

答:
I had a similar error, right after the first instantiation of Django (v3.0.3). All recommendations here did not work apart from:

deleted the db.sqlite3 file and lose the data there, if any,

python manage.py makemigrations

python manage.py migrate

Btw, if you want to just test PostgreSQL:

docker run --rm --name django-postgres \
  -e POSTGRES_PASSWORD=mypassword \
  -e PGPORT=5432 \
  -e POSTGRES_DB=myproject \
  -p 5432:5432 \
  postgres:9.6.17-alpine
```

<p>Change the <code>settings.py</code> to add this <code>DATABASES</code>:</p>

<pre class="lang-py prettyprint-override"><code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'myproject',
        'USER': 'postgres',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
</code>```

...and add database adapter:

```<code>pip install psycopg2-binary
</code>```

Then the usual:

```<code>python manage.py makemigrations
python manage.py migrate
</code>```

ContentLicense: CC BY-SA 3.0

Title: OperationalError: database is locked

Body:
I have made some repetitive operations in my application (testing it), and suddenly I’m getting a weird error:

OperationalError: database is locked

I've restarted the server, but the error persists. What can it be all about?

Body:
I had a similar error, right after the first instantiation of Django (v3.0.3). All recommendations here did not work apart from:

deleted the db.sqlite3 file and lose the data there, if any,

python manage.py makemigrations

python manage.py migrate

Btw, if you want to just test PostgreSQL:

docker run --rm --name django-postgres \
  -e POSTGRES_PASSWORD=mypassword \
  -e PGPORT=5432 \
  -e POSTGRES_DB=myproject \
  -p 5432:5432 \
  postgres:9.6.17-alpine

Change the settings.py to add this DATABASES:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'myproject',
        'USER': 'postgres',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

...and add database adapter:

pip install psycopg2-binary

Then the usual:

python manage.py makemigrations
python manage.py migrate


问:
How can I correctly flag the end of the first sequence of a group?
This is an example of the the type of dataframe that I'm using and the desired column output.

```<code>reprEx <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"))

Desireddf <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             desiredResult = c(0,0,1,1,0,0,1,0,0,1,1,1,1,1))
</code>```

I am trying to use dplyr to correctly flag whenever a stage changes within a grouped id. The approved and declined flags are easy because I only have to flag the first case of a declined or approved appearing with:

```<code>    reprExWrong <- reprEx %>% group_by(id,stage1) %>%
  mutate(desiredResult = ifelse(stage1 == last(stage1) & stage1 == "open",1,
                                ifelse(stage1 == first(stage1) & stage1 %in% c("approved","declined"),1,0)
                                )
  )
</code>```

The issue is with the open stage. I only want to apply a flag for when the first sequences of opens ends within a group of id's. With the code that I have now it is choosing the last open within the group, even if it wasn't part of the first sequence of opens. for example:

```<code>reprExWrong <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             notdesiredResult = c(0,0,0,1,0,1,1,0,0,1,1,1,1,1))
</code>```

In this case, within id1 I would need the flag to show up where the sequence reaches the last open before approved appears, and not in the open after approved appears. I only need the flag in the row of the last occurrence of open if that succession of opens is the first succession within the id. Sorry for any confusion, I would be happy to further elaborate. This is just to correctly identify stage transitions for recording purposes

答:
Try this:

reprEx %>%
  group_by(id) %>%
  mutate(result = stage1 != lag(stage1),
         result = ifelse(is.na(result), 0, result))
```

Body:
This is an example of the the type of dataframe that I'm using and the desired column output.

reprEx <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"))

Desireddf <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             desiredResult = c(0,0,1,1,0,0,1,0,0,1,1,1,1,1))

I am trying to use dplyr to correctly flag whenever a stage changes within a grouped id. The approved and declined flags are easy because I only have to flag the first case of a declined or approved appearing with:

    reprExWrong <- reprEx %>% group_by(id,stage1) %>%
  mutate(desiredResult = ifelse(stage1 == last(stage1) & stage1 == "open",1,
                                ifelse(stage1 == first(stage1) & stage1 %in% c("approved","declined"),1,0)
                                )
  )

The issue is with the open stage. I only want to apply a flag for when the first sequences of opens ends within a group of id's. With the code that I have now it is choosing the last open within the group, even if it wasn't part of the first sequence of opens. for example:

reprExWrong <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             notdesiredResult = c(0,0,0,1,0,1,1,0,0,1,1,1,1,1))

In this case, within id1 I would need the flag to show up where the sequence reaches the last open before approved appears, and not in the open after approved appears. I only need the flag in the row of the last occurrence of open if that succession of opens is the first succession within the id. Sorry for any confusion, I would be happy to further elaborate. This is just to correctly identify stage transitions for recording purposes


问:
PHP missing function arguments in exception stack trace
I am working to evolve my own error handler for my php apps and I need to send a pretty Exception report to the user on development server.
So, when it catches an Exception, it have to parse the exception stack trace to show function, line arguments, etc.
But, I no more have the arguments in function calls.

I think this is caused by XDebug and I tried to change the value of xdebug.collect_params to fix it but without any success.
In fact, this config only changes the display of xdebug default report that now have the function call parameters.

I made a test script to test it so I let you see.

```<code><?php
$config = 'xdebug.collect_params';
echo "Current value of $config is<br />\n";
var_dump(ini_get($config));

ini_set($config, 3);

function fallDeepToHell($param) {
    echo 'Param is : ' . $param . "<br>\n";
    throw new Exception();
}

try {
    fallDeepToHell('from heaven');
} catch(Exception $e) {
    var_dump($e->getTrace());
    var_dump($e->getTraceAsString());
}
fallDeepToHell('from heaven');
</code>```

The result on my development server is

I am using PHP 7.4 with FPM.

My php.ini changes:

```<code>max_execution_time = 30
memory_limit = 128M
error_reporting = E_ALL
display_errors = On
display_startup_errors = On
html_errors = On
post_max_size = 100M
upload_max_filesize = 49M
date.timezone = Europe/Paris

;[mail function]
mail.add_x_header = On

;[Session]
session.gc_divisor = 1000
session.gc_maxlifetime = 43200
</code>```

My XDebug settings are only about remote things.

答:
I had the same problem, it turned out to be the new zend.exception_ignore_args INI directive introduced in PHP 7.4.

zend.exception_ignore_args is a new INI directive for including or
  excluding arguments from stack traces generated from exceptions.

Body:
I am working to evolve my own error handler for my php apps and I need to send a pretty Exception report to the user on development server.
So, when it catches an Exception, it have to parse the exception stack trace to show function, line arguments, etc.
But, I no more have the arguments in function calls.

I think this is caused by XDebug and I tried to change the value of xdebug.collect_params to fix it but without any success.
In fact, this config only changes the display of xdebug default report that now have the function call parameters.

I made a test script to test it so I let you see.

<?php
$config = 'xdebug.collect_params';
echo "Current value of $config is
\n";
var_dump(ini_get($config));

ini_set($config, 3);

function fallDeepToHell($param) {
    echo 'Param is : ' . $param . "
\n";
    throw new Exception();
}

try {
    fallDeepToHell('from heaven');
} catch(Exception $e) {
    var_dump($e->getTrace());
    var_dump($e->getTraceAsString());
}
fallDeepToHell('from heaven');

The result on my development server is

I am using PHP 7.4 with FPM.

My php.ini changes:

max_execution_time = 30
memory_limit = 128M
error_reporting = E_ALL
display_errors = On
display_startup_errors = On
html_errors = On
post_max_size = 100M
upload_max_filesize = 49M
date.timezone = Europe/Paris

;[mail function]
mail.add_x_header = On

;[Session]
session.gc_divisor = 1000
session.gc_maxlifetime = 43200

My XDebug settings are only about remote things.


问:
Port exposed with docker run but not docker-compose up
I am trying to run rabbitmq along with influxdb TICK stack with docker-compose. When I run rabbitmq with this command:docker run -d --rm -p 5672:5672 -p 15672:15672 rabbitmq:3-management, both ports are open and I am able to access from a remote machine. However, when I run rabbitmq as part of a docker-compose file, it is not accessable from a remote machine. Here is my docker-compose.yml file:

```<code>version: "3.7"

services:
  influxdb:
    image: influxdb
    volumes:
      - ./influxdb/influxdb/data/:/var/lib/influxdb/
      - ./influxdb/influxdb/config/:/etc/influxdb/
    ports:
      - "8086:8086"

  rabbitmq:
    image: rabbitmq:3-management
    volumes:
      - ./rabbitmq/data:/var/lib/rabbitmq
    ports:
      - "15672:15672"
      - "5672:5627"

  telegraf:
    image: telegraf
    volumes:
      - ./influxdb/telegraf/config/:/etc/telegraf/
      - /proc:/host/proc:ro
    depends_on:
      - "influxdb"
      - "rabbitmq"

  chronograf:
    image: chronograf
    volumes:
      - ./influxdb/chronograf/data/:/var/lib/chronograf/
    ports:
      - "8888:8888"
    depends_on:
      - "telegraf"

</code>```

More information: when I run this with docker-compose up -d the 8086 and 8888 are accessible from a remote machine (I confirm with using nmap command). Also, either way I am able to access the rabbitmq management console at http://localhost:15672.

How can I set this up so I can access rabbitmq from a remote machine using docker-compose?

Thank you.

答:
Looks like just a typo in the port mapping in docker-compose.yml: 5672:5627 should actually be 5672:5672.

Otherwise the docker-compose configuration looks just fine.

Body:
I am trying to run rabbitmq along with influxdb TICK stack with docker-compose. When I run rabbitmq with this command:docker run -d --rm -p 5672:5672 -p 15672:15672 rabbitmq:3-management, both ports are open and I am able to access from a remote machine. However, when I run rabbitmq as part of a docker-compose file, it is not accessable from a remote machine. Here is my docker-compose.yml file:

version: "3.7"

services:
  influxdb:
    image: influxdb
    volumes:
      - ./influxdb/influxdb/data/:/var/lib/influxdb/
      - ./influxdb/influxdb/config/:/etc/influxdb/
    ports:
      - "8086:8086"

  rabbitmq:
    image: rabbitmq:3-management
    volumes:
      - ./rabbitmq/data:/var/lib/rabbitmq
    ports:
      - "15672:15672"
      - "5672:5627"

  telegraf:
    image: telegraf
    volumes:
      - ./influxdb/telegraf/config/:/etc/telegraf/
      - /proc:/host/proc:ro
    depends_on:
      - "influxdb"
      - "rabbitmq"

  chronograf:
    image: chronograf
    volumes:
      - ./influxdb/chronograf/data/:/var/lib/chronograf/
    ports:
      - "8888:8888"
    depends_on:
      - "telegraf"

More information: when I run this with docker-compose up -d the 8086 and 8888 are accessible from a remote machine (I confirm with using nmap command). Also, either way I am able to access the rabbitmq management console at http://localhost:15672.

How can I set this up so I can access rabbitmq from a remote machine using docker-compose?

Thank you.


问:
Panel Size not staying the same between two computers in unity
I am using unity for a group project, on one computer we get everything set up and looking nice, but after pushing to GitHub and opening on a personal computer the screen size seems to be smaller and buttons are off the panel. Is there a setting that we are missing?

Personal computer view

答:
Short Answer

This is happening because you are both using absolute positioning in your Rect Transform, and not properly nesting the Back/Main Menu/? buttons inside your panel in the Scene hierarchy (leftmost panel).

Depending on your specific need, I would either make Nav a child of the panel, if you want your Nav buttons to be inside your panel, or else change your Rect Transform anchor presets for Nav to something like "Stretch Top" rather than "Center Center".

Generally, you want to use "stretch" with dimensions that are screen-dependent (e.g. "this nav area should always span the width of the screen"). For things that are not screen-dependent (e.g. "this nav button should always be 5 pixels below the top of the screen"), it's okay to use manual position values.

Long Answer

There are two primary means of positioning under the hood in Unity:

Anchors

Pixel Offsets

Anchors

Anchors essentially define the element's relation to its parent. Some examples:

The default anchor of Min: (.5, .5), Max: (.5, .5) means that the element's position will be calculated from the x-center and y-center of the parent element.

An anchor of Min: (0, .5), Max: (0, .5) means that the element's position will be calculated from the midpoint of the parent's left edge.

An anchor of Min: (1, 1), Max: (1, 1) means that the element's position will be calculated from the parent's top-right corner.

Note that all of the example anchors so far have had the same minimum and maximum values, resulting in an anchor that is a single point. If you set the minimum and maximum values differently, it will instead create an anchor "box" that the element will scale to fill. Some examples of this:

An anchor of Min: (0, 0), Max: (1, 1) means that the element will scale to be the same size as the parent.

An anchor of Min: (0, 0), Max: (.5, .5) means that the element will
scale to fill the bottom-left quarter of the parent.

An anchor of Min: (0, 0), Max: (1, .5) means that the element will
scale to fill the bottom half of the parent.

Pixel Offsets

Now that we understand anchors, what are pixel offsets? Essentially, they are absolute pixel positional offsets from the edges of the anchors. For example:

An anchor of Min: (0, 0), Max: (.5, .5) and pixel offset of Top: 40 Right: 10 means that the element will scale to fill the bottom-left quarter of the parent, and then additionally scale to fill 40 pixels above the vertical midpoint of the screen and 10 pixels to the right of the horizontal midpoint of the screen.

Hey, I don't have any pixel offsets!

Yes you do, but the Unity inspector pane uses different terminology for them depending on how your anchors are set up. You'll see "Top", "Left", "Right", and "Bottom" only if you have your anchors set to make a rectangle rather than a point. Otherwise, you may see fields like "Pos X", "Pos Y", "Width", or "Height". However, these fields are merely conceptual abstractions for offsets. For example, setting "Width" to 100 is equivalent to setting "Left" to -50 and "Right" to 50, and so on.

Great, how should I use these?

Generally, use anchor boxes to create responsive layouts, then use offsets inside those layout boxes to fine-tune positions.


问:
Counting continuous sequences of months
If I have a vector of year and month coded like this:

```<code>ym <- c(
  201401,
  201403:201412,
  201501:201502,
  201505:201510,
  201403
)
</code>```

And I'd like to end up with a vector that looks like this:

```<code> [1]  1  1  2  3  4  5  6  7  8  9 10  11  12  1  2  3  4  5  6  1
</code>```

That is, I want to count continuous sequences of month records. Can anyone recommend an approach? I've spinning my wheels with something like this:

```<code>ym_date <- as.Date(paste0(ym, 01), format = "%Y%m%d")

diff(ym_date)
</code>```

but haven't been able to get any farther because I'm not sure how to flag that start of a sequence when we are dealing with months. Any base R, tidyverse, data.frame centric or not solution would be welcomed.

答:
Maybe you can try the following base R code with rle

```<code>r <- unlist(sapply(rle(cumsum(c(1,round(as.numeric(diff(ym_date))/30.24)!=1)))$lengths,seq_along))
</code>```

or with ave

```<code>r <- ave(ym,cumsum(c(1,round(as.numeric(diff(ym_date))/30.24)!=1)),FUN = seq_along)
</code>```

such that

```<code>> r
 [1]  1  1  2  3  4  5  6  7  8  9 10  11  12  1  2  3  4  5  6  1
</code>```

Title: Counting continuous sequences of months

Body:
If I have a vector of year and month coded like this:

ym <- c(
  201401,
  201403:201412,
  201501:201502,
  201505:201510,
  201403
)

And I'd like to end up with a vector that looks like this:

 [1]  1  1  2  3  4  5  6  7  8  9 10  11  12  1  2  3  4  5  6  1

That is, I want to count continuous sequences of month records. Can anyone recommend an approach? I've spinning my wheels with something like this:

ym_date <- as.Date(paste0(ym, 01), format = "%Y%m%d")

diff(ym_date)

but haven't been able to get any farther because I'm not sure how to flag that start of a sequence when we are dealing with months. Any base R, tidyverse, data.frame centric or not solution would be welcomed.

Body:
Maybe you can try the following base R code with rle

r <- unlist(sapply(rle(cumsum(c(1,round(as.numeric(diff(ym_date))/30.24)!=1)))$lengths,seq_along))

or with ave

r <- ave(ym,cumsum(c(1,round(as.numeric(diff(ym_date))/30.24)!=1)),FUN = seq_along)

such that

> r
 [1]  1  1  2  3  4  5  6  7  8  9 10  11  12  1  2  3  4  5  6  1


问:
Can't perform I/O in foldr?
I have a Data.Map structure that maps Strings to Stringss. For whatever reason, I want to print the contents of the map in the format key: value using foldrWithKey, like so:

```<code>M.foldrWithKey (\k v b -> putStrLn (k++": "++v++"\n")) (return ()) data
</code>```

However, only the first element of the map appears in the output (even though the map has more than one element). But when I try to construct a list using foldrWithKey and then print it, all of the elements show up:

```<code>print (M.foldrWithKey (\k v b -> k:b) [] data)
</code>```

So, why don't the other elemnts show up when trying to perform I/O? Is it the way foldr works or is there some subtle lazy-io-related quirk that I'm missing?

答:
It's because of how a right fold works, yes. A fold function is an accumulation: At each step, given one element (in this case, the key and value) and the accumulated result of the rest of the data, it combines them into a single result. The fold as a whole does that recursively to summarize the entire set of data.

In your case, you're discarding the "result" input of the accumulator function--note that the b argument is never used. Keep in mind that IO a isn't just a value of type a with some extra junk attached, what it actually represents is a computation to produce an a, and that computation will only be run by combining it with other computations as part of the final value of the main function (or, in GHCi, of the expression that gets evaluated).

By discarding the accumulated value, the other computations never become part of the final result, and so the values never get printed.

From the way you phrased the question I'm guessing that you're still more comfortable in imperative-style programming than Haskell's functional style. Obviously, in an imperative language where the printing is actually "happening" during the fold in some meaningful sense, it would be reasonable to assume that the accumulated value is useless. If it helps, think of this more as a sort of meta-programming; you're not actually writing a loop to print the values, you're constructing an imperative program that does the actual printing, and by discarding the accumulated value you're basically discarding all but the first lines of an unrolled loop, to abuse the analogy badly.

At any rate, what you probably want in this case is to take the "print the rest of the data" action, the b parameter, and combine it with the putStrLn ... action using (>>), an operator that basically means "execute the first action, ignore the result, execute the second". This is a pretty direct translation of the imperative style "print statement in a loop".

Also, while I understand that it's beside the point entirely, I'd probably avoid mixing the formatting and printing that way anyhow. To my eye, it seems tidier to format each key/value pair separately into a list, then just mapM_ putStrLn over that.

mapM_ is a higher-order function that describes the essence of what you're doing here; given a list of some type a and a function that turns an a into an IO action of some sort, it applies the function to each item and runs the resulting list of actions in order. mapM_ has type Monad m => (a -> m b) -> [a] -> m () which seems cryptic at first, but one of the nice things about Haskell is that once you get used to reading type signatures, mapM_'s type is not only understandable at a glance, it's nearly self-documenting in that there's only one sensible thing for a function with that type to do and that's precisely what mapM_ itself does.

Title: Can't perform I/O in foldr?

Body:
I have a Data.Map structure that maps Strings to Stringss. For whatever reason, I want to print the contents of the map in the format key: value using foldrWithKey, like so:

M.foldrWithKey (\k v b -> putStrLn (k++": "++v++"\n")) (return ()) data

However, only the first element of the map appears in the output (even though the map has more than one element). But when I try to construct a list using foldrWithKey and then print it, all of the elements show up:

print (M.foldrWithKey (\k v b -> k:b) [] data)

So, why don't the other elemnts show up when trying to perform I/O? Is it the way foldr works or is there some subtle lazy-io-related quirk that I'm missing?


问:
Model Checking : Safety and Liveness properties
I know what Safety and Liveness properties are and the relation between Safety and Badprefixes of an LT property. I wanted to understand about the closure properties and why the closure of a safety property is the property itself. The image is for reference. Can someone explain me the concepts that can be used that will enable me to answer the questions, it would be really helpful.

答:
We are considering languages of infinite traces.

As you hinted, a language L is defined to be a safety property if for every trace not in L, there exists a bad prefix, that is, a finite prefix such all infinite continuations of the prefix are not in L. So intuitively, a safety property is about some bad event not happening.

For a given language L, the language closure(L) is defined to consist of all traces where every finite prefix is also prefix of a trace in L.

The standard example for taking the closure would be for L = a*b^omega = { bbb..., abbb..., aabbb..., aaabbb... }. The language L contains all traces with a finite prefix of a's and then infinitely many b's. Then closure(L) = a*b^omega + a^omega = L U {aaa...}. The trace of infinitely many a's is not contained in L, but every finite prefix of a^omega is also prefix of a trace in L. Therefore a^omega is contained in the closure of L.

Now your question is why for a safety property L, it holds that L = closure(L).

Let L be a safety property. We have to show that every trace in L is contained in closure(L) and vice versa that every trace in closure(L) is contained in L.

Every trace in L is contained in closure(L): Consider a trace sigma in L. Then every finite prefix of sigma is a prefix of sigma. Therefore every finite prefix of sigma is the prefix of a trace in L. By definition of closure(L), it follows that sigma is in closure(L).

Every trace in closure(L) is contained in L: Let sigma be in closure(L). Assume sigma is not in L. By definition of safety properties, sigma has a finite prefix w, such that no infinite continuation of w is in L. But then w cannot be a prefix of a word in L. But by definition of closure(L), every finite prefix of sigma has to be in L. Contradiction. Since the assumption that sigma is not in L leads to a contradiction, it follows that sigma is in L.

Sidenote A: Note that for 1. we didn't use that L is a safety property. The property that L is a subset of closure(L) holds in general, not just for safety properties.

Sidenote B: In the example for the closure we noted that for L = a*b^omega, we have closure(L) = a*b^omega + a^omega. Therefore L is unequal to closure(L), so L cannot be a safety property. We can see this from the trace a^omega, which is not in L, but does not have a bad prefix, as every finite prefix of a^omega is of the form a* and can be continued to a trace of the form a*b^omega in L.

Sidenote C: We could also ask the reverse question, when L = closure(L), is L a safety property? The answer is yes. Let L be a language with L = closure(L). Consider a trace sigma that is not in L. We have to show that sigma has a bad prefix. By L = closure(L), we have sigma is not in closure(L). By definition of closure(L), if all finite prefixes of sigma are in L, we would have sigma in closure(L). Thus, from sigma not in closure(L), it follows that there is some finite prefix w of sigma, such that all traces sigma' in L do not have w as a prefix. In other words, every infinite continuation of w cannot be a trace in L. Therefore w is a bad prefix. In conclusion, every trace sigma that is not in L has a bad prefix thus L is a safety property.

Sidenote D: From your original question and Sidenote C we can conclude that L is a safety property if and only if L = closure(L). This improves our understanding of what is means to take the closure of L: Adding all traces that do not have a bad prefix. Further, you could verify that taking the closure of the closure does not add any new traces, so for any L, it holds that closure(L) = closure(closure(L)). Therefore for any L, it holds that closure(L) is a safety property.

Sidenote E: To answer your comment question for an example of a language that is equal to its closure: Based on Sidenote D, we could take any safety property: Consider the language L over the alphabet {a,b,c} that is L = { sigma in {a,b,c}^omega | sigma has no c }. So the bad prefixes would be all finite words that have a c (if you think of the trace as modelling the execution of some program, maybe c could mean "the program has a crash" and does random things after that). We can verify that L = closure(L): We already know that L subset closure(L), based on 1. above. For the other direction, consider a trace sigma in closure(L). By definition of closure(L), every finite prefix w of sigma has to be a prefix of a trace sigma' in L. Since by definition of L, sigma' cannot contain a c, it follows that w cannot contain a c. When every finite prefix w of sigma cannot contain c, it follows that sigma cannot contain c. Therefore sigma is in L. We conclude L = closure(L).


问:
Using table() function from base with dplyr pipe-syntax?
I enjoy the syntax of dplyr, but I'm struggling with easily obtaining a contingency table in the same way that I can get with the base R table() function. table() is OK, but I can't figure out how to incorporate it into the dplyr pipe syntax.

Thank you for your help.

Here is some example data that has the output I'm trying to get to.

```<code>df <- tibble(id=c(rep("A",100),rep("B",100),rep("C",100)),
               val=c(rnorm(300,mean=500,sd=100))) %>%
  mutate(val_bin=cut(val,breaks=5))

table(df$id,df$val_bin)
</code>```

Output:

```<code>    (210,325] (325,440] (440,554] (554,669] (669,784]
  A         4        22        55        18         1
  B         6        19        46        24         5
  C         3        23        44        22         8
</code>```

答:
We can select the columns of interest and apply the table

```<code>library(dplyr)
df %>%
    select(id, val_bin) %>%
    table
</code>```

Or another option is to wrap within {}

```<code>df %>%
    {table(.$id, .$val_bin)}
</code>```

In tidyverse, it is a bit more convoluted to get the required output

```<code>library(dplyr)
library(tidyr)
df %>%
   count(id, val_bin) %>%
   pivot_wider(names_from = val_bin, values_from = n, values_fill = list(n = 0)) %>%
   column_to_rownames('id')
#   (214,338] (338,461] (461,584] (584,707] (707,831]
#A         5        30        44        20         1
#B         9        30        34        27         0
#C         8        28        43        20         1
</code>```

Body:
I enjoy the syntax of dplyr, but I'm struggling with easily obtaining a contingency table in the same way that I can get with the base R table() function. table() is OK, but I can't figure out how to incorporate it into the dplyr pipe syntax.

Thank you for your help.

Here is some example data that has the output I'm trying to get to.

df <- tibble(id=c(rep("A",100),rep("B",100),rep("C",100)),
               val=c(rnorm(300,mean=500,sd=100))) %>%
  mutate(val_bin=cut(val,breaks=5))

table(df$id,df$val_bin)

Output:

    (210,325] (325,440] (440,554] (554,669] (669,784]
  A         4        22        55        18         1
  B         6        19        46        24         5
  C         3        23        44        22         8

Body:
We can select the columns of interest and apply the table

library(dplyr)
df %>%
    select(id, val_bin) %>%
    table

Or another option is to wrap within {}

df %>%
    {table(.$id, .$val_bin)}

In tidyverse, it is a bit more convoluted to get the required output

library(dplyr)
library(tidyr)
df %>%
   count(id, val_bin) %>%
   pivot_wider(names_from = val_bin, values_from = n, values_fill = list(n = 0)) %>%
   column_to_rownames('id')
#   (214,338] (338,461] (461,584] (584,707] (707,831]
#A         5        30        44        20         1
#B         9        30        34        27         0
#C         8        28        43        20         1


问:
Generating random values with custom PDF
I have a large dataset (over 300000 values), and I have created a PDF for it with stats.gaussian_kde as follows:

```<code>kernel=scipy.stats.gaussian_kde(vals)
ind=np.linspace(np.min(vals), np.max(vals),1000)
PDE=kernel.evaluate(ind)
</code>```

Now I want to generate new random values from this pdf, but I'm not sure how to do that.  Does anyone have any examples?

Body:
I have a large dataset (over 300000 values), and I have created a PDF for it with stats.gaussian_kde as follows:

kernel=scipy.stats.gaussian_kde(vals)
ind=np.linspace(np.min(vals), np.max(vals),1000)
PDE=kernel.evaluate(ind)

Now I want to generate new random values from this pdf, but I'm not sure how to do that.  Does anyone have any examples?

Body:
Use the resample method.

vals = [1,2,3,4,5]
kernel = scipy.stats.gaussian_kde(vals)
my_random_vals = kernel.resample(size=10)

print(my_random_vals)
[[ 2.18467151 -1.22069121  2.64074108  0.32268845  2.78022227  6.29483273
   1.94848359  4.79865993  1.30363424  3.71441989]]


问:
white line inserted during second filter using jquery (Chrome Bug)
I have a filter that hides elements of a table that don't pass a test (time less than x hours). Everything works fine the first time. I chose time. Elements that don't pass test are hidden. I reload to show all. I try to filter again. This time when all other rows are hidden there is a blank line that is inserted between my table headers and the contents. Each time I rerun the filter another line gets inserted.

Here is code:

Html:

```<code><div id="timeSelect">
<select id="FilterTimeList" name="FilterTimeList"><option value="">-- select Time --
</option>
</select>
</div>

<a id="filterLink" href="#" onclick="timeFilter(this);">Filter</a>
<table width="100%">
<tr>
<td>Log Id</td>
<td>Message</td>
<td>SourceStackTrace</td>
<td>awData</td>
<td>LogDate</td>
</tr>
<tr class="list">
<td class="myTitle">1</td>
<td>this is my message</td>
<td></td><td></td>
<td class="exceptionDate">5/4/2011 5:41:00 PM</td>
<td></td>
</tr>
<tr class="list">
<td class="myTitle">2</td>
<td>this is my message 2</td>
<td></td><td></td>
<td class="exceptionDate">4/27/2011 5:41:24 PM</td>
<td>
</td>
</tr>
<tr class="list">
<td class="myTitle">12</td>
<td>this is my message 12</td>
<td></td><td></td>
<td class="exceptionDate">5/16/2011 12:06:38 PM</td>
<td></td>
</tr>
</table>
</code>```

Javascript:

```<code><script src="http://code.jquery.com/jquery-1.5.1.min.js" type="text/javascript"/>
<script type="text/javascript">
var myOptions =
{
  0: 'Show All',
  1: 'Last 12 hours',
  2: 'Last 24 hours'
};
$.each(myOptions, function (val, text) {
$('<option />').val(val).text(text).appendTo('#timeSelect select');
});

function timeFilter(a) {
  $('.test').hide();
  var chosenTime = $('#timeSelect select').val();
  var timeCompare;
  switch (chosenTime) {
   case '1':
   timeCompare = 12;
   break;
    case '2':
    timeCompare = 24;
    break;
    }
   var now = new Date();
   var nowHours = now.setHours(now.getHours() - timeCompare);
   var newDate = new Date(nowHours);
   if (chosenTime > 0) {
   var myDateClass = $('.exceptionDate')
   var i = 0
   $(myDateClass).each(function () {
   var myDateClassVal = $(this).text();
   var myDate = new Date(myDateClassVal);
   if (myDate < newDate) {
      $('tr:eq(' + i + ')').slideUp();
      }
      i++;
      });
 }
 else {
   $('.exceptionDate').parent().slideDown();
  }
}
 </script>
</code>```

答:
I think you may be missing some code in your javascript, as you've got an extra '});' after your options code.

Not sure where your extra line is coming from, though.  I got it working in jsFiddle with 1.5.2, so it might be a bug that was corrected in jQuery...

http://jsfiddle.net/QhkGk/

Body:
I have a filter that hides elements of a table that don't pass a test (time less than x hours). Everything works fine the first time. I chose time. Elements that don't pass test are hidden. I reload to show all. I try to filter again. This time when all other rows are hidden there is a blank line that is inserted between my table headers and the contents. Each time I rerun the filter another line gets inserted.

Here is code:

Html:

<select id="FilterTimeList" name="FilterTimeList"><option value="">-- select Time --
</option>
</select>

Filter

Log Id
Message
SourceStackTrace
awData
LogDate

1
this is my message

5/4/2011 5:41:00 PM

2
this is my message 2

4/27/2011 5:41:24 PM

12
this is my message 12

5/16/2011 12:06:38 PM

Javascript:


问:
Xcode, React Native and redux logger: [TOO BIG formatValueCalls XXX exceeded limit of 200]
When running React Native, without debug js remotely, Xcode shows a lot of logs saying:

```<code>[TOO BIG formatValueCalls XXX exceeded limit of 200]
</code>```

The logs seem to appear in redux logger entries.

The errors are thrown by React Native, from a file called console.js in node_modules/react-native/Libraries/polyfills/console.js

Should this be preoccupying? I couldn't find anything related to this on the internet.

答: OK, those messages come from the console.js module in React Native. This module pipes console.log to NSLog on iOS. I am logging out some biiiig objects (which I need to fix), and this module is clipping them (rightly so). So look for places in your code where you're doing something similar.</p>

Body:
When running React Native, without debug js remotely, Xcode shows a lot of logs saying:

[TOO BIG formatValueCalls XXX exceeded limit of 200]

The logs seem to appear in redux logger entries.

The errors are thrown by React Native, from a file called console.js in node_modules/react-native/Libraries/polyfills/console.js

Should this be preoccupying? I couldn't find anything related to this on the internet.


问:
Stored procedure times out when ran from code, but not from query tool
I am trying to figure out why a stored procedure call takes seconds in a SQL server express query window, but when I run call the stored procedure in code the query TIMES OUT.  We are using sql server 2008.  I know it is hard to say exactly what is going on without seeing the stored procedure.  I'm just hoping this is a known issue.  Any guidance is much appreciated.

SQL query that calls "STORED_PROCEDURE_X" and runs in 2 seconds in SQL server express query window:

```<code>EXEC STORED_PROCEDURE_X '07/01/2010', '07/31/2010', 0, '', 'true','', 'Top 20'
</code>```

Code that calls "STORED_PROCEDURE_X" and TIMES OUT:

```<code>SqlConnection connSQL = null;
SqlCommand sqlCmd = null;
SqlDataAdapter sqlDataAdpater = null;
DataTable returnData = null;

try
{
    returnData = new DataTable();
    connSQL = new SqlConnection(sqlConnection);
    sqlCmd = new SqlCommand("STORED_PROC_X", connSQL);
    if (connSQL.State == ConnectionState.Closed)
    {
        connSQL.Open();
    }
    sqlCmd.CommandType = CommandType.StoredProcedure;
    sqlCmd.CommandTimeout = 600;
    sqlCmd.Parameters.Add("@StartDate", SqlDbType.NVarChar).Value = "07/01/2010";
    sqlCmd.Parameters.Add("@EndDate", SqlDbType.NVarChar).Value = "07/31/2010";

    sqlCmd.Parameters.Add("@AuditType", SqlDbType.Int).Value = "0";

    sqlCmd.Parameters.Add("@SortBy", SqlDbType.NVarChar).Value = "";

    sqlCmd.Parameters.Add("@IsClaimDepartment", SqlDbType.NVarChar).Value = "true";
    sqlCmd.Parameters.Add("@IdsList", SqlDbType.NVarChar).Value = "";
    sqlCmd.Parameters.Add("@ReportType", SqlDbType.NVarChar).Value = "Top 20";
    sqlDataAdpater = new SqlDataAdapter(sqlCmd);
    sqlDataAdpater.Fill(returnData);
    if (connSQL.State == ConnectionState.Open)
    {
        connSQL.Close();
    }
    return returnData;
}
catch (Exception ex)
{
    LogErrorMessages("ExecuteStoredProcedure", ex.Message);
    throw ex;
}
</code>```

Exception Received:

```<code>System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
</code>```

答: We had this same issue and thought it was parameter sniffing also, but after trying many things including changing parameter sniffing, using with recompile, drop/recreate, updating statistics, freeing proc cache, we found none of these worked. We tracked it down to a single index that needed to be added. We had just switched from the legacy cardinality estimator to the post-2014 estimator. Switching back to the legacy estimator resolved the issue, or using the new estimator and adding the index.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to figure out why a stored procedure call takes seconds in a SQL server express query window, but when I run call the stored procedure in code the query TIMES OUT.  We are using sql server 2008.  I know it is hard to say exactly what is going on without seeing the stored procedure.  I'm just hoping this is a known issue.  Any guidance is much appreciated.

SQL query that calls "STORED_PROCEDURE_X" and runs in 2 seconds in SQL server express query window:

EXEC STORED_PROCEDURE_X '07/01/2010', '07/31/2010', 0, '', 'true','', 'Top 20'

Code that calls "STORED_PROCEDURE_X" and TIMES OUT:

SqlConnection connSQL = null;
SqlCommand sqlCmd = null;
SqlDataAdapter sqlDataAdpater = null;
DataTable returnData = null;

try
{
    returnData = new DataTable();
    connSQL = new SqlConnection(sqlConnection);
    sqlCmd = new SqlCommand("STORED_PROC_X", connSQL);
    if (connSQL.State == ConnectionState.Closed)
    {
        connSQL.Open();
    }
    sqlCmd.CommandType = CommandType.StoredProcedure;
    sqlCmd.CommandTimeout = 600;
    sqlCmd.Parameters.Add("@StartDate", SqlDbType.NVarChar).Value = "07/01/2010";
    sqlCmd.Parameters.Add("@EndDate", SqlDbType.NVarChar).Value = "07/31/2010";

    sqlCmd.Parameters.Add("@AuditType", SqlDbType.Int).Value = "0";

    sqlCmd.Parameters.Add("@SortBy", SqlDbType.NVarChar).Value = "";

    sqlCmd.Parameters.Add("@IsClaimDepartment", SqlDbType.NVarChar).Value = "true";
    sqlCmd.Parameters.Add("@IdsList", SqlDbType.NVarChar).Value = "";
    sqlCmd.Parameters.Add("@ReportType", SqlDbType.NVarChar).Value = "Top 20";
    sqlDataAdpater = new SqlDataAdapter(sqlCmd);
    sqlDataAdpater.Fill(returnData);
    if (connSQL.State == ConnectionState.Open)
    {
        connSQL.Close();
    }
    return returnData;
}
catch (Exception ex)
{
    LogErrorMessages("ExecuteStoredProcedure", ex.Message);
    throw ex;
}

Exception Received:

System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.


问:
How do I detect an aborted connection in Django?
I have a Django view that does some pretty heavy processing and takes around 20-30 seconds to return a result.

Sometimes the user will end up closing the browser window (terminating the connection) before the request completes -- in that case, I'd like to be able to detect this and stop working.  The work I do is read-only on the database so there isn't any issue with transactions.

In PHP the connection_aborted function does exactly this.  Is this functionality available in Django?

Here's example code I'd like to write:

```<code>def myview(request):
    while not connection_aborted():
        # do another bit of work...
        if work_complete:
            return HttpResponse('results go here')
</code>```

Thanks.

答:
I don't think Django provides it because it basically can't.  More than Django itself, this depends on the way Django interfaces with your web server.  All this depends on your software stack (which you have not specified).  I don't think it's even part of the FastCGI and WSGI protocols!

Edit: I'm also pretty sure that Django does not start sending any data to the client until your view finishes execution, so it can't possibly know if the connection is dead. The underlying socket won't trigger an error unless the server tries to send some data back to the user.

Body:
I have a Django view that does some pretty heavy processing and takes around 20-30 seconds to return a result.

Sometimes the user will end up closing the browser window (terminating the connection) before the request completes -- in that case, I'd like to be able to detect this and stop working.  The work I do is read-only on the database so there isn't any issue with transactions.

In PHP the connection_aborted function does exactly this.  Is this functionality available in Django?

Here's example code I'd like to write:

def myview(request):
    while not connection_aborted():
        # do another bit of work...
        if work_complete:
            return HttpResponse('results go here')

Thanks.


问:
ImageFactory is generating .webp file that is larger than .jpeg file
I have an ASP.NET Core based WebAPI. I am trying to convert uploaded .jpeg images to .webp. I tried using ImageProcessor library along with the ImageProcessor.Plugins.WebP to generate the .webp compressed file. Here is the code I used

```<code>public async Task<IActionResult> Store(IFormFile file)
{
    if(!ModelState.IsValid)
    {
        return Problem("Invalid model!");
    }

    string absoluteFilename = Path.Combine("d:/uploaded_images", Path.GetRandomFileName() + ".webp");

    using var stream = new FileStream(absoluteFilename, FileMode.Create);
    using ImageFactory imageFactory = new ImageFactory(preserveExifData: false);
    imageFactory.Load(file.OpenReadStream())
                .Format(new WebPFormat())
                .Quality(100)
                .Save(stream);

    return Ok(absoluteFilename);
}
</code>```

But the above code takes an 83.9KB JPEG file and created a 379KB WEBP file. I tried to convert my JPEG file to WEBP using an online converter and the outcome was  73KB.

How can I correctly convert the .jpeg file to .webp?

答:
I checked source code of this package and I think a lot of compression benefits gets lost during convertion source image to Bitmap. I tried using Google's tool for converting files to webp and it reduced image file for from 100 KB to 74 KB.
You can embed it into your project.

Starting an exe in Web environment can be tricky, but you can check some articles on this topic http://www.codedigest.com/articles/aspnet/334_working_with_exe_in_aspnet-calling_killingaborting_an_exe.aspx

More about cwebp can be found here https://developers.google.com/speed/webp/docs/cwebp

Download link https://developers.google.com/speed/webp/download

```<code>using System;
using System.Diagnostics;

namespace ConsoleApp15
{
    class Program
    {
        static void Main(string[] args)
        {
            var filePath = @"C:\Users\jjjjjjjjjjjj\Downloads\libwebp-1.0.3-windows-x86\bin\cwebp.exe";
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = filePath;
            startInfo.Arguments = "file.jpeg -o file.webp";

            startInfo.CreateNoWindow = true; // I've read some articles this is required for launching exe in Web environment
            startInfo.UseShellExecute = false;
            try
            {
                using (Process exeProcess = Process.Start(startInfo))
                {
                    exeProcess.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}
</code>```

Body:
I have an ASP.NET Core based WebAPI. I am trying to convert uploaded .jpeg images to .webp. I tried using ImageProcessor library along with the ImageProcessor.Plugins.WebP to generate the .webp compressed file. Here is the code I used

public async Task<IActionResult> Store(IFormFile file)
{
    if(!ModelState.IsValid)
    {
        return Problem("Invalid model!");
    }

    string absoluteFilename = Path.Combine("d:/uploaded_images", Path.GetRandomFileName() + ".webp");

    using var stream = new FileStream(absoluteFilename, FileMode.Create);
    using ImageFactory imageFactory = new ImageFactory(preserveExifData: false);
    imageFactory.Load(file.OpenReadStream())
                .Format(new WebPFormat())
                .Quality(100)
                .Save(stream);

    return Ok(absoluteFilename);
}

But the above code takes an 83.9KB JPEG file and created a 379KB WEBP file. I tried to convert my JPEG file to WEBP using an online converter and the outcome was  73KB.

How can I correctly convert the .jpeg file to .webp?

Body:
I checked source code of this package and I think a lot of compression benefits gets lost during convertion source image to Bitmap. I tried using Google's tool for converting files to webp and it reduced image file for from 100 KB to 74 KB.
You can embed it into your project.

Starting an exe in Web environment can be tricky, but you can check some articles on this topic http://www.codedigest.com/articles/aspnet/334_working_with_exe_in_aspnet-calling_killingaborting_an_exe.aspx

More about cwebp can be found here https://developers.google.com/speed/webp/docs/cwebp

Download link https://developers.google.com/speed/webp/download

using System;
using System.Diagnostics;

namespace ConsoleApp15
{
    class Program
    {
        static void Main(string[] args)
        {
            var filePath = @"C:\Users\jjjjjjjjjjjj\Downloads\libwebp-1.0.3-windows-x86\bin\cwebp.exe";
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = filePath;
            startInfo.Arguments = "file.jpeg -o file.webp";

            startInfo.CreateNoWindow = true; // I've read some articles this is required for launching exe in Web environment
            startInfo.UseShellExecute = false;
            try
            {
                using (Process exeProcess = Process.Start(startInfo))
                {
                    exeProcess.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}


问:
Exchange data.table columns with most prevalent value of columns
I have data

```<code>test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)
</code>```

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

```<code>test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)
</code>```

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

```<code>test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]
</code>```

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

```<code>test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))
</code>```

答:
Another option:

```<code>dtmode <- function(x) x[which.max(rowid(x))]
test[, .(A=unique(A), B=dtmode(B), C=dtmode(C))]
</code>```

data:

```<code>test = data.table(
    A = c(1,1,3,4,5,6),
    B = c("a", "be", "a", "c", "d", "c"),
    C = rep(1, 6)
)
</code>```

Body:
I have data

test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))

Body:
Another option:

dtmode <- function(x) x[which.max(rowid(x))]
test[, .(A=unique(A), B=dtmode(B), C=dtmode(C))]

data:

test = data.table(
    A = c(1,1,3,4,5,6),
    B = c("a", "be", "a", "c", "d", "c"),
    C = rep(1, 6)
)


问:
Load a Bootstrap popover content with AJAX. Is this possible?
The appropriate bits of what I tried are here:

"> Click here

$(".button").popover({html: true})

$(".button").click(function(){
    $(this).popover('show');
    $("#my_popover").load('my_stuff')
})
```

When I click, I see the request get made, but doesn't populate the popover. I don't even see HTML for the popover get added to the DOM, but that could be firebug.

Has anyone tried this?

答:
There are way too many answers here but I also found none of them to be what I wanted. I've extended Ivan Klass's answer to be both Bootstrap 4 appropriate and intelligently cached.

Note that the snippet won't actually load the remote address due to Stackoverflow's CORS policy.

var popoverRemoteContents = function(element) {
  if ($(element).data('loaded') !== true) {
    var div_id = 'tmp-id-' + $.now();
    $.ajax({
      url: $(element).data('popover-remote'),
      success: function(response) {
        $('#' + div_id).html(response);
        $(element).attr("data-loaded", true);
        $(element).attr("data-content", response);
        return $(element).popover('update');
      }
    });
    return '
Loading...
';
  } else {
    return $(element).data('content');
  }
};

$('[data-popover-remote]').popover({
  html: true,
  trigger: 'hover',
  content: function() {
    return popoverRemoteContents(this);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<span data-popover-remote="http://example.com/">Remote Popover test with caching</span></code>```

Body:
The appropriate bits of what I tried are here:

 Click here

$(".button").popover({html: true})

$(".button").click(function(){
    $(this).popover('show');
    $("#my_popover").load('my_stuff')
})

When I click, I see the request get made, but doesn't populate the popover. I don't even see HTML for the popover get added to the DOM, but that could be firebug.

Has anyone tried this?

Body:
There are way too many answers here but I also found none of them to be what I wanted. I've extended Ivan Klass's answer to be both Bootstrap 4 appropriate and intelligently cached.

Note that the snippet won't actually load the remote address due to Stackoverflow's CORS policy.

var popoverRemoteContents = function(element) {
  if ($(element).data('loaded') !== true) {
    var div_id = 'tmp-id-' + $.now();
    $.ajax({
      url: $(element).data('popover-remote'),
      success: function(response) {
        $('#' + div_id).html(response);
        $(element).attr("data-loaded", true);
        $(element).attr("data-content", response);
        return $(element).popover('update');
      }
    });
    return '<div id="' + div_id + '">Loading...</div>';
  } else {
    return $(element).data('content');
  }
};

$('[data-popover-remote]').popover({
  html: true,
  trigger: 'hover',
  content: function() {
    return popoverRemoteContents(this);
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<span data-popover-remote="http://example.com/">Remote Popover test with caching</span>