问:
Get querysnapshot docs length from Empty collection
I am fetching docs length from collection logs. It works absolutely fine if there are documents in the collection, but it doesnt give any response when collection is empty. I want it to return 0 or null in this case.

My code::

```<code>firebase.firestore().collection('logs')
.where("date" , "==" , show_year_month_date)
.get()
.then(querySnapshot => {
 querySnapshot.forEach(doc=> {
 console.log(doc.id, " => ", doc.data());
 alert(querySnapshot.docs.length); // It doesnt goes here if collection is empty
 console.log(querySnapshot.docs.length);

 if(querySnapshot.docs.length==null){
  console.log("its null"); // It doesnt goes here if collection is empty
}

 if(querySnapshot.docs.length>0){
   console.log("entry found");
 }
 if(!querySnapshot.docs.length){
   console.log("no entry");
   alert("no entry"); // It doesnt goes here if collection is empty
   this.sendLogs();
 }
});
})
.catch(function(error) {
   console.log("Error getting documents: ", error);
   alert("error no document found"); // It doesnt goes here if collection is empty
})

  }
</code>```

答:
The problem is that you only access the length inside the querySnapshot.forEach(doc => { statement. If there are no documents, the code inside that statement is never executed.

Any code that should run regardless of the documents should be outside of the querySnapshot.forEach(doc => { block. So for example:

```<code>firebase.firestore().collection('logs')
    .where("date", "==", show_year_month_date)
    .get()
    .then(querySnapshot => {
        alert(querySnapshot.docs.length);
        console.log(querySnapshot.docs.length);

        if (querySnapshot.docs.length == null) {
            console.log("its null"); // It doesnt goes here if collection is empty
        }

        if (querySnapshot.docs.length > 0) {
            console.log("entry found");
        }
        if (!querySnapshot.docs.length) {
            console.log("no entry");
            alert("no entry"); // It doesnt goes here if collection is empty
            this.sendLogs();
        }

        querySnapshot.forEach(doc => {
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
        alert("error no document found"); // It doesnt goes here if collection is empty
    })
}
</code>```

Now the only code that is inside the querySnapshot.forEach(doc => { block is the code that prints the document ids, which is also the only code that actually needs the document data.

Body:
I am fetching docs length from collection logs. It works absolutely fine if there are documents in the collection, but it doesnt give any response when collection is empty. I want it to return 0 or null in this case.

My code::

firebase.firestore().collection('logs')
.where("date" , "==" , show_year_month_date)
.get()
.then(querySnapshot => {
 querySnapshot.forEach(doc=> {
 console.log(doc.id, " => ", doc.data());
 alert(querySnapshot.docs.length); // It doesnt goes here if collection is empty
 console.log(querySnapshot.docs.length);

 if(querySnapshot.docs.length==null){
  console.log("its null"); // It doesnt goes here if collection is empty
}

 if(querySnapshot.docs.length>0){
   console.log("entry found");
 }
 if(!querySnapshot.docs.length){
   console.log("no entry");
   alert("no entry"); // It doesnt goes here if collection is empty
   this.sendLogs();
 }
});
})
.catch(function(error) {
   console.log("Error getting documents: ", error);
   alert("error no document found"); // It doesnt goes here if collection is empty
})

  }

Body:
The problem is that you only access the length inside the querySnapshot.forEach(doc => { statement. If there are no documents, the code inside that statement is never executed.

Any code that should run regardless of the documents should be outside of the querySnapshot.forEach(doc => { block. So for example:

firebase.firestore().collection('logs')
    .where("date", "==", show_year_month_date)
    .get()
    .then(querySnapshot => {
        alert(querySnapshot.docs.length);
        console.log(querySnapshot.docs.length);

        if (querySnapshot.docs.length == null) {
            console.log("its null"); // It doesnt goes here if collection is empty
        }

        if (querySnapshot.docs.length > 0) {
            console.log("entry found");
        }
        if (!querySnapshot.docs.length) {
            console.log("no entry");
            alert("no entry"); // It doesnt goes here if collection is empty
            this.sendLogs();
        }

        querySnapshot.forEach(doc => {
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
        alert("error no document found"); // It doesnt goes here if collection is empty
    })
}

Now the only code that is inside the querySnapshot.forEach(doc => { block is the code that prints the document ids, which is also the only code that actually needs the document data.


来源: stackexchange

问:
How to have text and image in same row using CSS Flexbox?
I have projects on my personal portfolio and I want each row of a grid to have an image pushed to the left or right (odd or even row) with a paragraph description on the opposite side. Basically I want a paragraph and image in-line with each other on the same row. When I do it, the text is above the image, which I do not want. The HTML code is the beginning of the "Projects" section

.project-box {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  margin-bottom: 60px;
  transition: .5s ease;
}

.odd {
  display: flex;
  justify-content: flex-end;
}

.even {
  display: flex;
  justify-content: flex-start;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row odd">
    <p class="project-decription">Lorem ipsum dolor sit amet consectetur adipisicing elit. Veritatis, similique consequatur expedita natus voluptatum non sint ea vero dignissimos eius. Eos animi, praesentium odit mollitia provident totam repudiandae sapiente cumque. Lorem ipsum, dolor
      sit amet consectetur adipisicing elit. Similique qui, quam dolorem aperiam perferendis minus iure veniam voluptatum molestias, sed non ea obcaecati nemo nisi amet dignissimos illo autem! Aliquam.</p>
    <div class="project-box col-lg-4 col-md-6 col-sm-12">
      <img src="img/whatfoodisthere.png" class="project-image" alt="Project 1">
      <div class="middle">

          <div class="text">
            Visit Site
          </div>

      </div>
      <span class="project-name">Recipe Library</span>
    </div>
  </div></code>```

答: It's cuz you're using the row class from bootstrap. If you remove it, they will be in the same line</p>

ContentLicense: CC BY-SA 4.0

Body:
I have projects on my personal portfolio and I want each row of a grid to have an image pushed to the left or right (odd or even row) with a paragraph description on the opposite side. Basically I want a paragraph and image in-line with each other on the same row. When I do it, the text is above the image, which I do not want. The HTML code is the beginning of the "Projects" section

.project-box {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  margin-bottom: 60px;
  transition: .5s ease;
}

.odd {
  display: flex;
  justify-content: flex-end;
}

.even {
  display: flex;
  justify-content: flex-start;
}

Lorem ipsum dolor sit amet consectetur adipisicing elit. Veritatis, similique consequatur expedita natus voluptatum non sint ea vero dignissimos eius. Eos animi, praesentium odit mollitia provident totam repudiandae sapiente cumque. Lorem ipsum, dolor
      sit amet consectetur adipisicing elit. Similique qui, quam dolorem aperiam perferendis minus iure veniam voluptatum molestias, sed non ea obcaecati nemo nisi amet dignissimos illo autem! Aliquam.

            Visit Site

      Recipe Library


问:
unsupported operand type(s) for +: 'int' and 'Entry'
I get that z is an Entry and that 5 is an integer but I don't know how to change z to be an integer that the user could enter.

This is my code:

```<code>import smtplib
from tkinter import *

window = Tk()

z = Entry(window, width=35, bg="white")
z.grid(row=5, column=2, sticky=W)

def click():
    global YOUR_EMAIL_ADDRESS
    YOUR_EMAIL_ADDRESS=YOUR_EMAIL_ADDRESS.get()
    global YOUR_PASSWORD
    YOUR_PASSWORD=YOUR_PASSWORD.get()
    global TARGET_EMAIL
    TARGET_EMAIL=TARGET_EMAIL.get()
    global subject
    subject=subject.get()
    global msg
    msg=msg.get()
    global z
    z=z.get()

    send_email(subject, msg)

x = 5 + z
print(z)
</code>```

答:
In tkinter you have StringVar() and IntVar() for string and integer respectively. So here you need to use a keyword argument to Entry widget called Entry(.....,textvariable=my_var) and in tkinter you have to define the variable before using it, so here is your code and I have simplify your code if you have trouble understanding you can ask or just copy and use this.

```<code>import smtplib
from tkinter import *

window = Tk()

my_var = IntVar()
z = Entry(window, width=35, bg="white",textvariable=my_var)
z.grid(row=5, column=2, sticky=W)

def click():
    global YOUR_EMAIL_ADDRESS , YOUR_PASSWORD , TARGET_EMAIL , subject , msg

    YOUR_EMAIL_ADDRESS=YOUR_EMAIL_ADDRESS.get()

    YOUR_PASSWORD=YOUR_PASSWORD.get()

    TARGET_EMAIL=TARGET_EMAIL.get()

    subject=subject.get()

    msg=msg.get()

    send_email(subject, msg)

x = 5 + my_var.get()
print(my_var)
</code>```

Note that i removed your assignment of z = z.get() as it might be wrong to say so, instead you can do this too.
also, to get the value of a entrybox you can use z.get() which means you last line of code will be

```<code>x = 5 + int(z.get())
print(z.get())
</code>```

and I don't recommend using z = z.get() as you already have a z outside your function. Note that I'm using int() because in Python you cannot '+' a str and int.

Body:
I get that z is an Entry and that 5 is an integer but I don't know how to change z to be an integer that the user could enter.

This is my code:

import smtplib
from tkinter import *

window = Tk()

z = Entry(window, width=35, bg="white")
z.grid(row=5, column=2, sticky=W)

def click():
    global YOUR_EMAIL_ADDRESS
    YOUR_EMAIL_ADDRESS=YOUR_EMAIL_ADDRESS.get()
    global YOUR_PASSWORD
    YOUR_PASSWORD=YOUR_PASSWORD.get()
    global TARGET_EMAIL
    TARGET_EMAIL=TARGET_EMAIL.get()
    global subject
    subject=subject.get()
    global msg
    msg=msg.get()
    global z
    z=z.get()

    send_email(subject, msg)

x = 5 + z
print(z)

Body:
In tkinter you have StringVar() and IntVar() for string and integer respectively. So here you need to use a keyword argument to Entry widget called Entry(.....,textvariable=my_var) and in tkinter you have to define the variable before using it, so here is your code and I have simplify your code if you have trouble understanding you can ask or just copy and use this.

import smtplib
from tkinter import *

window = Tk()

my_var = IntVar()
z = Entry(window, width=35, bg="white",textvariable=my_var)
z.grid(row=5, column=2, sticky=W)

def click():
    global YOUR_EMAIL_ADDRESS , YOUR_PASSWORD , TARGET_EMAIL , subject , msg

    YOUR_EMAIL_ADDRESS=YOUR_EMAIL_ADDRESS.get()

    YOUR_PASSWORD=YOUR_PASSWORD.get()

    TARGET_EMAIL=TARGET_EMAIL.get()

    subject=subject.get()

    msg=msg.get()

    send_email(subject, msg)

x = 5 + my_var.get()
print(my_var)

Note that i removed your assignment of z = z.get() as it might be wrong to say so, instead you can do this too.
also, to get the value of a entrybox you can use z.get() which means you last line of code will be

x = 5 + int(z.get())
print(z.get())

and I don't recommend using z = z.get() as you already have a z outside your function. Note that I'm using int() because in Python you cannot '+' a str and int.


问:
Go towards or away from the model in mobile
From the code on my previous answer, I get a WebVR page that works fine in Desktop but in the mobile phone I'm not able to go closer to the model (looks more like a skybox).

Would like to be able to go towards / away from the model (using two fingers going, respectively, away from each other or closer), apart from looking around.

After some searching, found an example of where this functionality I look for is used.

How can I get that same mobile functionality working for my case?

答:
1) Orbit controls

If you want your experience to revolve around a model, moving the camera around it, and zooming in and out - I'd say the orbit controls are exacly what You're looking for:

```<code><a-entity camera look-controls
          orbit-controls="target: 0 1.6 -0.5; initialPosition: 0 5 15"></a-entity>
</code>```

The camera will move around the defined target. Works with mobile touch events.
Check it out with gltf models here.

2) Moving the camera with pinching

If you want to move the camera towars or away the direction it's looking at, as far as i know, You'll have to implement such behavior in a custom component. A poor mans version could look a bit like this:

```<code>AFRAME.registerComponent('pinch-controls', {
  init: function() {
    // moveCamera uses variables from 'this' scope
    this.moveCamera.bind(this);

    // we'll use this to get the 'pinch direction'
    this.distance = 0;
    // we'll keep here the camera's current direction
    this.direction = new THREE.Vector3();
    // camera entity reference
    this.camera = document.querySelector("[camera]");

    // listeners
    document.body.addEventListener('touchstart', event => {
      // we're interested only in two - finger pinches
      if (event.touches.length != 2) return 0;
      // calculate the distance
      this.distance = this.calculatePinchDistance(event);
      // we don't want the touch to rotate the camera around
      this.el.setAttribute('look-controls', 'touchEnabled', false);
    }, false);

    document.body.addEventListener('touchend', event => {
      // when the pinch ends - restore the look-controls
      if (event.touches.length != 1) this.el.setAttribute('look-controls', 'touchEnabled', true);
    }, false);

    document.body.addEventListener('touchmove', event => {
      // we're interested only in two - finger pinches
      if (event.touches.length != 2) return 0;

      // compare the distances to determine which direction should we move
      var distance = this.calculatePinchDistance(event);
      let speed = (distance < this.distance) ? -0.2 : 0.2;
      this.moveCamera(speed);

      // keep the distance for the next callback
      this.distance = distance;
    }, false);
  },
  calculatePinchDistance(event) {
      var dx = event.touches[0].pageX - event.touches[1].pageX;
      var dy = event.touches[0].pageY - event.touches[1].pageY;
      return Math.sqrt(dx * dx + dy * dy);
  },
  moveCamera: function(speed) {
        // get the camera direction, and multiply it by the desired 'speed'
        this.el.sceneEl.camera.getWorldDirection(this.direction);
        this.direction.multiplyScalar(speed);
        // apply the change to the actual position
        var pos = this.el.getAttribute("position");
        pos.add(this.direction);
        this.el.setAttribute("position", pos);
    }
}

// HTML
// <a-entity camera look-controls pinch-controls></a-entity>
</code>```

Check it out here

If you want to move the camera towards the model (instead of the direction it's facing), you can just replace extracting the camera direction (in moveCamera) with calculating the camera <-> model direction:

```<code>// instead of
// this.el.sceneEl.camera.getWorldDirection(this.direction);
// grab the direction towards the model
this.direction.copy(this.el.object3D.position)
this.direction.add(modelReference.object3D.position)
this.direction.normalize();
// (...)
</code>```

Tiago edit:

The final code used was

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Octant Cube - by Dodds, H. & Peres, T.</title>
    <meta name="description" content="Present in the Taxonomy article">
        <script src="https://kit.fontawesome.com/c9500776a0.js" crossorigin="anonymous"></script>
    <script src="misc/codeBtn.js"></script>
    <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
    <script src="https://unpkg.com/aframe-orbit-controls@1.2.0/dist/aframe-orbit-controls.min.js"></script>
    <script src="https://unpkg.com/aframe-supercraft-loader@1.1.3/dist/aframe-supercraft-loader.js"></script>
    <style>
    #toggleBtn {
        position: fixed;
        z-index: 9999;
        margin: 25px;
        font-size: 3em;
        color: rgb(128, 0, 128);
        cursor: pointer;
    }

    #toggleBtn:hover {
        color: rgba(128, 0, 128, 0.6);
    }
    </style>
    <script>
    // Models swap component
    AFRAME.registerComponent('content-manager', {
        init: function() {
            const btn = document.querySelector("#toggleBtn")
            const castle = document.querySelector("#castle")
            const fish = document.querySelector("#fish")

            btn.addEventListener("click", e => {
                if (castle.getAttribute("visible")) {
                    castle.emit("fadeOut")
                    btn.classList.remove("fa-fish")
                    btn.classList.add("fa-landmark")
                } else {
                    fish.emit("fadeOut")
                    btn.classList.remove("fa-landmark")
                    btn.classList.add("fa-fish")
                }
            })
            fish.addEventListener('animationcomplete__fadeout', e => {
                fish.setAttribute("visible", "false")
                castle.setAttribute("visible", "true")
                castle.emit("fadeIn")
            })
            castle.addEventListener('animationcomplete__fadeout', e => {
                castle.setAttribute("visible", "false")
                fish.setAttribute("visible", "true")
                fish.emit("fadeIn")
            })
        }
    })

    // move the camera on pinching
    AFRAME.registerComponent('pinch-controls', {
        init: function() {
            // bind the methods that use the scope variables
            this.moveCamera.bind(this);

            // use this to keep track whether the user is moving forward or backwards
            this.distance = 0;
            // store the camera direction here
            this.direction = new THREE.Vector3();
            // camera entity reference
            this.camera = document.querySelector("[camera]");

            document.body.addEventListener('touchstart', event => {
                // react only on two finger pinches
                if (event.touches.length != 2) return 0;

                this.distance = this.calculatePinchDistance(event);
                // prevent the look controls to rotate the camera while pinching
                this.el.setAttribute('look-controls', 'touchEnabled', false);
            }, false);

            document.body.addEventListener('touchend', event => {
                // restore the look-controls
                if (event.touches.length != 1) this.el.setAttribute('look-controls', 'touchEnabled', true)
            }, false);
            document.body.addEventListener('wheel', e => {
                this.moveCamera(e.deltaY < 0 ? -0.2 : 0.2);
            })
            document.body.addEventListener('touchmove', event => {
                // we're interested only in pinching
                if (event.touches.length != 2) return 0;

                // calculate the pinch difference and move the camera
                var distance = this.calculatePinchDistance(event);
                let multiplier = (distance < this.distance) ? -0.2 : 0.2;;
                if (!isNaN(multiplier)) this.moveCamera(multiplier);

                // for later use
                this.distance = distance;
            }, false);
        },
        calculatePinchDistance: function(mouseEvent) {
            var dx = event.touches[0].pageX - event.touches[1].pageX;
            var dy = event.touches[0].pageY - event.touches[1].pageY;
            return Math.sqrt(dx * dx + dy * dy);
        },
        moveCamera: function(speed) {
            this.el.sceneEl.camera.getWorldDirection(this.direction);
            this.direction.multiplyScalar(speed);
            var pos = this.el.getAttribute("position");
            pos.add(this.direction);
            this.el.setAttribute("position", pos)
        }
    })
    </script>
  </head>
  <body>
    <a-scene background="color: #FAFAFA">
      <a-assets>
        <a-asset-item id="octant" src="octant.glb"></a-asset-item>
      </a-assets>
      <a-entity position="0 0.347 -4" rotation="0 60 -1"  gltf-model="#octant"  scale="5 5 5" animation__fadeIn="property: scale; dur: 150; from: 0.001 0.001 0.001; to: 0.5 0.5 0.5; easing: easeInQuad; startEvents: fadeIn" animation__fadeOut="property: scale; dur: 150; from: 0.5 0.5 0.5; to: 0.001 0.001 0.001; easing: easeInQuad; startEvents: fadeOut"></a-entity>
      <a-entity camera look-controls
          orbit-controls="target: 0 1.6 -0.5; initialPosition: 0 5 15"></a-entity>
    </a-scene>
  </body>
</html>
</code>```

And this was the final result

Body:
1) Orbit controls

If you want your experience to revolve around a model, moving the camera around it, and zooming in and out - I'd say the orbit controls are exacly what You're looking for:

<a-entity camera look-controls
          orbit-controls="target: 0 1.6 -0.5; initialPosition: 0 5 15"></a-entity>

The camera will move around the defined target. Works with mobile touch events.
Check it out with gltf models here.

2) Moving the camera with pinching

If you want to move the camera towars or away the direction it's looking at, as far as i know, You'll have to implement such behavior in a custom component. A poor mans version could look a bit like this:

AFRAME.registerComponent('pinch-controls', {
  init: function() {
    // moveCamera uses variables from 'this' scope
    this.moveCamera.bind(this);

    // we'll use this to get the 'pinch direction'
    this.distance = 0;
    // we'll keep here the camera's current direction
    this.direction = new THREE.Vector3();
    // camera entity reference
    this.camera = document.querySelector("[camera]");

    // listeners
    document.body.addEventListener('touchstart', event => {
      // we're interested only in two - finger pinches
      if (event.touches.length != 2) return 0;
      // calculate the distance
      this.distance = this.calculatePinchDistance(event);
      // we don't want the touch to rotate the camera around
      this.el.setAttribute('look-controls', 'touchEnabled', false);
    }, false);

    document.body.addEventListener('touchend', event => {
      // when the pinch ends - restore the look-controls
      if (event.touches.length != 1) this.el.setAttribute('look-controls', 'touchEnabled', true);
    }, false);

    document.body.addEventListener('touchmove', event => {
      // we're interested only in two - finger pinches
      if (event.touches.length != 2) return 0;

      // compare the distances to determine which direction should we move
      var distance = this.calculatePinchDistance(event);
      let speed = (distance < this.distance) ? -0.2 : 0.2;
      this.moveCamera(speed);

      // keep the distance for the next callback
      this.distance = distance;
    }, false);
  },
  calculatePinchDistance(event) {
      var dx = event.touches[0].pageX - event.touches[1].pageX;
      var dy = event.touches[0].pageY - event.touches[1].pageY;
      return Math.sqrt(dx * dx + dy * dy);
  },
  moveCamera: function(speed) {
        // get the camera direction, and multiply it by the desired 'speed'
        this.el.sceneEl.camera.getWorldDirection(this.direction);
        this.direction.multiplyScalar(speed);
        // apply the change to the actual position
        var pos = this.el.getAttribute("position");
        pos.add(this.direction);
        this.el.setAttribute("position", pos);
    }
}

// HTML
// <a-entity camera look-controls pinch-controls></a-entity>

Check it out here

If you want to move the camera towards the model (instead of the direction it's facing), you can just replace extracting the camera direction (in moveCamera) with calculating the camera <-> model direction:

// instead of
// this.el.sceneEl.camera.getWorldDirection(this.direction);
// grab the direction towards the model
this.direction.copy(this.el.object3D.position)
this.direction.add(modelReference.object3D.position)
this.direction.normalize();
// (...)

Tiago edit:

The final code used was

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Octant Cube - by Dodds, H. & Peres, T.</title>
    <meta name="description" content="Present in the Taxonomy article">
        <script src="https://kit.fontawesome.com/c9500776a0.js" crossorigin="anonymous"></script>
    <script src="misc/codeBtn.js"></script>
    <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
    <script src="https://unpkg.com/aframe-orbit-controls@1.2.0/dist/aframe-orbit-controls.min.js"></script>
    <script src="https://unpkg.com/aframe-supercraft-loader@1.1.3/dist/aframe-supercraft-loader.js"></script>
    <style>
    #toggleBtn {
        position: fixed;
        z-index: 9999;
        margin: 25px;
        font-size: 3em;
        color: rgb(128, 0, 128);
        cursor: pointer;
    }

    #toggleBtn:hover {
        color: rgba(128, 0, 128, 0.6);
    }
    </style>
    <script>
    // Models swap component
    AFRAME.registerComponent('content-manager', {
        init: function() {
            const btn = document.querySelector("#toggleBtn")
            const castle = document.querySelector("#castle")
            const fish = document.querySelector("#fish")

            btn.addEventListener("click", e => {
                if (castle.getAttribute("visible")) {
                    castle.emit("fadeOut")
                    btn.classList.remove("fa-fish")
                    btn.classList.add("fa-landmark")
                } else {
                    fish.emit("fadeOut")
                    btn.classList.remove("fa-landmark")
                    btn.classList.add("fa-fish")
                }
            })
            fish.addEventListener('animationcomplete__fadeout', e => {
                fish.setAttribute("visible", "false")
                castle.setAttribute("visible", "true")
                castle.emit("fadeIn")
            })
            castle.addEventListener('animationcomplete__fadeout', e => {
                castle.setAttribute("visible", "false")
                fish.setAttribute("visible", "true")
                fish.emit("fadeIn")
            })
        }
    })

    // move the camera on pinching
    AFRAME.registerComponent('pinch-controls', {
        init: function() {
            // bind the methods that use the scope variables
            this.moveCamera.bind(this);

            // use this to keep track whether the user is moving forward or backwards
            this.distance = 0;
            // store the camera direction here
            this.direction = new THREE.Vector3();
            // camera entity reference
            this.camera = document.querySelector("[camera]");

            document.body.addEventListener('touchstart', event => {
                // react only on two finger pinches
                if (event.touches.length != 2) return 0;

                this.distance = this.calculatePinchDistance(event);
                // prevent the look controls to rotate the camera while pinching
                this.el.setAttribute('look-controls', 'touchEnabled', false);
            }, false);

            document.body.addEventListener('touchend', event => {
                // restore the look-controls
                if (event.touches.length != 1) this.el.setAttribute('look-controls', 'touchEnabled', true)
            }, false);
            document.body.addEventListener('wheel', e => {
                this.moveCamera(e.deltaY < 0 ? -0.2 : 0.2);
            })
            document.body.addEventListener('touchmove', event => {
                // we're interested only in pinching
                if (event.touches.length != 2) return 0;

                // calculate the pinch difference and move the camera
                var distance = this.calculatePinchDistance(event);
                let multiplier = (distance < this.distance) ? -0.2 : 0.2;;
                if (!isNaN(multiplier)) this.moveCamera(multiplier);

                // for later use
                this.distance = distance;
            }, false);
        },
        calculatePinchDistance: function(mouseEvent) {
            var dx = event.touches[0].pageX - event.touches[1].pageX;
            var dy = event.touches[0].pageY - event.touches[1].pageY;
            return Math.sqrt(dx * dx + dy * dy);
        },
        moveCamera: function(speed) {
            this.el.sceneEl.camera.getWorldDirection(this.direction);
            this.direction.multiplyScalar(speed);
            var pos = this.el.getAttribute("position");
            pos.add(this.direction);
            this.el.setAttribute("position", pos)
        }
    })
    </script>
  </head>
  <body>
    <a-scene background="color: #FAFAFA">
      <a-assets>
        <a-asset-item id="octant" src="octant.glb"></a-asset-item>
      </a-assets>
      <a-entity position="0 0.347 -4" rotation="0 60 -1"  gltf-model="#octant"  scale="5 5 5" animation__fadeIn="property: scale; dur: 150; from: 0.001 0.001 0.001; to: 0.5 0.5 0.5; easing: easeInQuad; startEvents: fadeIn" animation__fadeOut="property: scale; dur: 150; from: 0.5 0.5 0.5; to: 0.001 0.001 0.001; easing: easeInQuad; startEvents: fadeOut"></a-entity>
      <a-entity camera look-controls
          orbit-controls="target: 0 1.6 -0.5; initialPosition: 0 5 15"></a-entity>
    </a-scene>
  </body>
</html>

And this was the final result


问:
Dynamically set property name of JavaScript object inside a function
I'm learning to build APIs with Express. I figured that every time I have to send a successful JSON response, I have to duplicate most of the code. So I tried to put it in a function like so in one of my controller modules:

```<code>const successResponse = (res, statusCode, obj, coll = false) => {
  const successObj = { status: "success" };
  if (coll) successObj.results = obj.length;
  successObj.data = { obj };
  return res.status(statusCode).json(successObj);
};

exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
  const player = await Player.findById(req.params.id);
  if (!player) return next(new AppError("Player not found", 404));

  successResponse(res, 200, player);
}
</code>```

The problem is in the line successObj.data = { obj } where I want the result to be the name of the argument that is passed as key and the object as value(s). The result I currently get is:

```<code>{
    "status": "success",
    "data": {
        "obj": { // I want this key to be "player" here
            "name": "Sal"
        }
    }
}
</code>```

As the comment says I would like the key to be the string that I passed as the object name. I can do it by passing another argument as a string but it will always be the same as the object name that I pass. Is there a better way to do this?

答:
You are getting a single object and trying to use that as key and value. You can try something like this:

Suppose your obj is

```<code>var obj = { player: {
            "name": "Sal"
        }}
</code>```

then while pushing to data you can follow these steps:

```<code>var selectedKey = Object.keys(obj)[0]; // assuming you will have a single key, if you have multiple then select based on the index

var selectedKeyData = Object.values(obj)[0];

var data = {};
data[selectedKey] = selectedKeyData;

</code>```

Now, your data will have desired result.

Body:
I'm learning to build APIs with Express. I figured that every time I have to send a successful JSON response, I have to duplicate most of the code. So I tried to put it in a function like so in one of my controller modules:

const successResponse = (res, statusCode, obj, coll = false) => {
  const successObj = { status: "success" };
  if (coll) successObj.results = obj.length;
  successObj.data = { obj };
  return res.status(statusCode).json(successObj);
};

exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
  const player = await Player.findById(req.params.id);
  if (!player) return next(new AppError("Player not found", 404));

  successResponse(res, 200, player);
}

The problem is in the line successObj.data = { obj } where I want the result to be the name of the argument that is passed as key and the object as value(s). The result I currently get is:

{
    "status": "success",
    "data": {
        "obj": { // I want this key to be "player" here
            "name": "Sal"
        }
    }
}

As the comment says I would like the key to be the string that I passed as the object name. I can do it by passing another argument as a string but it will always be the same as the object name that I pass. Is there a better way to do this?

Body:
You are getting a single object and trying to use that as key and value. You can try something like this:

Suppose your obj is

var obj = { player: {
            "name": "Sal"
        }}

then while pushing to data you can follow these steps:

var selectedKey = Object.keys(obj)[0]; // assuming you will have a single key, if you have multiple then select based on the index

var selectedKeyData = Object.values(obj)[0];

var data = {};
data[selectedKey] = selectedKeyData;

Now, your data will have desired result.


问:
How to make cells in UITableView not turn blue?
I am using a UITableView and the cells I am using in this view should do nothing when I click them. I can't turn off UserInteraction though because then I am not able to click on the accessory (detailDisclosureButton). So how can I make them stop turning blue and still allow them to click on the accessory?</p>

答: By default, the selectionStyle property of cell is UITableViewCellSelectionStyleBlue. Change it to UITableViewCellSelectionStyleNone.

ContentLicense: CC BY-SA 3.0


问:
How to wait for findit result?
Hi I am using the library findit to recursively search a directory tree for a file. I am able to find the file, but how do I wait for the search to be done before trying to do something with the file? Right now I have:

```<code>var path = require('path');
var finder = require('findit')(project_root_dir);
finder.on('file', function (file, stat) {
        if (path.basename(file) == 'file_im_looking_for.json') {
          stop()  // found it
          console.log('FOUND IT');
          console.log(file);
          console.log(path.basename(file));
          found_file = file;
        }
      });
// Now I want to do some stuff with found_file
</code>```

my Issue is that it takes some time for findit to run, and so my code that references found_file later on is usually dealing with an undefined value instead of the filepath string I desire. How can I wait for the finder.on() method to finish before using my found_file variable?

答:
Promise is what you need. Try this code:

(async () => {
  var search = new Promise((resolve, reject) => {
     var finder = require('findit')(project_root_dir);
     finder.on('file', function (file, stat) {
        if (path.basename(file) == 'file_im_looking_for.json') {
          stop()  // found it
          console.log('FOUND IT');
          console.log(file);
          console.log(path.basename(file));
          resolve(file)
        }
      });
     finder.on('error', reject);
  });
  var found_file = await search;
  // do some stuff with found_file
})()
```

Title: How to wait for findit result?

Body:
Hi I am using the library findit to recursively search a directory tree for a file. I am able to find the file, but how do I wait for the search to be done before trying to do something with the file? Right now I have:

var path = require('path');
var finder = require('findit')(project_root_dir);
finder.on('file', function (file, stat) {
        if (path.basename(file) == 'file_im_looking_for.json') {
          stop()  // found it
          console.log('FOUND IT');
          console.log(file);
          console.log(path.basename(file));
          found_file = file;
        }
      });
// Now I want to do some stuff with found_file

my Issue is that it takes some time for findit to run, and so my code that references found_file later on is usually dealing with an undefined value instead of the filepath string I desire. How can I wait for the finder.on() method to finish before using my found_file variable?


问:
In Android how to run the background service?
Can you pls tell what mistake i did in the code for running the BackGround Service.Is Any other code Available for running the BackGround Service.
Is the below Procedure correct.... How to run the background service in android ?

```<code>FrontEnd.java:
*****************

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class FrontEnd extends Activity implements OnClickListener {

    private Button btnStartService, btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frontend);

        bindComponents();
        addListener();
        init();
    }

    private void bindComponents() {
        btnStartService = (Button)findViewById(R.id.btnStartService);
        btnStopService = (Button)findViewById(R.id.btnStopService);
    }

    private void addListener() {
        btnStartService.setOnClickListener(this);
        btnStopService.setOnClickListener(this);
    }

    private void init() {

    }

    public void onClick(View view) {
        Intent mIntent = new Intent(this,BackEndService.class);
        System.out.println("------------------------>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<");
        switch (view.getId()) {
        case R.id.btnStartService:
            startService(mIntent);
            break;
        case R.id.btnStopService:
            stopService(mIntent);
            break;
        default:
            break;
        }
    }
}

******************************************************************************************************************

BackEndService.java
*********************

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BackEndService extends Service{

    private static final String tag = "Panacea";

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(tag, "onBind");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d(tag, "onCreate");

        Notification notification = new Notification(R.drawable.launcher, getText(R.string.app_name),
                System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, GmaTestApp01Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, "BackGround Service", "Project is running", pendingIntent);
        startForeground(1, notification);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d(tag, "onStart startId=" + startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(tag, "onStartCommand startId=" + startId);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(tag, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(tag, "onDestroy");
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }
}

*******************************************************************************************************************
frontend.xml
***************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical"
   >

    <Button
        android:id="@+id/btnStartService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/start_service"
         />

    <Button
        android:id="@+id/btnStopService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/stop_service" />

</LinearLayout>
</code>```

Update:

```<code>import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Home extends Activity
{

    Integer[] imageIDs = {
            R.drawable.a,
            R.drawable.b,
            R.drawable.c,
            R.drawable.d,
            R.drawable.e,
            R.drawable.f,
            R.drawable.g,
            R.drawable.h,
            R.drawable.i,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(this));

        gridView.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent,
            View v, int position, long id)
            {
                /*Toast.makeText(getBaseContext(),
                        "pic" + (position + 1) + " selected",
                        Toast.LENGTH_SHORT).show();*/
                int pos= position + 1;

                if(pos == 1)
                {
                     Intent intent = new Intent("com.project.GmaTestApp01Activity");
                     startActivity(intent);
                }
                else if(pos == 2)
                {
                     Intent intent = new Intent("com.project.FrontEnd");
                     startActivity(intent);
                }
                else if(pos == 9)
                {
                    Intent intent = new Intent("com.project.UserProfile");
                    startActivity(intent);
                }
                else
                {
                    Toast.makeText(getBaseContext(),"Coming Soon!", Toast.LENGTH_SHORT).show();
                }

            }
        });

        gridView.setOnTouchListener(new OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_MOVE){
                    return true;
                }
                return false;
            }

        });
    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;

        public ImageAdapter(Context c)
        {
            context = c;
        }

        //---returns the number of images---
        public int getCount() {
            return imageIDs.length;
        }

        //---returns the ID of an item---
        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(5, 5, 5, 5);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(imageIDs[position]);
            return imageView;
        }
    }
}
</code>```

答: Running background service without notification would not work since Android 8.</p>

Body:
Can you pls tell what mistake i did in the code for running the BackGround Service.Is Any other code Available for running the BackGround Service.
Is the below Procedure correct.... How to run the background service in android ?

FrontEnd.java:
*****************

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class FrontEnd extends Activity implements OnClickListener {

    private Button btnStartService, btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frontend);

        bindComponents();
        addListener();
        init();
    }

    private void bindComponents() {
        btnStartService = (Button)findViewById(R.id.btnStartService);
        btnStopService = (Button)findViewById(R.id.btnStopService);
    }

    private void addListener() {
        btnStartService.setOnClickListener(this);
        btnStopService.setOnClickListener(this);
    }

    private void init() {

    }

    public void onClick(View view) {
        Intent mIntent = new Intent(this,BackEndService.class);
        System.out.println("------------------------>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<");
        switch (view.getId()) {
        case R.id.btnStartService:
            startService(mIntent);
            break;
        case R.id.btnStopService:
            stopService(mIntent);
            break;
        default:
            break;
        }
    }
}

******************************************************************************************************************

BackEndService.java
*********************

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BackEndService extends Service{

    private static final String tag = "Panacea";

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(tag, "onBind");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d(tag, "onCreate");

        Notification notification = new Notification(R.drawable.launcher, getText(R.string.app_name),
                System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, GmaTestApp01Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, "BackGround Service", "Project is running", pendingIntent);
        startForeground(1, notification);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d(tag, "onStart startId=" + startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(tag, "onStartCommand startId=" + startId);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(tag, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(tag, "onDestroy");
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }
}

*******************************************************************************************************************
frontend.xml
***************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical"
   >

    <Button
        android:id="@+id/btnStartService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/start_service"
         />

    <Button
        android:id="@+id/btnStopService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/stop_service" />

</LinearLayout>

Update:

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Home extends Activity
{

    Integer[] imageIDs = {
            R.drawable.a,
            R.drawable.b,
            R.drawable.c,
            R.drawable.d,
            R.drawable.e,
            R.drawable.f,
            R.drawable.g,
            R.drawable.h,
            R.drawable.i,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(this));

        gridView.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent,
            View v, int position, long id)
            {
                /*Toast.makeText(getBaseContext(),
                        "pic" + (position + 1) + " selected",
                        Toast.LENGTH_SHORT).show();*/
                int pos= position + 1;

                if(pos == 1)
                {
                     Intent intent = new Intent("com.project.GmaTestApp01Activity");
                     startActivity(intent);
                }
                else if(pos == 2)
                {
                     Intent intent = new Intent("com.project.FrontEnd");
                     startActivity(intent);
                }
                else if(pos == 9)
                {
                    Intent intent = new Intent("com.project.UserProfile");
                    startActivity(intent);
                }
                else
                {
                    Toast.makeText(getBaseContext(),"Coming Soon!", Toast.LENGTH_SHORT).show();
                }

            }
        });

        gridView.setOnTouchListener(new OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_MOVE){
                    return true;
                }
                return false;
            }

        });
    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;

        public ImageAdapter(Context c)
        {
            context = c;
        }

        //---returns the number of images---
        public int getCount() {
            return imageIDs.length;
        }

        //---returns the ID of an item---
        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(5, 5, 5, 5);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(imageIDs[position]);
            return imageView;
        }
    }
}


问:
Showing list of items including item details on same page in Django
In a Django v3.x app I would like to display a list of uploaded file names (e.g. images) in the left hand side of the screen. When a user clicks on one of those, I'd like to display the actual file/image on the right hand side of the screen. I am still new to Django and have used both ListView and DetailView separately, but not in such a combination. I'm not sure how this can be achieved.

Using a little Bootstrap magic, I can create a split screen easily. Hence, my template would look somehow like this:

```<code><div class="row">
  <div class="col-md-5 left">
  {% for image in images %}
     <div class="card">
       <h4>{{ image.url }}</h4>
       <a href="{{ image.url }}">View</a>
     </div>
  {% endfor %}
  </div>
  <div class="col-md-5 right">
    {# TODO: When the user clicks on the View url above, then I'd
    like to load the actual image here on the right hand side of the
    screen inside this div-tag. #}
  </div>
</div>
</code>```

Question 1: How can I achieve loading a selected image from a list? Can I still use ListView and DetailView, or do I need to write my own View logic?

Question 2: Ideally, I'd like to NOT re-send the whole page from the server to the client, because the list of images in the lefthand-side could potentially be long and require pagination. So, when the user clicks View, then, ideally, I'd like to load only the document from the server. Is this somehow feasible?

答: basically you want to show the selected item from the list on the other side like a slideshow</p>

Body:
In a Django v3.x app I would like to display a list of uploaded file names (e.g. images) in the left hand side of the screen. When a user clicks on one of those, I'd like to display the actual file/image on the right hand side of the screen. I am still new to Django and have used both ListView and DetailView separately, but not in such a combination. I'm not sure how this can be achieved.

Using a little Bootstrap magic, I can create a split screen easily. Hence, my template would look somehow like this:

  {% for image in images %}

{{ image.url }}

       View

  {% endfor %}

    {# TODO: When the user clicks on the View url above, then I'd
    like to load the actual image here on the right hand side of the
    screen inside this div-tag. #}

Question 1: How can I achieve loading a selected image from a list? Can I still use ListView and DetailView, or do I need to write my own View logic?

Question 2: Ideally, I'd like to NOT re-send the whole page from the server to the client, because the list of images in the lefthand-side could potentially be long and require pagination. So, when the user clicks View, then, ideally, I'd like to load only the document from the server. Is this somehow feasible?


问:
How to extract text from a web page that requires logging in using python and beautiful soup?
i have to retrieve some text from a website called morningstar.com . To access that data i have to log in. Once i log in and provide the url  of the web page  ,  i get the HTML text of a normal user (not logged in).As a result am not able to accees that information . ANy solutions ?</p>

答:
BeautifulSoup is for parsing html once you've already fetched it.  You can fetch the html using any standard url fetching library.  I prefer curl, as you tagged your post, python's built-in urllib2 also works well.

If you're saying that after logging in the response html is the same as for those who are not logged in, I'm gonna guess that your login is failing for some reason.  If you are using urllib2, are are you making sure to store the cookie properly after your first login and then passing this cookie to urllib2 when you are sending the request for the data?

It would help if you posted the code you are using to make the two requests (the initial login, and the attempt to fetch the data).


问:
Why am I getting this ImportError trying import users model?
Have two files in the same directory level, application.py and models.py, the first contains the blueprints registres, initial login and index route and the secondary database models.

Models:

```<code># -*- coding: utf-8 -*-
from src.application import db
from flask_login import UserMixin

class Usuarios(db.Model,UserMixin):

    __tablename__ = 'usuarios'

    id = db.Column(db.Integer, primary_key=True)
    nome = db.Column(db.String(), index=True)
    usuario = db.Column(db.String(), index=True, unique=True)
    email = db.Column(db.String(), unique=True)
    senha = db.Column(db.String())
    stats = db.Column(db.Boolean())
    role = db.Column(db.String())
    foto = db.Column(db.String())
    artigos = db.relationship('Artigos',backref='usuario',uselist=False)

class Artigos(db.Model):

    __tablename__ = 'artigos'

    id = db.Column(db.Integer, primary_key=True)
    titulo = db.Column(db.String(), index=True)
    id_usuario = db.Column(db.Integer,db.ForeignKey('usuarios.id'))
    text = db.Column(db.Text())
    data = db.Column(db.DateTime())
    stats = db.Column(db.Boolean())
</code>```

Application:

```<code># coding: utf-8
from flask import Flask, url_for, redirect, render_template, request, abort, Blueprint, session, jsonify
from flask_login import LoginManager, logout_user, current_user, login_user, login_required
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import os

app = Flask(__name__)

app.secret_key = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://postgres:postgres@192.168.10.102:5432/ntest"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

#Flask_Login
login_manager = LoginManager()
login_manager.init_app(app)

#Flask_Alchmey e migrate
db = SQLAlchemy(app)
migrate = Migrate(app, db)

from src.models import Usuarios

....
</code>```

I have been facing this boring ImportError problem since I've decided to use ORM and migrate my database. Im not knowing to spplit this files or call theirs imports. Anyone can help or suggest something?

```<code>(test) C:\Users\PC\Desktop\Python\test\src>python application.py
Traceback (most recent call last):
  File "application.py", line 22, in <module>
    from src.models import Usuarios
  File "CC:\Users\PC\Desktop\Python\test\src\models.py", line 2, in <module>
    from src.application import db
  File "C:\Users\PC\Desktop\Python\test\src\application.py", line 22, in <module>
    from src.models import Usuarios
ImportError: cannot import name Usuarios
</code>```

答:
You have a circular import where application.py is importing from models.py, but models.py needs to import from application.py.

This is a common occurrence with flask. The typical solution is to use the application factory pattern.

Body:
Have two files in the same directory level, application.py and models.py, the first contains the blueprints registres, initial login and index route and the secondary database models.

Models:

# -*- coding: utf-8 -*-
from src.application import db
from flask_login import UserMixin

class Usuarios(db.Model,UserMixin):

    __tablename__ = 'usuarios'

    id = db.Column(db.Integer, primary_key=True)
    nome = db.Column(db.String(), index=True)
    usuario = db.Column(db.String(), index=True, unique=True)
    email = db.Column(db.String(), unique=True)
    senha = db.Column(db.String())
    stats = db.Column(db.Boolean())
    role = db.Column(db.String())
    foto = db.Column(db.String())
    artigos = db.relationship('Artigos',backref='usuario',uselist=False)

class Artigos(db.Model):

    __tablename__ = 'artigos'

    id = db.Column(db.Integer, primary_key=True)
    titulo = db.Column(db.String(), index=True)
    id_usuario = db.Column(db.Integer,db.ForeignKey('usuarios.id'))
    text = db.Column(db.Text())
    data = db.Column(db.DateTime())
    stats = db.Column(db.Boolean())

Application:

# coding: utf-8
from flask import Flask, url_for, redirect, render_template, request, abort, Blueprint, session, jsonify
from flask_login import LoginManager, logout_user, current_user, login_user, login_required
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import os

app = Flask(__name__)

app.secret_key = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://postgres:postgres@192.168.10.102:5432/ntest"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

#Flask_Login
login_manager = LoginManager()
login_manager.init_app(app)

#Flask_Alchmey e migrate
db = SQLAlchemy(app)
migrate = Migrate(app, db)

from src.models import Usuarios

....

I have been facing this boring ImportError problem since I've decided to use ORM and migrate my database. Im not knowing to spplit this files or call theirs imports. Anyone can help or suggest something?

(test) C:\Users\PC\Desktop\Python\test\src>python application.py
Traceback (most recent call last):
  File "application.py", line 22, in <module>
    from src.models import Usuarios
  File "CC:\Users\PC\Desktop\Python\test\src\models.py", line 2, in <module>
    from src.application import db
  File "C:\Users\PC\Desktop\Python\test\src\application.py", line 22, in <module>
    from src.models import Usuarios
ImportError: cannot import name Usuarios


问:
BotFramework Composer, getting 404 error on callback at the skill

Steps To Reproduce:

Step 1:

Create a bot using composer(v1.0.0 installed form DMG on mac), choosing Echo Bot template.

Step 2:

Clone echo skill sample from the current repo:
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/python/80.skills-simple-bot-to-bot

Step 3:

Run the skill locally.

Step 4:

Connect to skill:

The endpoint in the picture is with port 3980 but it sue to at the last attempts the main bot was served by the composer on current bot. The point is that I set the callback URL to be the URL on which the main bot is running.

Step 5:

Add skill to Unknown Intent Dialog, After the echo response:

The Error:

I relieve an error at the skill side. After debugging of the skill I found that the problem is at the callback which returns 404 error back to the skill on sending activity.

```<code>uring handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/victorvasiliev/PycharmProjects/BotBuilder-Samples/samples/python/80.skills-simple-bot-to-bot/echo-skill-bot/adapter_with_error_handler.py", line 71, in _send_eoc_to_parent
    await turn_context.send_activity(end_of_conversation)
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 170, in send_activity
    result = await self.send_activities([activity_or_text])
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 217, in send_activities
    return await self._emit(self._on_send_activities, output, logic())
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 295, in _emit
    return await logic
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 212, in logic
    responses = await self.adapter.send_activities(self, output)
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_framework_adapter.py", line 686, in send_activities
    raise error
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_framework_adapter.py", line 672, in send_activities
    activity.conversation.id, activity.reply_to_id, activity
  File "/usr/local/lib/python3.7/site-packages/botframework/connector/aio/operations_async/_conversations_operations_async.py", line 533, in reply_to_activity
    raise models.ErrorResponseException(self._deserialize, response)
botbuilder.schema._models_py3.ErrorResponseException: Operation returned an invalid status code 'Not Found'
</code>```

Did anybody faced the same issue?

答:
You can see in the documentation that your skill host endpoint needs to end with api/skills and not just api:

Select Skills from the Composer menu. In the Skills page, if your skill is remote, enter <ngrok address>/api/skills in the Skill Host Endpoint field. If your skill is local, you should enter localhost:port/api/skills in the Skill Host Endpoint field.

The skill host endpoint is used as the service URL in activities sent to the skill, which means it will be the base URI for any Conversations API methods the skill calls. If your skill tries to send requests to a non-existent URL then you should expect to get 404's. The Composer bot will be routing requests to routes starting with api/skills so that's what you should be putting in your service URL.

Body:
Steps To Reproduce:

Step 1:

Create a bot using composer(v1.0.0 installed form DMG on mac), choosing Echo Bot template.

Step 2:

Clone echo skill sample from the current repo:
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/python/80.skills-simple-bot-to-bot

Step 3:

Run the skill locally.

Step 4:

Connect to skill:

The endpoint in the picture is with port 3980 but it sue to at the last attempts the main bot was served by the composer on current bot. The point is that I set the callback URL to be the URL on which the main bot is running.

Step 5:

Add skill to Unknown Intent Dialog, After the echo response:

The Error:

I relieve an error at the skill side. After debugging of the skill I found that the problem is at the callback which returns 404 error back to the skill on sending activity.

uring handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/victorvasiliev/PycharmProjects/BotBuilder-Samples/samples/python/80.skills-simple-bot-to-bot/echo-skill-bot/adapter_with_error_handler.py", line 71, in _send_eoc_to_parent
    await turn_context.send_activity(end_of_conversation)
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 170, in send_activity
    result = await self.send_activities([activity_or_text])
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 217, in send_activities
    return await self._emit(self._on_send_activities, output, logic())
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 295, in _emit
    return await logic
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/turn_context.py", line 212, in logic
    responses = await self.adapter.send_activities(self, output)
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_framework_adapter.py", line 686, in send_activities
    raise error
  File "/usr/local/lib/python3.7/site-packages/botbuilder/core/bot_framework_adapter.py", line 672, in send_activities
    activity.conversation.id, activity.reply_to_id, activity
  File "/usr/local/lib/python3.7/site-packages/botframework/connector/aio/operations_async/_conversations_operations_async.py", line 533, in reply_to_activity
    raise models.ErrorResponseException(self._deserialize, response)
botbuilder.schema._models_py3.ErrorResponseException: Operation returned an invalid status code 'Not Found'

Did anybody faced the same issue?


问:
Set conditional request header if client ip is local
I'm trying to set a request header in Apache, the value of the header depends on the IP address of the client. If the IP address is local (private range) the value of the header should be "inside" else it should be "outside"

So far I have configured:

```<code>     RemoteIPHeader X-Forwarded-For
     RemoteIPInternalProxy 172.24.x.x
</code>```

The value of X-Forwarded-For now has the clients IP address. The other part should be solvable with Apache If then Else Syntax but I have no idea how to check the value of X-Forwarded-For and compare it against all local/private IP ranges.

```<code><If "????????'">
 RequestHeader set My-Header "inside"
</If>
<Else>
 RequestHeader set My-Header "outside"
</Else>
</code>```

I'm running:

```<code>  Server version: Apache/2.4.6 (CentOS)
  Server built:   Aug  8 2019 11:41:18
</code>```

答:
I manged to solve it myself, I can probably use an or statements to get rid of the Elsifs and write the entire condition in just one if but I like how this reads. If a better approach exists I'm still interested.</p>

```<code>RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 172.24.x.x #Loadbalancer IP

<If "%{REMOTE_ADDR} -ipmatch '010.000.000.000/8'">
 RequestHeader set My-Header "inside"
</If>
<ElseIf "%{REMOTE_ADDR} -ipmatch '172.016.000.000/12'">
 RequestHeader set My-Header "inside"
</ElseIf>
<ElseIf "%{REMOTE_ADDR} -ipmatch '192.168.000.000/16'">
 RequestHeader set My-Header "inside"
</ElseIf>
<Else>
 RequestHeader set My-Header "outside"
</Else>
</code>```

Body:
I'm trying to set a request header in Apache, the value of the header depends on the IP address of the client. If the IP address is local (private range) the value of the header should be "inside" else it should be "outside"

So far I have configured:

     RemoteIPHeader X-Forwarded-For
     RemoteIPInternalProxy 172.24.x.x

The value of X-Forwarded-For now has the clients IP address. The other part should be solvable with Apache If then Else Syntax but I have no idea how to check the value of X-Forwarded-For and compare it against all local/private IP ranges.

<If "????????'">
 RequestHeader set My-Header "inside"
</If>
<Else>
 RequestHeader set My-Header "outside"
</Else>

I'm running:

  Server version: Apache/2.4.6 (CentOS)
  Server built:   Aug  8 2019 11:41:18

Body:
I manged to solve it myself, I can probably use an or statements to get rid of the Elsifs and write the entire condition in just one if but I like how this reads. If a better approach exists I'm still interested.

RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 172.24.x.x #Loadbalancer IP

<If "%{REMOTE_ADDR} -ipmatch '010.000.000.000/8'">
 RequestHeader set My-Header "inside"
</If>
<ElseIf "%{REMOTE_ADDR} -ipmatch '172.016.000.000/12'">
 RequestHeader set My-Header "inside"
</ElseIf>
<ElseIf "%{REMOTE_ADDR} -ipmatch '192.168.000.000/16'">
 RequestHeader set My-Header "inside"
</ElseIf>
<Else>
 RequestHeader set My-Header "outside"
</Else>


问:
Another "Build path specifies execution environment JavaSE-13." problem
So, the full warning looks like
Build path specifies execution environment JavaSE-13. There are no JREs installed in the workspace that are strictly compatible with this environment.

I just installed JDK(version: 14.0.1 from here) and Eclipse(Version: 2020-03 (4.15.0) from here)

I've read post1 and post2 but i dont have any libraries in Java->Build Path -> User libraries. It's empty at all. In Installed Libraries i don't have any jdk{version}. I only have Name "JDK" and Location "D:\..."

Am i missing something vital? Because i have no idea how to fix it.

I am newbee, so if you have an answer or following question, please write a bit simpler. Thank you.

答:
This should really be a comment, but I felt like spelling things out. The main thing to watch out for here is that with Java its version comes into play at least 4 times and there is nothing strictly stopping you from having 4 different versions configured on each occasion, which may or may not work. Add Eclipse and it becomes at least 5:

The java binary used to run Eclipse itself. (Configured via eclipse.ini)

This can affect how plugins behave. I remember a scenario where m2e would refuse to use a Java compliance level older than the version of the JRE running Eclipse. I can't make too confident specific calls from the top of my head here, but this is something to keep in mind.

Should be latest and greatest, though Java 8 appears to be the defensive option for obscure scenarios, such as projects depending on deprecated internal libraries. (tools.jar comes to mind)

The javac (java compiler) binary used to build your project. (Sits next to the java binary in a bin subdirectory of the JDK)

Should also be latest and greatest: every version of javac is capable of compiling source code written for previous versions as well as generating compatible byte code for older versions. This is what the following two points are about.

The Java version that javac is told to assert that your code is compatible with. (javac -source parameter)

The Java version that javac is told to make your build compatible with. (javac -target parameter; equal or greater than the value of -source)

The java  binary used to run your build.

Should also be latest and greatest, though the minimum version required here is what was given to javac via -target, and incompatibility scenarios do exist.

The latest trend here is to ship every Java application with its own JRE to rule out problems arising from users having configured or installed Java in an incompatible manner. A user will then be required run a specially crafted native executable or a shortcut which will then invoke Java with the right arguments to start the application.

Now, you do not invoke javac or java even. In fact, the former is not even invoked by Eclipse. Eclipse actually comes with its own Java compiler, Eclipse Compiler for Java (ECJ). For what it's worth, we don't usually need to worry about that however. For Eclipse to know anything about available JREs, you need to match JDK locations on disk to Java versions "known" to Eclipse. This is done under Window -> Preferences -> Java -> Installed JREs -> Execution Environments.

After doing that, they should pop up in all the places where you can specify Java versions, which is mainly Project settings and possibly run configurations you have set up or Eclipse has set up for you. Project settings can then be set to up to infer the compliance level for building from the version of the JRE configured to run the build.

By the way, note that you probably want to use AdoptOpenJDK instead of the release from Oracle for reasons. You'll also want to just unpack any JREs which aren't the latest one in a nice folder somewhere on your hard drive instead of installing them. Installing them mostly means to make .jar files run with that version when launched from your OS's file browser. If you are on Linux, sdkman is currently the preferred way to do this.


问:
Expire unix or time() code after x hours
I am trying to create a forgot password feature which will expire the link created after x hours. So I am storing time() data in database value when a user requests a password reset. So how can I expire it?

答:
three options:

compare the time you saved on the db with the one you get when the user click the link

Use a cron job and make it run periodically

Just don't save in the db and make the link to care about everything. You could use a signature + a salt to avoid users to modify this link

like:

```<code>$now = time();

$sk = sh1($user_id . $now . "yoursupersalthere")

$link = "http://www.example.com/forgot.php?id={$user_id}&ts={$now}&sk={$sk}"
</code>```

that will be the link you sent to the user. Then to make the check

```<code>$ts = $_GET['ts'];
$user = $_GET['id'];
$sk = $_GET['sk'];

if (!$sk == sh1($user_id . $now . "yoursupersalthere")) {
    die("bad signature");
}
elseif (time() - $ts > 3600 /* or put your expiration limit */) {
    die('link expired');
}

// do your job
</code>```

Body:
three options:

compare the time you saved on the db with the one you get when the user click the link

Use a cron job and make it run periodically

Just don't save in the db and make the link to care about everything. You could use a signature + a salt to avoid users to modify this link

like:

$now = time();

$sk = sh1($user_id . $now . "yoursupersalthere")

$link = "http://www.example.com/forgot.php?id={$user_id}&ts={$now}&sk={$sk}"

that will be the link you sent to the user. Then to make the check

$ts = $_GET['ts'];
$user = $_GET['id'];
$sk = $_GET['sk'];

if (!$sk == sh1($user_id . $now . "yoursupersalthere")) {
    die("bad signature");
}
elseif (time() - $ts > 3600 /* or put your expiration limit */) {
    die('link expired');
}

// do your job


问:
use styled-components to share styles between components/elements
I am using styled-components along with Gatsby. I used styled-components to style the Link component provided by Gatsby for my home page.

const HomePageLink = styled(Link)`
  display: inline-block;
  font-size: ${fontSizes.xxlarge};
  text-decoration: none;
  box-shadow: none;
  :link,
  :visited {
    color: ${colors.slate};
  }
  :hover,
  :active {
    color: ${colors.red};
  }
`
```

<p>However I realize that I also need to style a plain html <code>/></code> tag using the exactly same style. I  wonder is there a way to make the style component above adapt to <code>/></code> tags without duplicating the code like this</p>

<pre class="lang-js prettyprint-override"><code>const HomePageAnchorTag = styled.a`
  display: inline-block;
  font-size: ${fontSizes.xxlarge};
  text-decoration: none;
  box-shadow: none;
  :link,
  :visited {
    color: ${colors.slate};
  }
  :hover,
  :active {
    color: ${colors.red};
  }
`
</code>```

答:
Yes, use css API which allows you to construct reusable CSS blocks.

A helper function to generate CSS from a template literal with interpolations.

```<code>import styled, { css } from 'styled-components';
const reusableCSS = css`
  display: inline-block;
  font-size: ${fontSizes.xxlarge};
  text-decoration: none;
  box-shadow: none;
  :link,
  :visited {
    color: ${colors.slate};
  }
  :hover,
  :active {
    color: ${colors.red};
  }
`;

const HomePageAnchorTag = styled.a`
  ${reusableCSS}
`;

const HomePageLink = styled(Link)`
  ${reusableCSS}
`;
</code>```

Usually, you will notice a mixins.js file that contains exports of reusable css block, for example:

```<code>// mixins.js
const flexCenter = css`...`
export default { flexCenter };

// usage inside styled components.
${mixins.flexCenter}
</code>```

Body:
I am using styled-components along with Gatsby. I used styled-components to style the Link component provided by Gatsby for my home page.

const HomePageLink = styled(Link)`
  display: inline-block;
  font-size: ${fontSizes.xxlarge};
  text-decoration: none;
  box-shadow: none;
  :link,
  :visited {
    color: ${colors.slate};
  }
  :hover,
  :active {
    color: ${colors.red};
  }
`

However I realize that I also need to style a plain html  tag using the exactly same style. I  wonder is there a way to make the style component above adapt to  tags without duplicating the code like this

const HomePageAnchorTag = styled.a`
  display: inline-block;
  font-size: ${fontSizes.xxlarge};
  text-decoration: none;
  box-shadow: none;
  :link,
  :visited {
    color: ${colors.slate};
  }
  :hover,
  :active {
    color: ${colors.red};
  }
`

Body:
Yes, use css API which allows you to construct reusable CSS blocks.

A helper function to generate CSS from a template literal with interpolations.

import styled, { css } from 'styled-components';
const reusableCSS = css`
  display: inline-block;
  font-size: ${fontSizes.xxlarge};
  text-decoration: none;
  box-shadow: none;
  :link,
  :visited {
    color: ${colors.slate};
  }
  :hover,
  :active {
    color: ${colors.red};
  }
`;

const HomePageAnchorTag = styled.a`
  ${reusableCSS}
`;

const HomePageLink = styled(Link)`
  ${reusableCSS}
`;

Usually, you will notice a mixins.js file that contains exports of reusable css block, for example:

// mixins.js
const flexCenter = css`...`
export default { flexCenter };

// usage inside styled components.
${mixins.flexCenter}


问:
nlstools methods not accepting nls object
I am using the nlstools package in R. I fit a model to my data and plot it well. I am not sure what i am doing wrong but i can't seem to call methods from nlstools as i get an error for "object 'd' not found". Here is the code, with the error lines commented:

```<code>Y=y_coll
X=x_ntips
d=data.frame(X,Y)

thisfit=nls(Y ~ a*X^b,data=d, start = list(a = .1, b = .1))

### Error in eval(expr, envir, enclos) : object 'd' not found
#a=nlsBoot (thisfit, niter = 999)
#cr= nlsConfRegions(thisfit, exp = 2, length = 200)

#plotting
res= data.frame(X, pred = predict(thisfit))
points(res[order(X),], type='l', col="grey40", lty=1)
</code>```

Any ideas of what is going on?
thanks

答: I encountered this same problem when using data containing NA's. Once I removed the NA's, the code worked fine.

Body:
I am using the nlstools package in R. I fit a model to my data and plot it well. I am not sure what i am doing wrong but i can't seem to call methods from nlstools as i get an error for "object 'd' not found". Here is the code, with the error lines commented:

Y=y_coll
X=x_ntips
d=data.frame(X,Y)

thisfit=nls(Y ~ a*X^b,data=d, start = list(a = .1, b = .1))

### Error in eval(expr, envir, enclos) : object 'd' not found
#a=nlsBoot (thisfit, niter = 999)
#cr= nlsConfRegions(thisfit, exp = 2, length = 200)

#plotting
res= data.frame(X, pred = predict(thisfit))
points(res[order(X),], type='l', col="grey40", lty=1)

Any ideas of what is going on?
thanks


问:
Ionic background task at a specific time?
Q: how can I do a task that repeats every x minutes in background?

答:
Use js setTimeout function.

Like this:

```<code>setTimeout(() => {
 alert("Hello");
}, 3000);
</code>```

3000 is the amount of time in ms. so this alert will be shown every 3 seconds.

to run it under any condition put it in app.component.ts

Body:
Use js setTimeout function.

Like this:

setTimeout(() => {
 alert("Hello");
}, 3000);

3000 is the amount of time in ms. so this alert will be shown every 3 seconds.

to run it under any condition put it in app.component.ts


问:
Change color of the checkbox when selected
I have a checkbox with an input button hidden. If the checkbox is selected, then the background color of the checkbox will be changed as it changes when hovered over. I am not able to do this. Here is the code:

.btn-grad{
                width: 400px;
                height: 10px;
                margin-top: 20px;
                padding: 15px;
                color: rgb(255, 255, 255);
                text-align: center;
                text-decoration: none;
                    background-color: linear-gradient(to right, #E55D87 0%, #5FC3E4 51%, #E55D87 100%);
                    background: linear-gradient(to right, #E55D87 0%, #5FC3E4 51%, #E55D87 100%);
                    border-radius: 5px;
                    border: 1px solid rgb(69, 9, 104);
                    box-shadow:
                    0px 5px 5px rgba(000,000,000,0.1),
                    inset 0px 1px 0px rgba(255,255,255,0.5);
                text-shadow:
                    0px 1px 3px rgba(000,000,000,0.3),
                    0px 0px 0px rgba(255,255,255,0);
                display: table;
                position: static;
                clear: both;
            }

            .btn-grad:hover{
                background-position: right center;
                background:
                    linear-gradient(to right top,
                #e4f0f8, #cfe5fc, #c3d7ff,
                #c1c8ff, #c9b5fb, #c0b6fd, #b7b6fe,
                #adb7ff, #8ecaff, #7dd9ff, #82e6f9, #99f0eb);
            }

            .btn-grad:checked{
                background-color: red;
            }

            .btn-grad > input{
                 display:none;
            }

            .btn-grad > div{
                font-size:25px;
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <body>
    <form>
      <label class="btn-grad" name="math">
      <input type="checkbox" name="course" value="math">
       <div>
        MATHS
       </div>
       </label></code>```

答:
Give the input checkbox a class name and id

```<code>  <input type="checkbox" class="mycheckbox" name="course" value="math" id="changecheck">
</code>```

Change label to this

```<code> <label for="changecheck">Math</label>
</code>```

The Using CSS to you can change background color when checked like this:

```<code> .mycheckbox:checked + label:after {
  background-color: red;
     }
</code>```

Body:
I have a checkbox with an input button hidden. If the checkbox is selected, then the background color of the checkbox will be changed as it changes when hovered over. I am not able to do this. Here is the code:

.btn-grad{
                width: 400px;
                height: 10px;
                margin-top: 20px;
                padding: 15px;
                color: rgb(255, 255, 255);
                text-align: center;
                text-decoration: none;
                    background-color: linear-gradient(to right, #E55D87 0%, #5FC3E4 51%, #E55D87 100%);
                    background: linear-gradient(to right, #E55D87 0%, #5FC3E4 51%, #E55D87 100%);
                    border-radius: 5px;
                    border: 1px solid rgb(69, 9, 104);
                    box-shadow:
                    0px 5px 5px rgba(000,000,000,0.1),
                    inset 0px 1px 0px rgba(255,255,255,0.5);
                text-shadow:
                    0px 1px 3px rgba(000,000,000,0.3),
                    0px 0px 0px rgba(255,255,255,0);
                display: table;
                position: static;
                clear: both;
            }

            .btn-grad:hover{
                background-position: right center;
                background:
                    linear-gradient(to right top,
                #e4f0f8, #cfe5fc, #c3d7ff,
                #c1c8ff, #c9b5fb, #c0b6fd, #b7b6fe,
                #adb7ff, #8ecaff, #7dd9ff, #82e6f9, #99f0eb);
            }

            .btn-grad:checked{
                background-color: red;
            }

            .btn-grad > input{
                 display:none;
            }

            .btn-grad > div{
                font-size:25px;
            }

    <form>

      <input type="checkbox" name="course" value="math">

        MATHS

Body:
Give the input checkbox a class name and id

  <input type="checkbox" class="mycheckbox" name="course" value="math" id="changecheck">

Change label to this

 <label for="changecheck">Math</label>

The Using CSS to you can change background color when checked like this:

 .mycheckbox:checked + label:after {
  background-color: red;
     }


答:
One method of doing this is to check to see if the link is expired when the link is clicked -- some pseudo-code:</p>

```<code>// when the link is clicked pull the information from the database and get the time
// SQL goes here

// this will give you the difference in seconds
$diff = time() - $timestamp_from_db;

// we'll pretend the time expires in 8 hours
$expires_in = 8 * 60 * 60;

// for this example we'll pretend the expiration is 8 hours
if($diff <= $expires_in)
{
  // has not been more then 8 hours
}
else
{
  // has been more then 8 hours
}
</code>```

Title: Expire unix or time() code after x hours

Body: I am trying to create a forgot password feature which will expire the link created after x hours. So I am storing time() data in database value when a user requests a password reset. So how can I expire it?

Body:
One method of doing this is to check to see if the link is expired when the link is clicked -- some pseudo-code:

// when the link is clicked pull the information from the database and get the time
// SQL goes here

// this will give you the difference in seconds
$diff = time() - $timestamp_from_db;

// we'll pretend the time expires in 8 hours
$expires_in = 8 * 60 * 60;

// for this example we'll pretend the expiration is 8 hours
if($diff <= $expires_in)
{
  // has not been more then 8 hours
}
else
{
  // has been more then 8 hours
}


问:
"Missing start boundary" when sending Emails with Text attachment
I have trouble sending Emails with text attachments (without attachment, everything is fine). I'm using actionmailer 3.2.11 and try to send Emails over Amazon SES. To me it looks like, that the amazon snmp server has a problem with the emails I produce. The code to produce the email looks like this:

```<code>class ServiceMailer < ActionMailer::Base
    default from: "noreply@dungeonpilot.com"

    def server_crashed log_file_names
        attachments[ 'foo.txt' ] = 'Hallo'
        mail to: 'Txxx@xxzki.de', subject: '[dungeonpilot] Server Crashed'
   end
end
</code>```

The error message, when sending mails: Net::SMTPFatalError: 554 Transaction failed: Missing start boundary.

The resulting Mail is this:

```<code>Date: Fri, 08 Feb 2013 10:11:09 +0000
From: noreply@dungeonpilot.com
To: Txxx@xxxzki.de
Message-ID: <5114cf3dc4886_701165e7f848869@ip-10-62-103-46.mail>
Subject: [dungeonpilot] Server Crashed
Mime-Version: 1.0
Content-Type: multipart/mixed;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

--
Date: Fri, 08 Feb 2013 10:11:09 +0000
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
 filename=foo.txt
filename: foo.txt
Content-ID: <5114cf3d55085_701165e7f8487cc@ip-10-62-103-46.mail>

Hallo

----
</code>```

Delivering this to SES as a Test Mail, results too in "Missing start boundary". So I think there must be something wrong with the delivered content.

In the views folder, there was just one .txt.erb template. I've added a .html.erb template and now there is a boundary="-header and boundaries between the mail parts:

```<code>Date: Fri, 08 Feb 2013 10:26:57 +0000
From: noreply@dungeonpilot.com
To: Torsten@Robitzki.de
Message-ID: <5114d2f1b8175_702812508041181@ip-10-62-103-46.mail>
Subject: [dungeonpilot] Server Crashed
Mime-Version: 1.0
Content-Type: multipart/mixed;
 boundary="--==_mimepart_5114d2f18f621_7028125080411632";
 charset=UTF-8
Content-Transfer-Encoding: 7bit

----==_mimepart_5114d2f18f621_7028125080411632
Date: Fri, 08 Feb 2013 10:26:57 +0000
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
 filename=foo.txt
filename: foo.txt
Content-ID: <5114d2f0ee34b_7028125080411545@ip-10-62-103-46.mail>

Hallo

----==_mimepart_5114d2f18f621_7028125080411632
Date: Fri, 08 Feb 2013 10:26:57 +0000
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <5114d2f19ce45_7028125080411785@ip-10-62-103-46.mail>

----==_mimepart_5114d2f18f621_7028125080411632--
</code>```

Looks like a bug in ActionMailer?

答: I faced the same issue, in my case I as appending an empty multipart in email body.</p>

Body:
I have trouble sending Emails with text attachments (without attachment, everything is fine). I'm using actionmailer 3.2.11 and try to send Emails over Amazon SES. To me it looks like, that the amazon snmp server has a problem with the emails I produce. The code to produce the email looks like this:

class ServiceMailer < ActionMailer::Base
    default from: "noreply@dungeonpilot.com"

    def server_crashed log_file_names
        attachments[ 'foo.txt' ] = 'Hallo'
        mail to: 'Txxx@xxzki.de', subject: '[dungeonpilot] Server Crashed'
   end
end

The error message, when sending mails: Net::SMTPFatalError: 554 Transaction failed: Missing start boundary.

The resulting Mail is this:

Date: Fri, 08 Feb 2013 10:11:09 +0000
From: noreply@dungeonpilot.com
To: Txxx@xxxzki.de
Message-ID: <5114cf3dc4886_701165e7f848869@ip-10-62-103-46.mail>
Subject: [dungeonpilot] Server Crashed
Mime-Version: 1.0
Content-Type: multipart/mixed;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

--
Date: Fri, 08 Feb 2013 10:11:09 +0000
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
 filename=foo.txt
filename: foo.txt
Content-ID: <5114cf3d55085_701165e7f8487cc@ip-10-62-103-46.mail>

Hallo

----

Delivering this to SES as a Test Mail, results too in "Missing start boundary". So I think there must be something wrong with the delivered content.

In the views folder, there was just one .txt.erb template. I've added a .html.erb template and now there is a boundary="-header and boundaries between the mail parts:

Date: Fri, 08 Feb 2013 10:26:57 +0000
From: noreply@dungeonpilot.com
To: Torsten@Robitzki.de
Message-ID: <5114d2f1b8175_702812508041181@ip-10-62-103-46.mail>
Subject: [dungeonpilot] Server Crashed
Mime-Version: 1.0
Content-Type: multipart/mixed;
 boundary="--==_mimepart_5114d2f18f621_7028125080411632";
 charset=UTF-8
Content-Transfer-Encoding: 7bit

----==_mimepart_5114d2f18f621_7028125080411632
Date: Fri, 08 Feb 2013 10:26:57 +0000
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
 filename=foo.txt
filename: foo.txt
Content-ID: <5114d2f0ee34b_7028125080411545@ip-10-62-103-46.mail>

Hallo

----==_mimepart_5114d2f18f621_7028125080411632
Date: Fri, 08 Feb 2013 10:26:57 +0000
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <5114d2f19ce45_7028125080411785@ip-10-62-103-46.mail>

----==_mimepart_5114d2f18f621_7028125080411632--

Looks like a bug in ActionMailer?


问:
How to escape closing square bracket within regular expression character class?
This command works as expected:

$ echo "foo}bar]baz" | sed 's/}/@/g; s/]/@/g'
foo@bar@baz
```

<p>Now I am trying to do the same thing using character class like this:</p>

<pre class="lang-sh prettyprint-override"><code>$ echo "foo}bar]baz" | sed 's/[}\]]/@/g'
foo}bar]baz
</code>```

This did not work. I want to have a character class with two characters } and ] so I thought escaping the square bracket like }\] would work but it did not.

What am I missing?

答:
You may use "smart" placement:

```<code>echo "foo}bar]baz" | sed 's/[]}]/@/g'
</code>```

See the online sed demo

Here, the ] char must appear right after the open square bracket, otherwise, it is treated as the bracket expression close bracket and the bracket expression is closed prematurely.

Note that in case you want to safely use - inside a bracket expression, you may use it right before the close square bracket.

Body:
This command works as expected:

$ echo "foo}bar]baz" | sed 's/}/@/g; s/]/@/g'
foo@bar@baz

Now I am trying to do the same thing using character class like this:

$ echo "foo}bar]baz" | sed 's/[}\]]/@/g'
foo}bar]baz

This did not work. I want to have a character class with two characters } and ] so I thought escaping the square bracket like }\] would work but it did not.

What am I missing?

Body:
You may use "smart" placement:

echo "foo}bar]baz" | sed 's/[]}]/@/g'

See the online sed demo

Here, the ] char must appear right after the open square bracket, otherwise, it is treated as the bracket expression close bracket and the bracket expression is closed prematurely.

Note that in case you want to safely use - inside a bracket expression, you may use it right before the close square bracket.


问:
Retrieve first non-NA value from a group of columns
I'm a pretty new coder so if you guys could help me that'd be great.

Let's say I have one dataframe:

Can I combine "Number" and "Number 2" in a way where "Number" takes precedence unless there is no value(NaN). When "Number" is NaN, then we use the entry in "Number 2"

It should look like this

In other words, I want to combine "Number" and "Number 2" where if "Number" is NaN, then use "Number 2"'s entry. If "Number" has an entry, keep it for the merged entry. This is similar to left merge for merging two data frames.

Btw, I'm using python and pandas.

Update: trying to use np.where

Output without np.where:

Output with np.where:

答:
bfill(axis=1) and iloc

```<code>df = pd.DataFrame({
    'Name': df['Name'],
    'Number': df.filter(like='Number').bfill(axis=1).iloc[:,0]
})
</code>```

Body:
bfill(axis=1) and iloc

df = pd.DataFrame({
    'Name': df['Name'],
    'Number': df.filter(like='Number').bfill(axis=1).iloc[:,0]
})


问:
Uncaught TypeError: Cannot read property 'innerHTML' of null at text inside this blog website I'm trying to write

var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //problem
  document.createElement("p").id = y;
  //
  document.getElementById(y).innerHTML = blogtext;
  //document.write("
"+blogtext+"
");
  x = x + 1;
}
```

When I run this code inside an HTML file the error: Uncaught TypeError occurs, the code is supposed to create a new paragraph tag whose content is the text inputted by the user inside the text area and each paragraph would have a different id as x increases.
Sorry, I'm new to coding this is one of my school's projects.

答:
append your paragraph to the DOM, check out for this one i made </p>

```<code> var x = 0;
function text() {
    var blogtext = document.getElementById("Textarea").value;
    var y = "p" + String(x);
    console.log(typeof y);
    var x =document.createElement("p").id = y;
    document.body.appendChild(x);
    document.getElementById(y).innerHTML = blogtext;
    x = x + 1;
}
</code>```

Body:
var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //problem
  document.createElement("p").id = y;
  //
  document.getElementById(y).innerHTML = blogtext;
  //document.write("
"+blogtext+"
");
  x = x + 1;
}

When I run this code inside an HTML file the error: Uncaught TypeError occurs, the code is supposed to create a new paragraph tag whose content is the text inputted by the user inside the text area and each paragraph would have a different id as x increases.
Sorry, I'm new to coding this is one of my school's projects.

Body:
append your paragraph to the DOM, check out for this one i made

 var x = 0;
function text() {
    var blogtext = document.getElementById("Textarea").value;
    var y = "p" + String(x);
    console.log(typeof y);
    var x =document.createElement("p").id = y;
    document.body.appendChild(x);
    document.getElementById(y).innerHTML = blogtext;
    x = x + 1;
}