问:
Add IF condition to clickable images to ascertain a pixel value
We have 2 images that we fetched from JSON:

1.Mask image [  name starts with mask_ ]

2.Car image [ name starts with other than mask_ ]

Requirement :

onclick Mask image , i want to display file upload dialog box. it's working fine. but onclick car image, i don't want to display file upload dialog box.

Issue :

onclick car image,  file upload dialog box is displaying. but Car image should't be clickable because it's name started with "other than mask_"

I tried $('.masked-img').css('pointer-events', 'none'); but it did't helped me.

Below is Snippet :

var target;
const imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
  "layers": [{
    "x": 0,
    "height": 612,
    "layers": [{
        "x": 70,
        "src": "ax0HVTs.png",
        "y": 199,
        "height": 296,
        "width": 429,
        "name": "mask_1"
      },
      {
        "name": "car",
        "x": 25,
        "src": "iEA642D.jpg",
        "height": 324,
        "width": 471,
        "y": 22

      }
    ],
    "y": 0,
    "width": 612
  }]
};

const containerElement = $('#container');
const fileUp = $('#fileup');
let mask;

$(function() {
  // Upload image onclick mask image
  containerElement.click(function(e) {
    var res = e.target;
    target = res.id;
    if (e.target.getContext) {
      // click only inside Non Transparent part
      var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
      if (pixel[3] === 255) {
        setTimeout(() => {
          $('#fileup').click();
        }, 20);
      }
    }
  });

  // Fetch mask images from json file - IGNORE this code

  function getAllSrc(layers) {
    let arr = [];
    layers.forEach(layer => {
      if (layer.src) {
        arr.push({
          src: layer.src,
          x: layer.x,
          y: layer.y,
          height: layer.height,
          width: layer.width,
          name: layer.name
        });
      } else if (layer.layers) {
        let newArr = getAllSrc(layer.layers);
        if (newArr.length > 0) {
          newArr.forEach(({
            src,
            x,
            y,
            height,
            width,
            name
          }) => {
            arr.push({
              src,
              x: (layer.x + x),
              y: (layer.y + y),
              height,
              width,
              name: (name)
            });
          });
        }
      }
    });
    return arr;
  }

  function json(data) {
    var width = 0;
    var height = 0;

    let arr = getAllSrc(data.layers);
    let layer1 = data.layers;
    width = layer1[0].width;
    height = layer1[0].height;
    let counter = 0;
    let table = [];

    // container dimensions
    containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
    //end

    for (let {
        src,
        x,
        y,
        name
      } of arr) {

      //Get Height and width of mask image [ edit button ]
      var ImagePosition = arr;
      //code end

      var imageUrl1 = imageUrl;

      var mask = $(".container").mask({
        imageUrl: name.indexOf('mask_') !== -1 ? imageUrl1 : undefined,

        // Fetch Mask images
        maskImageUrl: 'http://i.imgur.com/' + src,
        // end

        onMaskImageCreate: function(img) {
          // Mask image positions
          img.css({
            "position": "absolute",
            "left": x + "px",
            "top": y + "px"
          });
          // end

        },
        id: counter
      });
      // here
      table.push(mask);
      fileup.onchange = function() {

        let mask2 = table[target];
        const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
        document.getElementById('fileup').value = "";

      };
      counter++;
    }
    return mask;
  }
  mask = json(jsonData);
}); // end of function

// Image code

(function($) {
  window.JQmasks = [];
  $.fn.mask = function(options) {
    // This is the easiest way to have default options.
    var settings = $.extend({
      // These are the defaults.
      maskImageUrl: undefined,
      imageUrl: undefined,
      scale: 1,
      id: new Date().getUTCMilliseconds().toString(),
      x: 0, // image start position
      y: 0, // image start position
      onMaskImageCreate: function(div) {},
    }, options);

    // Create the image properties
    settings.maskImage = new Image
    settings.image = new Image

    // set the cross-origin attributes
    settings.maskImage.setAttribute('crossOrigin', 'anonymous');
    settings.image.setAttribute('crossOrigin', 'anonymous');

    settings.maskImage.onload = function() {
      // once the mask is loaded, load the image
      container.loadImage(settings.imageUrl)
      container.drawMask()
    }

    settings.image.onload = function() {
      // once the image is loaded, render to canvas

      container.drawImage()
    }

    var container = $(this);

    let prevX = 0,
      prevY = 0,
      draggable = false,
      img,
      canvas,
      context,
      image,
      timeout,
      initImage = false,
      startX = settings.x,
      startY = settings.y,
      div;

    container.drawMask = function() {
      if (!settings.maskImage) return true;
      canvas.width = settings.maskImage.width;
      canvas.height = settings.maskImage.height;
      context.save();
      context.beginPath();
      context.globalCompositeOperation = "source-over";
      // draw the masked image after scaling
      if (settings.maskImage) context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage.height);
      context.restore()
    };

    container.drawImage = function() {

      const img = settings.image

      settings.x = (canvas.width - (img.width * settings.scale)) / 2
      settings.y = (canvas.height - (img.height * settings.scale)) / 2

      context.globalCompositeOperation = 'source-atop';
      if (img) context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
      context.restore()
      initImage = false;
    }

    // change the draggable image

    container.loadImage = function(imageUrl) {
      if (!imageUrl) return true;
      settings.y = startY;
      settings.x = startX;
      prevX = prevY = 0;

      initImage = true;

      settings.image.src = imageUrl; // CHANGED

      // sirpepole Add this
      return settings.id;
    };

    container.loadMaskImage = function(imageUrl, from) {

      canvas = document.createElement("canvas");
      context = canvas.getContext('2d');
      canvas.setAttribute("draggable", "true");
      canvas.setAttribute("id", settings.id);
      // settings.maskImageUrl = imageUrl;
      settings.maskImage.src = imageUrl // CHANGED

      div = $("
", {
        "class": "masked-img"
      }).append(canvas);

      // div.find("canvas").on('touchstart mousedown', function(event)
      div.find("canvas").on('dragstart', function(event) {
        if (event.handled === false) return;
        event.handled = true;
        container.onDragStart(event);
      });

      div.find("canvas").on('touchend mouseup', function(event) {
        if (event.handled === false) return;
        event.handled = true;
        container.selected(event);
      });

      div.find("canvas").bind("dragover", container.onDragOver);

      container.append(div);
      if (settings.onMaskImageCreate)
        settings.onMaskImageCreate(div);

      // container.loadImage(settings.imageUrl);
      // Moved this to the settings.maskImage.onload
    };
    if (settings.maskImageUrl) {
      container.loadMaskImage(settings.maskImageUrl);
    }
    JQmasks.push({
      item: container,
      id: settings.id
    })
    // Edit image
    div.addClass('masked-img' + settings.id);
    div.attr('data-id', settings.id);
    // ends
    return container;
  };
}(jQuery));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  background: silver;
  position: relative;
}

.container img {
  position: absolute;
  top: 0;
  bottom: 250px;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 999;
}

.masked-img {
  overflow: hidden;
  position: relative;
}</code>```

<input id="fileup" name="fileup" type="file" style="display:none" />

```

Here is Codepen, Fiddle & Full code in pastebin

We implemented similar feature that displaying "+" icon only on mask images....

答:
You are getting the data of one pixel and it returns a Uint8ClampedArray which is 4 bytes long.

```<code>var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
</code>```

Now these 4 bytes represent the R, G, B and A value of the pixel. The pixels[3] represents the Alpha value which can be 255 easily for most of the images.

If you want to make sure that only the White pixels should trigger the action, you should check for R, G and B for 255.

```<code>if (pixel[0] === 255 && pixel[1] === 255 && pixel[2] === 255) {
     setTimeout(() => {
         $('#fileup').click();
     }, 20);
}
</code>```

Hint:

There is a design flaw in your program. That is, if your image (the car or anything) has White pixels and the user clicks on one of them, the action would be taken. You should check for a clicks on the mask region and then look for White pixels.

Body:
We have 2 images that we fetched from JSON:

1.Mask image [  name starts with mask_ ]

2.Car image [ name starts with other than mask_ ]

Requirement :

onclick Mask image , i want to display file upload dialog box. it's working fine. but onclick car image, i don't want to display file upload dialog box.

Issue :

onclick car image,  file upload dialog box is displaying. but Car image should't be clickable because it's name started with "other than mask_"

I tried $('.masked-img').css('pointer-events', 'none'); but it did't helped me.

Below is Snippet :

var target;
const imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
  "layers": [{
    "x": 0,
    "height": 612,
    "layers": [{
        "x": 70,
        "src": "ax0HVTs.png",
        "y": 199,
        "height": 296,
        "width": 429,
        "name": "mask_1"
      },
      {
        "name": "car",
        "x": 25,
        "src": "iEA642D.jpg",
        "height": 324,
        "width": 471,
        "y": 22

      }
    ],
    "y": 0,
    "width": 612
  }]
};

const containerElement = $('#container');
const fileUp = $('#fileup');
let mask;

$(function() {
  // Upload image onclick mask image
  containerElement.click(function(e) {
    var res = e.target;
    target = res.id;
    if (e.target.getContext) {
      // click only inside Non Transparent part
      var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
      if (pixel[3] === 255) {
        setTimeout(() => {
          $('#fileup').click();
        }, 20);
      }
    }
  });

  // Fetch mask images from json file - IGNORE this code

  function getAllSrc(layers) {
    let arr = [];
    layers.forEach(layer => {
      if (layer.src) {
        arr.push({
          src: layer.src,
          x: layer.x,
          y: layer.y,
          height: layer.height,
          width: layer.width,
          name: layer.name
        });
      } else if (layer.layers) {
        let newArr = getAllSrc(layer.layers);
        if (newArr.length > 0) {
          newArr.forEach(({
            src,
            x,
            y,
            height,
            width,
            name
          }) => {
            arr.push({
              src,
              x: (layer.x + x),
              y: (layer.y + y),
              height,
              width,
              name: (name)
            });
          });
        }
      }
    });
    return arr;
  }

  function json(data) {
    var width = 0;
    var height = 0;

    let arr = getAllSrc(data.layers);
    let layer1 = data.layers;
    width = layer1[0].width;
    height = layer1[0].height;
    let counter = 0;
    let table = [];

    // container dimensions
    containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
    //end

    for (let {
        src,
        x,
        y,
        name
      } of arr) {

      //Get Height and width of mask image [ edit button ]
      var ImagePosition = arr;
      //code end

      var imageUrl1 = imageUrl;

      var mask = $(".container").mask({
        imageUrl: name.indexOf('mask_') !== -1 ? imageUrl1 : undefined,

        // Fetch Mask images
        maskImageUrl: 'http://i.imgur.com/' + src,
        // end

        onMaskImageCreate: function(img) {
          // Mask image positions
          img.css({
            "position": "absolute",
            "left": x + "px",
            "top": y + "px"
          });
          // end

        },
        id: counter
      });
      // here
      table.push(mask);
      fileup.onchange = function() {

        let mask2 = table[target];
        const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
        document.getElementById('fileup').value = "";

      };
      counter++;
    }
    return mask;
  }
  mask = json(jsonData);
}); // end of function

// Image code

(function($) {
  window.JQmasks = [];
  $.fn.mask = function(options) {
    // This is the easiest way to have default options.
    var settings = $.extend({
      // These are the defaults.
      maskImageUrl: undefined,
      imageUrl: undefined,
      scale: 1,
      id: new Date().getUTCMilliseconds().toString(),
      x: 0, // image start position
      y: 0, // image start position
      onMaskImageCreate: function(div) {},
    }, options);

    // Create the image properties
    settings.maskImage = new Image
    settings.image = new Image

    // set the cross-origin attributes
    settings.maskImage.setAttribute('crossOrigin', 'anonymous');
    settings.image.setAttribute('crossOrigin', 'anonymous');

    settings.maskImage.onload = function() {
      // once the mask is loaded, load the image
      container.loadImage(settings.imageUrl)
      container.drawMask()
    }

    settings.image.onload = function() {
      // once the image is loaded, render to canvas

      container.drawImage()
    }

    var container = $(this);

    let prevX = 0,
      prevY = 0,
      draggable = false,
      img,
      canvas,
      context,
      image,
      timeout,
      initImage = false,
      startX = settings.x,
      startY = settings.y,
      div;

    container.drawMask = function() {
      if (!settings.maskImage) return true;
      canvas.width = settings.maskImage.width;
      canvas.height = settings.maskImage.height;
      context.save();
      context.beginPath();
      context.globalCompositeOperation = "source-over";
      // draw the masked image after scaling
      if (settings.maskImage) context.drawImage(settings.maskImage, 0, 0, settings.maskImage.width, settings.maskImage.height);
      context.restore()
    };

    container.drawImage = function() {

      const img = settings.image

      settings.x = (canvas.width - (img.width * settings.scale)) / 2
      settings.y = (canvas.height - (img.height * settings.scale)) / 2

      context.globalCompositeOperation = 'source-atop';
      if (img) context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
      context.restore()
      initImage = false;
    }

    // change the draggable image

    container.loadImage = function(imageUrl) {
      if (!imageUrl) return true;
      settings.y = startY;
      settings.x = startX;
      prevX = prevY = 0;

      initImage = true;

      settings.image.src = imageUrl; // CHANGED

      // sirpepole Add this
      return settings.id;
    };

    container.loadMaskImage = function(imageUrl, from) {

      canvas = document.createElement("canvas");
      context = canvas.getContext('2d');
      canvas.setAttribute("draggable", "true");
      canvas.setAttribute("id", settings.id);
      // settings.maskImageUrl = imageUrl;
      settings.maskImage.src = imageUrl // CHANGED

      div = $("
", {
        "class": "masked-img"
      }).append(canvas);

      // div.find("canvas").on('touchstart mousedown', function(event)
      div.find("canvas").on('dragstart', function(event) {
        if (event.handled === false) return;
        event.handled = true;
        container.onDragStart(event);
      });

      div.find("canvas").on('touchend mouseup', function(event) {
        if (event.handled === false) return;
        event.handled = true;
        container.selected(event);
      });

      div.find("canvas").bind("dragover", container.onDragOver);

      container.append(div);
      if (settings.onMaskImageCreate)
        settings.onMaskImageCreate(div);

      // container.loadImage(settings.imageUrl);
      // Moved this to the settings.maskImage.onload
    };
    if (settings.maskImageUrl) {
      container.loadMaskImage(settings.maskImageUrl);
    }
    JQmasks.push({
      item: container,
      id: settings.id
    })
    // Edit image
    div.addClass('masked-img' + settings.id);
    div.attr('data-id', settings.id);
    // ends
    return container;
  };
}(jQuery));

.container {
  background: silver;
  position: relative;
}

.container img {
  position: absolute;
  top: 0;
  bottom: 250px;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 999;
}

.masked-img {
  overflow: hidden;
  position: relative;
}

<input id="fileup" name="fileup" type="file" style="display:none" />

Here is Codepen, Fiddle & Full code in pastebin

We implemented similar feature that displaying "+" icon only on mask images....

Body:
You are getting the data of one pixel and it returns a Uint8ClampedArray which is 4 bytes long.

var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;

Now these 4 bytes represent the R, G, B and A value of the pixel. The pixels[3] represents the Alpha value which can be 255 easily for most of the images.

If you want to make sure that only the White pixels should trigger the action, you should check for R, G and B for 255.

if (pixel[0] === 255 && pixel[1] === 255 && pixel[2] === 255) {
     setTimeout(() => {
         $('#fileup').click();
     }, 20);
}

Hint:

There is a design flaw in your program. That is, if your image (the car or anything) has White pixels and the user clicks on one of them, the action would be taken. You should check for a clicks on the mask region and then look for White pixels.


来源: stackexchange

问:
PyQt5 focusing on readonly QLineEdit widgets
I have 3 QLineEdit widgets that are readonly and listen to keyevents. Well I want to let the user to choose what QLineEdit he is going to use(because it's going to be a shortcut setting window). It appears when in readonly mode the widget is non-clickable. Is there a way to make it clickable or do the same thing without readonly?

I made the code in Qt Designer.

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

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(392, 290)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(140, 70, 113, 21))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
        MainWindow.keyPressEvent = self.newOnkeyPressEvent1

        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(140, 150, 113, 21))
        self.lineEdit_2.setReadOnly(True)
        self.lineEdit_2.setAlignment(QtCore.Qt.AlignCenter)
        MainWindow.keyPressEvent = self.newOnkeyPressEvent2
        self.lineEdit_2.setObjectName("lineEdit_2")

        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(140, 220, 113, 21))
        self.lineEdit_3.setReadOnly(True)
        self.lineEdit_3.setAlignment(QtCore.Qt.AlignCenter)
        MainWindow.keyPressEvent = self.newOnkeyPressEvent3
        self.lineEdit_3.setObjectName("lineEdit_3")

        MainWindow.setCentralWidget(self.centralwidget)

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

    def newOnkeyPressEvent1(self, event):
        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        self.lineEdit.setText(str(keyname))

    def newOnkeyPressEvent2(self, event):
        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        self.lineEdit_2.setText(str(keyname))

    def newOnkeyPressEvent3(self, event):
        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        self.lineEdit_3.setText(str(keyname))

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

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

答:
You need to determine which lineedit is under focus with self.centralwidget.focusWidget(). Here is full working code:

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

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(392, 290)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(140, 70, 113, 21))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)

        MainWindow.keyPressEvent = self.newOnkeyPressEvent

        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(140, 150, 113, 21))
        self.lineEdit_2.setReadOnly(True)
        self.lineEdit_2.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit_2.setObjectName("lineEdit_2")

        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(140, 220, 113, 21))
        self.lineEdit_3.setReadOnly(True)
        self.lineEdit_3.setAlignment(QtCore.Qt.AlignCenter)

        self.lineEdit_3.setObjectName("lineEdit_3")

        MainWindow.setCentralWidget(self.centralwidget)

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

    def newOnkeyPressEvent(self, event):
        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        lineEdit = self.centralwidget.focusWidget()
        lineEdit.setText(str(keyname))

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

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

ContentLicense: CC BY-SA 4.0

Body:
I have 3 QLineEdit widgets that are readonly and listen to keyevents. Well I want to let the user to choose what QLineEdit he is going to use(because it's going to be a shortcut setting window). It appears when in readonly mode the widget is non-clickable. Is there a way to make it clickable or do the same thing without readonly?

I made the code in Qt Designer.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(392, 290)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(140, 70, 113, 21))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
        MainWindow.keyPressEvent = self.newOnkeyPressEvent1

        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(140, 150, 113, 21))
        self.lineEdit_2.setReadOnly(True)
        self.lineEdit_2.setAlignment(QtCore.Qt.AlignCenter)
        MainWindow.keyPressEvent = self.newOnkeyPressEvent2
        self.lineEdit_2.setObjectName("lineEdit_2")

        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(140, 220, 113, 21))
        self.lineEdit_3.setReadOnly(True)
        self.lineEdit_3.setAlignment(QtCore.Qt.AlignCenter)
        MainWindow.keyPressEvent = self.newOnkeyPressEvent3
        self.lineEdit_3.setObjectName("lineEdit_3")

        MainWindow.setCentralWidget(self.centralwidget)

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

    def newOnkeyPressEvent1(self, event):
        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        self.lineEdit.setText(str(keyname))

    def newOnkeyPressEvent2(self, event):
        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        self.lineEdit_2.setText(str(keyname))

    def newOnkeyPressEvent3(self, event):
        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        self.lineEdit_3.setText(str(keyname))

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

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

Body:
You need to determine which lineedit is under focus with self.centralwidget.focusWidget(). Here is full working code:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(392, 290)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(140, 70, 113, 21))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)

        MainWindow.keyPressEvent = self.newOnkeyPressEvent

        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(140, 150, 113, 21))
        self.lineEdit_2.setReadOnly(True)
        self.lineEdit_2.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit_2.setObjectName("lineEdit_2")

        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(140, 220, 113, 21))
        self.lineEdit_3.setReadOnly(True)
        self.lineEdit_3.setAlignment(QtCore.Qt.AlignCenter)

        self.lineEdit_3.setObjectName("lineEdit_3")

        MainWindow.setCentralWidget(self.centralwidget)

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

    def newOnkeyPressEvent(self, event):
        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        lineEdit = self.centralwidget.focusWidget()
        lineEdit.setText(str(keyname))

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

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


问:
Getting text search relevance scores out of ArangoDB?
Does ArangoDB provide a way of getting the underlying scores out of text search queries, either through AQL queries against fulltext index or via a custom search view?

One use case for this is to colour search results based on their relevance in a UI.

答:
```<code>FOR doc IN myView
    SEARCH PHRASE(doc.abstract,"fulltext search","text_en")
        OR PHRASE(doc.text,"fulltext search","text_en")
    SORT BM25(doc)
    LIMIT 10
    RETURN { id: doc._key, title: doc.title, score: bm25(doc) }
</code>```

This would return the top 10 results with the BM25 score (TF/IDF is supported as well) that you can use for highlighting individual records.

I think the support of scores in return values was introduced just recently. I am currently testing 3.5.

Body:
FOR doc IN myView
    SEARCH PHRASE(doc.abstract,"fulltext search","text_en")
        OR PHRASE(doc.text,"fulltext search","text_en")
    SORT BM25(doc)
    LIMIT 10
    RETURN { id: doc._key, title: doc.title, score: bm25(doc) }

This would return the top 10 results with the BM25 score (TF/IDF is supported as well) that you can use for highlighting individual records.

I think the support of scores in return values was introduced just recently. I am currently testing 3.5.


问:
App should go to a different route when fetched dropdown values are clicked
I'm trying to redirect users in my react app to a certain route in my app or a site say google when you pick the value from the dropdown. I'm populating the dropdown by fetching the data from an api

I've tried adding an If then returning the fetched data from the api but that only renders the the value specified in the if as shown below.

```<code>if (item.Name === 'MTN') {
  console.log('works');
  return <option value="/">{item.Name}</option>;
}
</code>```

```<code>componentDidMount() {
  getTheSimProviders().then(data => {
    console.log(data);
    if (this._isMounted) {
      this.setState({
        isLoaded: false,
      });
    } else {
      this.setState({
        isLoaded: true,
        airtime: data[0].Merchants,
      });
    }
  });
}
</code>```

Method that redirects a user once an item from the dropdown is selected:

```<code>onUrlSelected(e) {
  console.log(`The value is: ${e.target.value}`);
  window.location = `${e.target.value}`;
}
</code>```

How I'm rendering the data from the dropdown:

```<code><div className="row">
  <h3 className="select-headings">Airtime & Data</h3>
  <select onChange={this.onUrlSelected} className="select">
    {this.state.airtime.map(item => {
      if (item.Name === 'MTN') {
        console.log('to jesus be my glory');
      }
      return <option value="/">{item.Name}</option>;
    })}
  </select>
</div>
</code>```

I would also appreciate if someone could show me how to do it onsubmit with a button

答:
You can use onsubmit on tag form and add a button into the form to submit it.

```<code><form onSubmit={this.onUrlSelected}>
   <select  className="select">
     {this.state.airtime.map(item =>
        <option key={item.key} value="/">{item.Name}</option>;
     })}
   </select>
  <button>Send</button>
</form>
</code>```

Don't forget to use a unique key for each item on map function.

Body:
I'm trying to redirect users in my react app to a certain route in my app or a site say google when you pick the value from the dropdown. I'm populating the dropdown by fetching the data from an api

I've tried adding an If then returning the fetched data from the api but that only renders the the value specified in the if as shown below.

if (item.Name === 'MTN') {
  console.log('works');
  return <option value="/">{item.Name}</option>;
}

componentDidMount() {
  getTheSimProviders().then(data => {
    console.log(data);
    if (this._isMounted) {
      this.setState({
        isLoaded: false,
      });
    } else {
      this.setState({
        isLoaded: true,
        airtime: data[0].Merchants,
      });
    }
  });
}

Method that redirects a user once an item from the dropdown is selected:

onUrlSelected(e) {
  console.log(`The value is: ${e.target.value}`);
  window.location = `${e.target.value}`;
}

How I'm rendering the data from the dropdown:

Airtime & Data

  <select onChange={this.onUrlSelected} className="select">
    {this.state.airtime.map(item => {
      if (item.Name === 'MTN') {
        console.log('to jesus be my glory');
      }
      return <option value="/">{item.Name}</option>;
    })}
  </select>

I would also appreciate if someone could show me how to do it onsubmit with a button

Body:
You can use onsubmit on tag form and add a button into the form to submit it.

<form onSubmit={this.onUrlSelected}>
   <select  className="select">
     {this.state.airtime.map(item =>
        <option key={item.key} value="/">{item.Name}</option>;
     })}
   </select>
  <button>Send</button>
</form>

Don't forget to use a unique key for each item on map function.


问:
Can SVN copy and override the target branch or merge and keep the source branch?
I am new to SVN. I found when you merge branch A to branch B, SVN moves all content in branch A to B, not copy. And when you copy branch A to branch C and when you do the same thing again, it gave you an error branch C already exists.

What I want to accomplish is:

first I have a branch/dev – for development

then copy branch/dev to branch/test – for function test

then copy branch/test to trunk – for stage

then tag to production.

Since I cannot override the existing branch, when I want to copy branch/dev again, I need to delete test first, which is inconvenient.

Is there a way to do it?

答:
svn merge does not "move all content". In fact, "merging" and "copying" is in Subversion to very different operations. Merging will take the changes made in a branch and merge them into a working copy:

```<code>$ cd my/working/copy
$ svn merge ^/branches/myfeaturebranch .
</code>```

Will merge all (unmerged) changes from ^/branches/myfeaturebranch into my/working/copy. This will leave you with a working copy containing all the changes from /branches/myfeaturebranch which you are attempting to merge. At this point you may also have conflicts which you need to resolve before committing. (Note that the final act of merging is simply committing a bunch of changes.)

Copying, on the other hand, is like cp -r SRC DST, where SRC and DST may either be local filesystem paths or repository URLs. When doing a repo-to-repo copy, Subversion will copy (not merge) all changes from SRC to DST. For example:

```<code>$ svn copy ^/trunk ^/tags/1.0.0
</code>```

This will copy (or "tag") the current trunk to ^/tags/1.0.0. If the destination already exists, Subversion will refuse to overwrite it.

So, what you want to do is probably something like

```<code>$ svn copy ^/trunk ^/branches/dev # create dev branch from trunk
$ svn co ^/branches/dev # checkout dev branch
$ cd dev
$ .... hack away ....
$ svn commit .... # commit your development changes
$ svn copy ^/branches/dev/ ^/branches/test # create testing branch
$ svn switch ^/branches/test # switch to testing branch
$ .... perform tests ....
$ svn commit .... # commit your changes in the testing branch
$ svn switch ^/trunk # switch back to trunk
$ svn merge ^/branches/test . # merge testing changes into working copy for trunk
$ .... resolve any conflicts ....
$ svn commit .... # commit merge
$ svn copy ^/trunk ^/tags/1.0.0 # final production tag
</code>```

Hope this straightens out things a little.

ContentLicense: CC BY-SA 3.0

Body:
svn merge does not "move all content". In fact, "merging" and "copying" is in Subversion to very different operations. Merging will take the changes made in a branch and merge them into a working copy:

$ cd my/working/copy
$ svn merge ^/branches/myfeaturebranch .

Will merge all (unmerged) changes from ^/branches/myfeaturebranch into my/working/copy. This will leave you with a working copy containing all the changes from /branches/myfeaturebranch which you are attempting to merge. At this point you may also have conflicts which you need to resolve before committing. (Note that the final act of merging is simply committing a bunch of changes.)

Copying, on the other hand, is like cp -r SRC DST, where SRC and DST may either be local filesystem paths or repository URLs. When doing a repo-to-repo copy, Subversion will copy (not merge) all changes from SRC to DST. For example:

$ svn copy ^/trunk ^/tags/1.0.0

This will copy (or "tag") the current trunk to ^/tags/1.0.0. If the destination already exists, Subversion will refuse to overwrite it.

So, what you want to do is probably something like

$ svn copy ^/trunk ^/branches/dev # create dev branch from trunk
$ svn co ^/branches/dev # checkout dev branch
$ cd dev
$ .... hack away ....
$ svn commit .... # commit your development changes
$ svn copy ^/branches/dev/ ^/branches/test # create testing branch
$ svn switch ^/branches/test # switch to testing branch
$ .... perform tests ....
$ svn commit .... # commit your changes in the testing branch
$ svn switch ^/trunk # switch back to trunk
$ svn merge ^/branches/test . # merge testing changes into working copy for trunk
$ .... resolve any conflicts ....
$ svn commit .... # commit merge
$ svn copy ^/trunk ^/tags/1.0.0 # final production tag

Hope this straightens out things a little.


问:
increase swagger requestTimeout
is there anyway that can help me increase the timeout of the swagger request that i issue to my RestAPI using " Try it out" of swagger ?

i roamed the internet and disn't find something usefull, and i tried to add things to my yml conf files, but i didn't know what to write

i expected to find something like this maybe :

```<code>swagger.timeout=5000
</code>```

i have a spring boot application using swagger in order to test my webservices in a restController. i have a treatement that takes about 30 seconds, the thing that makes swagger throw a 500 timeout error for me.

thanks !

答:
As far as I know, Swagger registers its endpoints as normal Spring controllers so use the underlying web container to serve its traffic.

Try to increase the global connection timeout:

```<code>server.connection-timeout=120000
</code>```

Time that connectors wait for another HTTP request before closing the connection. When not set, the connector's container-specific default is used. Use a value of -1 to indicate no (that is, an infinite) timeout.

Title: increase swagger requestTimeout

Body:
is there anyway that can help me increase the timeout of the swagger request that i issue to my RestAPI using " Try it out" of swagger ?

i roamed the internet and disn't find something usefull, and i tried to add things to my yml conf files, but i didn't know what to write

i expected to find something like this maybe :

swagger.timeout=5000

i have a spring boot application using swagger in order to test my webservices in a restController. i have a treatement that takes about 30 seconds, the thing that makes swagger throw a 500 timeout error for me.

thanks !

Body:
As far as I know, Swagger registers its endpoints as normal Spring controllers so use the underlying web container to serve its traffic.

Try to increase the global connection timeout:

server.connection-timeout=120000

Time that connectors wait for another HTTP request before closing the connection. When not set, the connector's container-specific default is used. Use a value of -1 to indicate no (that is, an infinite) timeout.


问:
Why are these two SQL date functions not providing the same answer
I've actually already solved the problem, but I'm trying to understand why the problem occurred because as far as I can see it has no reason to happen.
I have a rather large query that I run to prepare a table with some often used combinations. Generally, it only contains 2 years of data. Occasionally I will reconstruct it. While doing this I tweaked the query to add more information, but suddenly the result no longer matched up to the old query. Comparing the old to the new I noticed several missing orders. Amazingly, even after removing the tweaked parts the results still didn't match up.

I ultimately tracked the problem down to my WHERE clause, which was different from how I did it last time.

The type of the orderdate column I go over has type (datetime, null)

One of the orders that was omitted had this as date:

```<code>2018-12-23 20:58:52.383
</code>```

An order that was included had this as date:

```<code>2019-01-28 15:20:49.107
</code>```

It looks exactly the same to me.

The entire query is the same, except for the WHERE clause. My original where was:

```<code>WHERE DATEPART(yyyy,tbOrder.[OrderDate]) >= DATEPART(yyyy,GETDATE()-2)
</code>```

My new where is now:

```<code>WHERE tborder.[OrderDate] >= DATEADD(yy, DATEDIFF(yy, 0, GETDATE())-2, 0)
</code>```

Any help in understanding why the original where clause drops some lines would be greatly appreciated.

答:
Because you are doing two different things. First predicate,

```<code>WHERE DATEPART(yyyy,tbOrder.[OrderDate]) >= DATEPART(yyyy,GETDATE()-2)
</code>```

Take all order dates that are bigger than the year for the day before yesterday or two days before. Notice that, -2 is inside the brackets.

Second predicate,

```<code>WHERE tborder.[OrderDate] >= DATEADD( yy, DATEDIFF( yy, 0, GETDATE() ) - 2, 0)
</code>```

Take all order dates bigger than two years before, i.e., datediff(yy,startdate,enddate) will return the year result of the difference between today and the initial value for date datatype, which is 1900-01-01. Then, add this, -2, to 1900-01-01. The second expression is the form of:

1900 + ( 201X - 1898 )

I simplified 1900 - 2 = 1898.

Body:
I've actually already solved the problem, but I'm trying to understand why the problem occurred because as far as I can see it has no reason to happen.
I have a rather large query that I run to prepare a table with some often used combinations. Generally, it only contains 2 years of data. Occasionally I will reconstruct it. While doing this I tweaked the query to add more information, but suddenly the result no longer matched up to the old query. Comparing the old to the new I noticed several missing orders. Amazingly, even after removing the tweaked parts the results still didn't match up.

I ultimately tracked the problem down to my WHERE clause, which was different from how I did it last time.

The type of the orderdate column I go over has type (datetime, null)

One of the orders that was omitted had this as date:

2018-12-23 20:58:52.383

An order that was included had this as date:

2019-01-28 15:20:49.107

It looks exactly the same to me.

The entire query is the same, except for the WHERE clause. My original where was:

WHERE DATEPART(yyyy,tbOrder.[OrderDate]) >= DATEPART(yyyy,GETDATE()-2)

My new where is now:

WHERE tborder.[OrderDate] >= DATEADD(yy, DATEDIFF(yy, 0, GETDATE())-2, 0)

Any help in understanding why the original where clause drops some lines would be greatly appreciated.

Body:
Because you are doing two different things. First predicate,

WHERE DATEPART(yyyy,tbOrder.[OrderDate]) >= DATEPART(yyyy,GETDATE()-2)

Take all order dates that are bigger than the year for the day before yesterday or two days before. Notice that, -2 is inside the brackets.

Second predicate,

WHERE tborder.[OrderDate] >= DATEADD( yy, DATEDIFF( yy, 0, GETDATE() ) - 2, 0)

Take all order dates bigger than two years before, i.e., datediff(yy,startdate,enddate) will return the year result of the difference between today and the initial value for date datatype, which is 1900-01-01. Then, add this, -2, to 1900-01-01. The second expression is the form of:

1900 + ( 201X - 1898 )

I simplified 1900 - 2 = 1898.


问:
How to read a string line into double columns and save them in a method
I need to read the following line of string into separate columns with type of double and then save these columns in a method named setPosition. The string line is

```<code>[1,1,0,0,0,1,0,1,0,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1,0,0,1,0,1,0,1,0,0,0,1,0]
</code>```

which is stored in a file named hh.

I use the next code for doing this task but still have a problem.

```<code>for (int i = 0; i < getSize(); ++i){
    File file1 = new File("hh.txt");
           try {
                Scanner scan = new Scanner(file1);
                while (scan.hasNextLine()) {
                    String line1 = scan.nextLine();
                   line1 = line1.replaceAll("\\[","");
                   line1 = line1.replaceAll("\\]","");
                  String[] columns = line1.split(",");
                double new_columns = Double.parseDouble(columns[i]);
                    setPosition(i, new_columns);
        }
           }
           catch (FileNotFoundException e) {
                e.printStackTrace();
            }

}
</code>```

i got the following error

```<code>Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:635)
    at java.util.ArrayList.get(ArrayList.java:411)
    at PSOFS.Swarm1.getParticle(Swarm1.java:39)
    at PSOFS.Main.main(Main.java:181)
Java Result: 1
</code>```

答:
To get the values in a double[] you just need to read once, and parse. Now you're reading in a loop, so you open an read the file multiple times for nothing

open file and read content

remove undesired chars, and split on comma

parse each value do touble

Then you do whatever you want with the values

```<code>File file1 = new File("hh.txt");
Scanner scan = new Scanner(file1);
String[] values = scan.nextLine().replace("[", "").replace("]", "").split(",");
double[] valuesD = new double[values.length];

for (int i = 0; i < values.length; ++i){
    valuesD[i] = Double.parseDouble(values[i]);
}
</code>```

>> Demo <<

Body:
I need to read the following line of string into separate columns with type of double and then save these columns in a method named setPosition. The string line is

[1,1,0,0,0,1,0,1,0,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1,0,0,1,0,1,0,1,0,0,0,1,0]

which is stored in a file named hh.

I use the next code for doing this task but still have a problem.

for (int i = 0; i < getSize(); ++i){
    File file1 = new File("hh.txt");
           try {
                Scanner scan = new Scanner(file1);
                while (scan.hasNextLine()) {
                    String line1 = scan.nextLine();
                   line1 = line1.replaceAll("\\[","");
                   line1 = line1.replaceAll("\\]","");
                  String[] columns = line1.split(",");
                double new_columns = Double.parseDouble(columns[i]);
                    setPosition(i, new_columns);
        }
           }
           catch (FileNotFoundException e) {
                e.printStackTrace();
            }

}

i got the following error

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:635)
    at java.util.ArrayList.get(ArrayList.java:411)
    at PSOFS.Swarm1.getParticle(Swarm1.java:39)
    at PSOFS.Main.main(Main.java:181)
Java Result: 1

Body:
To get the values in a double[] you just need to read once, and parse. Now you're reading in a loop, so you open an read the file multiple times for nothing

open file and read content

remove undesired chars, and split on comma

parse each value do touble

Then you do whatever you want with the values

File file1 = new File("hh.txt");
Scanner scan = new Scanner(file1);
String[] values = scan.nextLine().replace("[", "").replace("]", "").split(",");
double[] valuesD = new double[values.length];

for (int i = 0; i < values.length; ++i){
    valuesD[i] = Double.parseDouble(values[i]);
}

>> Demo <<


问:
When I import the date from mockaroo.com, the date shows but the time is missing
I imported my data from mockaroo.com and when I run it using DBeaver PostgreSQL, the hour is missing when I try to extract it.

```<code>create table t7 (
    id INT,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(50),
    gender VARCHAR(50),
    thedate DATE
);

insert into t7 (id, first_name, last_name, email, gender, thedate) values (1, 'Lise', 'Scading', 'lscading0@yandex.ru', 'Female', '2018-11-17 07:24:03');
insert into t7 (id, first_name, last_name, email, gender, thedate) values (2, 'Pall', 'Tilbrook', 'ptilbrook1@whitehouse.gov', 'Male', '2019-04-17 15:04:51');

SELECT id, thedate, extract(hour from thedate)
FROM t7
</code>```

date_part says 0 which is clearly wrong.

Here is a video I made which shows what I'm talking about.

答:
Looking at the CREATE statement, I can see the datatype used for you column is DATE - this does not store the time. Try using TIMESTAMP or some other Date/Time type that will store time as well when creating the table.

```<code>create table t7 (
    id INT,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(50),
    gender VARCHAR(50),
    thedate TIMESTAMP
);
</code>```

Body:
I imported my data from mockaroo.com and when I run it using DBeaver PostgreSQL, the hour is missing when I try to extract it.

create table t7 (
    id INT,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(50),
    gender VARCHAR(50),
    thedate DATE
);

insert into t7 (id, first_name, last_name, email, gender, thedate) values (1, 'Lise', 'Scading', 'lscading0@yandex.ru', 'Female', '2018-11-17 07:24:03');
insert into t7 (id, first_name, last_name, email, gender, thedate) values (2, 'Pall', 'Tilbrook', 'ptilbrook1@whitehouse.gov', 'Male', '2019-04-17 15:04:51');

SELECT id, thedate, extract(hour from thedate)
FROM t7

date_part says 0 which is clearly wrong.

Here is a video I made which shows what I'm talking about.

Body:
Looking at the CREATE statement, I can see the datatype used for you column is DATE - this does not store the time. Try using TIMESTAMP or some other Date/Time type that will store time as well when creating the table.

create table t7 (
    id INT,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(50),
    gender VARCHAR(50),
    thedate TIMESTAMP
);


问:
nodejs-0.4.2 segfault on start (Fixed in v 0.4.5)
Greetings, to save your time this bug was fixed in v0.4.5
I ran into a rather weird problem while installing node.js today and sifted through the mail archives but couldn't quite pin it!. so I posted the problem to nodejs here

just a heads up that I changed snapshot='snapshot=on' from wscript in
Node to snapshot=''.
I did this because prior to doing this I encountered the following
error during make:

scons: *** [obj/release/snapshot.cc] Error -11

Now to the steps I followed.

*logged in as root

---Start of configure

```<code>adil-X:/usr/local/nodejs/node-v0.4.2 # ./configure --prefix=/usr/local/nodejs
Checking for program g++ or c++          : /usr/bin/g++
Checking for program cpp                 : /usr/bin/cpp
Checking for program ar                  : /usr/bin/ar
Checking for program ranlib              : /usr/bin/ranlib
Checking for g++                         : ok
Checking for program gcc or cc           : /usr/bin/gcc
Checking for program ar                  : /usr/bin/ar
Checking for program ranlib              : /usr/bin/ranlib
Checking for gcc                         : ok
Checking for library dl                  : yes
Checking for openssl                     : yes
Checking for library util                : yes
Checking for library rt                  : yes
--- libeio ---
Checking for library pthread             : yes
Checking for function pthread_create     : yes
Checking for function pthread_atfork     : yes
Checking for futimes(2)                  : yes
Checking for readahead(2)                : yes
Checking for fdatasync(2)                : yes
Checking for pread(2) and pwrite(2)      : yes
Checking for sendfile(2)                 : yes
Checking for sync_file_range(2)          : yes
--- libev ---
Checking for header sys/inotify.h        : yes
Checking for function inotify_init       : yes
Checking for header sys/epoll.h          : yes
Checking for function epoll_ctl          : yes
Checking for header port.h               : not found
Checking for header poll.h               : yes
Checking for function poll               : yes
Checking for header sys/event.h          : not found
Checking for header sys/queue.h          : yes
Checking for function kqueue             : not found
Checking for header sys/select.h         : yes
Checking for function select             : yes
Checking for header sys/eventfd.h        : yes
Checking for function eventfd            : yes
Checking for SYS_clock_gettime           : yes
Checking for library rt                  : yes
Checking for function clock_gettime      : yes
Checking for function nanosleep          : yes
Checking for function ceil               : yes
Checking for fdatasync(2) with c++       : yes
'configure' finished successfully (2.239s)
</code>```

----End of configure

----Start of make(this compiles fine!!)

[make output omitted for brevity]

Waf: Leaving directory /usr/local/nodejs/node-v0.4.2/build'

'build' finished successfully (21.853s)

-----End of make

-----Start of make test

```<code>/usr/bin/python "/usr/local/nodejs/node-v0.4.2/tools/scons/scons.py" -
j 2 -C "/usr/local/nodejs/node-v0.4.2/build/default/" -Y "/usr/local/
nodejs/node-v0.4.2/deps/v8" visibility=default mode=release arch=ia32
toolchain=gcc library=static

scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
scons: `library' is up to date.
scons: done building targets.
DEST_OS: linux
DEST_CPU: ia32
Parallel Jobs: 2

Product type: program
python tools/test.py --mode=release simple message
[00:00|%   0|+   0|-   0]: release test-pipe-
head                                                  === release test-
pipe-head ===
Path: simple/test-pipe-head
Command: build/default/node /usr/local/nodejs/node-v0.4.2/test/simple/
test-pipe-head.js
--- CRASHED ---
</code>```

...
All of the subsequent tests fail in a similar fashion.

-----End of make test

-----Start of make install (I did not execute make test on the first few tries.it was only later that I used it)

```<code>adil-X:/usr/local/nodejs/node-v0.4.2 # make install

Waf: Entering directory `/usr/local/nodejs/node-v0.4.2/build'
DEST_OS: linux
DEST_CPU: ia32
Parallel Jobs: 2
Product type: program
* installing build/default/config.h as /usr/local/nodejs/include/node/
config.h
* installing build/default/tools/nodejs.pc as /usr/local/nodejs/lib/
pkgconfig/nodejs.pc
* installing build/default/node as /usr/local/nodejs/bin/node
* installing build/default/src/node_config.h as /usr/local/nodejs/
include/node/node_config.h
Waf: Leaving directory `/usr/local/nodejs/node-v0.4.2/build'
'install' finished successfully (0.122s)
</code>```

-----End of make install

I updated the PATH variable to include the nodejs bin.

Now nodejs crashes with following error on startup

```<code>adil-X:/usr/local/nodejs/node-v0.4.2 # node example.js

node.js:0
Segmentation fault
</code>```

still, I can see the node.js version

```<code>adil-X:~ # node -v
v0.4.2
</code>```

OS/Arch info:

```<code>adil-X:~ # cat /etc/*release
LSB_VERSION="core-2.0-noarch:core-3.2-noarch:core-4.0-noarch:core-2.0-
ia32:core-3.2-ia32:core-4.0-ia32"
openSUSE 11.3 (i586)

adil-X:~ # cat /proc/cpuinfo
vendor_id    :GenuineIntel
cpu family    : 6
model          : 23
model name  : Intel(R) Core(TM)2 Duo CPU     T6500  @ 2.10GHz
stepping       : 10
cpu MHz       : 1200.000
cache size     : 2048 KB
</code>```

With no errors on the way when building from source, I am unable to
figure out the problem.
am I missing something obvious? thanks.

答: problem fixed in nodejs-v0.4.5.no hassle at all. Maybe there was really a bug in nodejs-v0.4.2 afterall.

Body:
Greetings, to save your time this bug was fixed in v0.4.5
I ran into a rather weird problem while installing node.js today and sifted through the mail archives but couldn't quite pin it!. so I posted the problem to nodejs here

just a heads up that I changed snapshot='snapshot=on' from wscript in
Node to snapshot=''.
I did this because prior to doing this I encountered the following
error during make:

scons: *** [obj/release/snapshot.cc] Error -11

Now to the steps I followed.

*logged in as root

---Start of configure

adil-X:/usr/local/nodejs/node-v0.4.2 # ./configure --prefix=/usr/local/nodejs
Checking for program g++ or c++          : /usr/bin/g++
Checking for program cpp                 : /usr/bin/cpp
Checking for program ar                  : /usr/bin/ar
Checking for program ranlib              : /usr/bin/ranlib
Checking for g++                         : ok
Checking for program gcc or cc           : /usr/bin/gcc
Checking for program ar                  : /usr/bin/ar
Checking for program ranlib              : /usr/bin/ranlib
Checking for gcc                         : ok
Checking for library dl                  : yes
Checking for openssl                     : yes
Checking for library util                : yes
Checking for library rt                  : yes
--- libeio ---
Checking for library pthread             : yes
Checking for function pthread_create     : yes
Checking for function pthread_atfork     : yes
Checking for futimes(2)                  : yes
Checking for readahead(2)                : yes
Checking for fdatasync(2)                : yes
Checking for pread(2) and pwrite(2)      : yes
Checking for sendfile(2)                 : yes
Checking for sync_file_range(2)          : yes
--- libev ---
Checking for header sys/inotify.h        : yes
Checking for function inotify_init       : yes
Checking for header sys/epoll.h          : yes
Checking for function epoll_ctl          : yes
Checking for header port.h               : not found
Checking for header poll.h               : yes
Checking for function poll               : yes
Checking for header sys/event.h          : not found
Checking for header sys/queue.h          : yes
Checking for function kqueue             : not found
Checking for header sys/select.h         : yes
Checking for function select             : yes
Checking for header sys/eventfd.h        : yes
Checking for function eventfd            : yes
Checking for SYS_clock_gettime           : yes
Checking for library rt                  : yes
Checking for function clock_gettime      : yes
Checking for function nanosleep          : yes
Checking for function ceil               : yes
Checking for fdatasync(2) with c++       : yes
'configure' finished successfully (2.239s)

----End of configure

----Start of make(this compiles fine!!)

[make output omitted for brevity]

Waf: Leaving directory /usr/local/nodejs/node-v0.4.2/build'

'build' finished successfully (21.853s)

-----End of make

-----Start of make test

/usr/bin/python "/usr/local/nodejs/node-v0.4.2/tools/scons/scons.py" -
j 2 -C "/usr/local/nodejs/node-v0.4.2/build/default/" -Y "/usr/local/
nodejs/node-v0.4.2/deps/v8" visibility=default mode=release arch=ia32
toolchain=gcc library=static

scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
scons: `library' is up to date.
scons: done building targets.
DEST_OS: linux
DEST_CPU: ia32
Parallel Jobs: 2

Product type: program
python tools/test.py --mode=release simple message
[00:00|%   0|+   0|-   0]: release test-pipe-
head                                                  === release test-
pipe-head ===
Path: simple/test-pipe-head
Command: build/default/node /usr/local/nodejs/node-v0.4.2/test/simple/
test-pipe-head.js
--- CRASHED ---

...
All of the subsequent tests fail in a similar fashion.

-----End of make test

-----Start of make install (I did not execute make test on the first few tries.it was only later that I used it)

adil-X:/usr/local/nodejs/node-v0.4.2 # make install

Waf: Entering directory `/usr/local/nodejs/node-v0.4.2/build'
DEST_OS: linux
DEST_CPU: ia32
Parallel Jobs: 2
Product type: program
* installing build/default/config.h as /usr/local/nodejs/include/node/
config.h
* installing build/default/tools/nodejs.pc as /usr/local/nodejs/lib/
pkgconfig/nodejs.pc
* installing build/default/node as /usr/local/nodejs/bin/node
* installing build/default/src/node_config.h as /usr/local/nodejs/
include/node/node_config.h
Waf: Leaving directory `/usr/local/nodejs/node-v0.4.2/build'
'install' finished successfully (0.122s)

-----End of make install

I updated the PATH variable to include the nodejs bin.

Now nodejs crashes with following error on startup

adil-X:/usr/local/nodejs/node-v0.4.2 # node example.js

node.js:0
Segmentation fault

still, I can see the node.js version

adil-X:~ # node -v
v0.4.2

OS/Arch info:

adil-X:~ # cat /etc/*release
LSB_VERSION="core-2.0-noarch:core-3.2-noarch:core-4.0-noarch:core-2.0-
ia32:core-3.2-ia32:core-4.0-ia32"
openSUSE 11.3 (i586)

adil-X:~ # cat /proc/cpuinfo
vendor_id    :GenuineIntel
cpu family    : 6
model          : 23
model name  : Intel(R) Core(TM)2 Duo CPU     T6500  @ 2.10GHz
stepping       : 10
cpu MHz       : 1200.000
cache size     : 2048 KB

With no errors on the way when building from source, I am unable to
figure out the problem.
am I missing something obvious? thanks.


问:
Click event in vuejs on custom component?
I have in my main component one custom component and I need to fire a custom event on click, I tried it in this way:

```<code><child-component @click="fireCustomEvent"></child-component>

</code>```

This does not work and I tried to solve this problem with adding @click.native

```<code><child-component @click.native="fireCustomEvent"></child-component>

</code>```

With .native it works but it fires the event every time if I click inside my "child-component".

Can I avoid somehow to fire this event again if I click inside "child-component"?

答:
To do this you need the click handler inside your child component and then emit an event to the parent.

In child component:

```<code>//child component
<template>
   <div @click="$emit('wasClicked')")>click here</div>
</template>
</code>```

In parent component:

```<code>//parent component
<template>
   ...
   <child-component @wasClicked="fireCustomEvent"></child-component>
</template>
</code>```

Body:
I have in my main component one custom component and I need to fire a custom event on click, I tried it in this way:

<child-component @click="fireCustomEvent"></child-component>

This does not work and I tried to solve this problem with adding @click.native

<child-component @click.native="fireCustomEvent"></child-component>

With .native it works but it fires the event every time if I click inside my "child-component".

Can I avoid somehow to fire this event again if I click inside "child-component"?

Body:
To do this you need the click handler inside your child component and then emit an event to the parent.

In child component:

//child component
<template>
   <div @click="$emit('wasClicked')")>click here</div>
</template>

In parent component:

//parent component
<template>
   ...
   <child-component @wasClicked="fireCustomEvent"></child-component>
</template>


问:
Fatal access conflict detected when swapping array values in swift 4.2
I am trying to use the direct swap method available in Swift 4.2 to swap values of an array storing modal data, but it crashed. Can someone please suggest me why this is not working.?

```<code>   if modalArray.count >= 2{
            swap(&modalArray[0], &modalArray[1])
        }
</code>```

The Error I got is:

Thread 1: Simultaneous accesses to 0x600001c4cb08, but modification
  requires exclusive access

When I jumped to swap I got the definition that says it should work. Refer to the image below.

答:
Try using the swapAt(_:_:) method

```<code>if modalArray.count >= 2{
   modalArray.swapAt(0, 1)
}

</code>```

On why yours does not work, swap should not be used on Mutable Collections.

Apple Doc for swap

The two arguments must not alias each other. To swap two elements of a mutable collection, use the swapAt(::) method of that collection instead of this function.

Body:
I am trying to use the direct swap method available in Swift 4.2 to swap values of an array storing modal data, but it crashed. Can someone please suggest me why this is not working.?

   if modalArray.count >= 2{
            swap(&modalArray[0], &modalArray[1])
        }

The Error I got is:

Thread 1: Simultaneous accesses to 0x600001c4cb08, but modification
  requires exclusive access

When I jumped to swap I got the definition that says it should work. Refer to the image below.

Body:
Try using the swapAt(_:_:) method

if modalArray.count >= 2{
   modalArray.swapAt(0, 1)
}

On why yours does not work, swap should not be used on Mutable Collections.

Apple Doc for swap

The two arguments must not alias each other. To swap two elements of a mutable collection, use the swapAt(::) method of that collection instead of this function.


问:
Unexpected Token < : Webpack configuration issue with Typescript, React
Can anyone help me resolve the issue?
I started project with Typescript, React, Webpack and the help from https://www.typescriptlang.org/docs/handbook/react-&-webpack.html

I configured everything and when i try to run the command webpack i am getting the error

```<code>ERROR in ./app/index.tsx
Module parse failed: app/index.tsx Unexpected token (10:4)
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
|     <Hello compiler="TypeScript" framework = "React" />,
|     document.getElementById("example")
| );
</code>```

I have similar configuration and same source files as mentioned.

Webpack.config.js

```<code>const path = require('path');
module.exports = {
entry: path.join(__dirname, "/app/index.tsx"),
output: {
    filename: "bundle.js",
    path: path.join(__dirname, "/dist")
},

// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",

resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: [ ".webpack.js", ".web.js", ".ts", ".tsx", ".js" ]
},

module: {
    loaders: [
        // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
        {
            test: /\.tsx?$/,
            include: path.join(__dirname, '/app'),
            loaders: [ "babel-loader", "awesome-typescript-loader"],
            query: {
                presets: [ "react", "es2015" ]
            }
        }
    ],

    rules: [
        // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
        {
            test: /\.js$/,
            include: path.join(__dirname, '/app'),
            loader: "source-map-loader"}
    ]
},

// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
    "react": "React",
    "react-dom": "ReactDOM"
}
</code>```

};

index.tsx

```<code>import * as React from "react";
import * as ReactDOM from "react-dom";

import {Hello} from "./components/Hello";

ReactDOM.render(
    <Hello compiler="TypeScript" framework = "React" />,
    document.getElementById("example")
);
</code>```

答:
Not sure this answers your specific issue, but I got the same error. It turned out Jest had changed my tsconfig.json. Even if you're not using Jest, this may still apply to you.

tsconfig was changed from:

```<code>{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "esnext",
    "target": "es5",
    "sourceMap": true,
    "jsx": "react",
    "allowJs": true,
    "lib": [ "dom", "dom.iterable", "esnext" ],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "strict": false,
    "noEmit": true
  },
  "exclude": [ "node_modules" ],
  "include": [ "src" ]
}

</code>```

to:

```<code>{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "esnext",
    "target": "es5",
    "sourceMap": true,
    "jsx": "preserve",
    "allowJs": true,
    "lib": [ "dom", "dom.iterable", "esnext" ],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "strict": false,
    "noEmit": true
  },
  "exclude": [ "node_modules" ],
  "include": [ "src" ]
}
</code>```

Note option "jsx" has been changed from "react" to "preserve". Changing this back fixed my issue

Body:
Can anyone help me resolve the issue?
I started project with Typescript, React, Webpack and the help from https://www.typescriptlang.org/docs/handbook/react-&-webpack.html

I configured everything and when i try to run the command webpack i am getting the error

ERROR in ./app/index.tsx
Module parse failed: app/index.tsx Unexpected token (10:4)
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
|     <Hello compiler="TypeScript" framework = "React" />,
|     document.getElementById("example")
| );

I have similar configuration and same source files as mentioned.

Webpack.config.js

const path = require('path');
module.exports = {
entry: path.join(__dirname, "/app/index.tsx"),
output: {
    filename: "bundle.js",
    path: path.join(__dirname, "/dist")
},

// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",

resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: [ ".webpack.js", ".web.js", ".ts", ".tsx", ".js" ]
},

module: {
    loaders: [
        // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
        {
            test: /\.tsx?$/,
            include: path.join(__dirname, '/app'),
            loaders: [ "babel-loader", "awesome-typescript-loader"],
            query: {
                presets: [ "react", "es2015" ]
            }
        }
    ],

    rules: [
        // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
        {
            test: /\.js$/,
            include: path.join(__dirname, '/app'),
            loader: "source-map-loader"}
    ]
},

// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
    "react": "React",
    "react-dom": "ReactDOM"
}

};

index.tsx

import * as React from "react";
import * as ReactDOM from "react-dom";

import {Hello} from "./components/Hello";

ReactDOM.render(
    <Hello compiler="TypeScript" framework = "React" />,
    document.getElementById("example")
);

Body:
Not sure this answers your specific issue, but I got the same error. It turned out Jest had changed my tsconfig.json. Even if you're not using Jest, this may still apply to you.

tsconfig was changed from:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "esnext",
    "target": "es5",
    "sourceMap": true,
    "jsx": "react",
    "allowJs": true,
    "lib": [ "dom", "dom.iterable", "esnext" ],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "strict": false,
    "noEmit": true
  },
  "exclude": [ "node_modules" ],
  "include": [ "src" ]
}

to:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "esnext",
    "target": "es5",
    "sourceMap": true,
    "jsx": "preserve",
    "allowJs": true,
    "lib": [ "dom", "dom.iterable", "esnext" ],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "strict": false,
    "noEmit": true
  },
  "exclude": [ "node_modules" ],
  "include": [ "src" ]
}

Note option "jsx" has been changed from "react" to "preserve". Changing this back fixed my issue


问:
Impute value cell with condition
I have this dataframe:

```<code>df <- data.frame( Date = c("2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-25"),
                   idx = c(1, 2, 3,  4,5, 6, 3),
                   Temp = c(2, 5, 12, 12,12, 1, 5),
                   idy=   c(1, 3,  1, 6,  2, 5, 9))
</code>```

where idx and idy are references and Temp are temperatures.

What I would like to do is replace values in Temp>10 doing the following.

In this case for Temp = 12, idy are 1,6,2 and if you compare that idy with idx
take the mean of the temperatures of that idx. . Sorry but it´s hard to explain. Here is what I want:

```<code>df <- data.frame( Date = c("2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-25"),
                   idx = c(1, 2,  3,  4, 5, 6, 3),
                   Temp = c(2, 5, 2.66, 2.66, 2.66, 1, 5),
                   idy=   c(1, 3,  1, 6,  2, 5, 9))
</code>```

where 2.66 = (2+5+1)/3 which are the temperatures of the idx=idy of the temperature over 10.

I have tried with this:

```<code>df = df %>%  group_by(Date) %>% mutate( Temp = ifelse ( Temp >10 , mean(Temp[idy =idx] , na.rm = TRUE), Temp))
</code>```

But the mean is not calculated in a proper way. The value is 7.33 instead of 2.66.

答:
If I have understood you correctly and if there are no more edge cases this should work

```<code>library(dplyr)

df %>%
  mutate(Temp = replace(Temp, Temp > 10, mean(Temp[idx %in% idy[Temp > 10]])))

#        Date idx     Temp idy
#1 2017-02-23   1 2.000000   1
#2 2017-02-23   2 5.000000   3
#3 2017-02-23   3 2.666667   1
#4 2017-02-23   4 2.666667   6
#5 2017-02-23   5 2.666667   2
#6 2017-02-23   6 1.000000   5
#7 2017-02-25   3 5.000000   9
</code>```

Also we can do this directly,

```<code>with(df, replace(Temp, Temp > 10, mean(Temp[idx %in% idy[Temp > 10]])))
#[1] 2.000000 5.000000 2.666667 2.666667 2.666667 1.000000 5.000000
</code>```

Logic is to replace all the Temp values greater than 10 by first finding their corresponding idy values, then idx and get the mean of those Temp values.

Title: Impute value cell with condition

Body:
I have this dataframe:

df <- data.frame( Date = c("2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-25"),
                   idx = c(1, 2, 3,  4,5, 6, 3),
                   Temp = c(2, 5, 12, 12,12, 1, 5),
                   idy=   c(1, 3,  1, 6,  2, 5, 9))

where idx and idy are references and Temp are temperatures.

What I would like to do is replace values in Temp>10 doing the following.

In this case for Temp = 12, idy are 1,6,2 and if you compare that idy with idx
take the mean of the temperatures of that idx. . Sorry but it´s hard to explain. Here is what I want:

df <- data.frame( Date = c("2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-23", "2017-02-25"),
                   idx = c(1, 2,  3,  4, 5, 6, 3),
                   Temp = c(2, 5, 2.66, 2.66, 2.66, 1, 5),
                   idy=   c(1, 3,  1, 6,  2, 5, 9))

where 2.66 = (2+5+1)/3 which are the temperatures of the idx=idy of the temperature over 10.

I have tried with this:

df = df %>%  group_by(Date) %>% mutate( Temp = ifelse ( Temp >10 , mean(Temp[idy =idx] , na.rm = TRUE), Temp))

But the mean is not calculated in a proper way. The value is 7.33 instead of 2.66.

Body:
If I have understood you correctly and if there are no more edge cases this should work

library(dplyr)

df %>%
  mutate(Temp = replace(Temp, Temp > 10, mean(Temp[idx %in% idy[Temp > 10]])))

#        Date idx     Temp idy
#1 2017-02-23   1 2.000000   1
#2 2017-02-23   2 5.000000   3
#3 2017-02-23   3 2.666667   1
#4 2017-02-23   4 2.666667   6
#5 2017-02-23   5 2.666667   2
#6 2017-02-23   6 1.000000   5
#7 2017-02-25   3 5.000000   9

Also we can do this directly,

with(df, replace(Temp, Temp > 10, mean(Temp[idx %in% idy[Temp > 10]])))
#[1] 2.000000 5.000000 2.666667 2.666667 2.666667 1.000000 5.000000

Logic is to replace all the Temp values greater than 10 by first finding their corresponding idy values, then idx and get the mean of those Temp values.


问:
Html Action Link Not hiding when view page load in mvc
I have html.Action link and i need to hide the link when page load depend on the some condition.That condition when bool value False it should hide else need to show..on the page...

```<code>        @{
        if (item.Approved)
        {
            @Html.ActionLink("Approve", "Approve", new { id = item.ClusterID }, new { @class = "btn btn-info" })*@
        }
        else
        {
            @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })
        }
    }
  }
</code>```

the above code not working could you tell me what is wrong above code?

答:
Maybe, you should write, @if missing:

```<code> @if (item.Approved)
    {
        @*@Html.ActionLink("Approve", "Approve", new { id =item.ClusterID }, new { @class = "btn btn-info" })*@
    }
    else
    {
        @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })
    }
</code>```

Body:
I have html.Action link and i need to hide the link when page load depend on the some condition.That condition when bool value False it should hide else need to show..on the page...

        @{
        if (item.Approved)
        {
            @Html.ActionLink("Approve", "Approve", new { id = item.ClusterID }, new { @class = "btn btn-info" })*@
        }
        else
        {
            @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })
        }
    }
  }

the above code not working could you tell me what is wrong above code?

Body:
Maybe, you should write, @if missing:

 @if (item.Approved)
    {
        @*@Html.ActionLink("Approve", "Approve", new { id =item.ClusterID }, new { @class = "btn btn-info" })*@
    }
    else
    {
        @Html.ActionLink("Approve", "Approved", new { id = item.ClusterID }, new { @style = "display:none" })
    }


问:
SQL if join doesn't match then join something else
Poorly worded because I'm new to these operations in SQL, suppose I have a table with territories that are eastern and western with another table that has a field called address_state. I want to be able to join on the UCASE of address_state being equal to either the state_abbreviation OR the state_name

EG:

```<code>SELECT orders.total_value, territories.territory FROM orders
INNER JOIN tblCanadianTerritories ON
UCASE(orders.technical_address_state) = tblCanadianTerritories.state
OR
tblCanadianTerritories ON
UCASE(orders.technical_address_state) = tblCanadianTerritories.name

WHERE UCASE(orders.technical_address_country) = "CANADA"
</code>```

EDIT:

Have come to two possible solutions:

```<code>SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer, tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON
UCASE(so_order.technical_address_state) = tblCanadianTerritories.state
OR
UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC
</code>```

OR

```<code>SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer,

tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) =

tblCanadianTerritories.state
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC
UNION
SELECT so_order.id, so_order.date_entered,so_order.check_if_new_customer,

tblCanadianTerritories.territory, so_order.total_value FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) =

tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered;
</code>```

But they both seem to retrieve different results.

答:
You don't need a separate join. Try this:

```<code>SELECT o.total_value, territories.territory
FROM orders AS o
INNER JOIN tblCanadianTerritories AS ct ON
UCASE(o.technical_address_state) = ct.state
OR
UCASE(o.technical_address_state) = ct.name
WHERE UCASE(o.technical_address_country) = "CANADA"
</code>```

(now with aliases)

Body:
Poorly worded because I'm new to these operations in SQL, suppose I have a table with territories that are eastern and western with another table that has a field called address_state. I want to be able to join on the UCASE of address_state being equal to either the state_abbreviation OR the state_name

EG:

SELECT orders.total_value, territories.territory FROM orders
INNER JOIN tblCanadianTerritories ON
UCASE(orders.technical_address_state) = tblCanadianTerritories.state
OR
tblCanadianTerritories ON
UCASE(orders.technical_address_state) = tblCanadianTerritories.name

WHERE UCASE(orders.technical_address_country) = "CANADA"

EDIT:

Have come to two possible solutions:

SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer, tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON
UCASE(so_order.technical_address_state) = tblCanadianTerritories.state
OR
UCASE(so_order.technical_address_state) = tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC

OR

SELECT so_order.id, so_order.date_entered, so_order.check_if_new_customer,

tblCanadianTerritories.territory, so_order.total_value  FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) =

tblCanadianTerritories.state
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered ASC
UNION
SELECT so_order.id, so_order.date_entered,so_order.check_if_new_customer,

tblCanadianTerritories.territory, so_order.total_value FROM so_order
INNER JOIN tblCanadianTerritories ON UCASE(so_order.technical_address_state) =

tblCanadianTerritories.name
WHERE UCASE(so_order.technical_address_country) = "CANADA"
ORDER BY so_order.date_entered;

But they both seem to retrieve different results.

Body:
You don't need a separate join. Try this:

SELECT o.total_value, territories.territory
FROM orders AS o
INNER JOIN tblCanadianTerritories AS ct ON
UCASE(o.technical_address_state) = ct.state
OR
UCASE(o.technical_address_state) = ct.name
WHERE UCASE(o.technical_address_country) = "CANADA"

(now with aliases)


问:
How to print all the button texts within the url using Selenium through Java
Steps:

Go to the site > https://www.toolsqa.com/automation-practice-switch-windows/

Get a list of buttons from that page

Print the name of the buttons that are displayed on the page.

Code trial:

```<code>package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

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

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }}}}
</code>```

答:
To print all the button texts within the url you can use Java8's stream() and map() and you can use the following solution:

Line of code:

```<code>System.out.println(driver.findElements(By.tagName("button")).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList()));
</code>```

Console Output:

```<code>[New Browser Window, New Message Window, New Browser Tab, Alert Box, Timing Alert, Change Color, Change Color, Disabled, Visible, , , , ,  ,  ]
</code>```

Body:
Steps:

Go to the site > https://www.toolsqa.com/automation-practice-switch-windows/

Get a list of buttons from that page

Print the name of the buttons that are displayed on the page.

Code trial:

package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

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

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }}}}

Body:
To print all the button texts within the url you can use Java8's stream() and map() and you can use the following solution:

Line of code:

System.out.println(driver.findElements(By.tagName("button")).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList()));

Console Output:

[New Browser Window, New Message Window, New Browser Tab, Alert Box, Timing Alert, Change Color, Change Color, Disabled, Visible, , , , ,  ,  ]


问:
IModuleNotFoundError: No module named 'django' in VS Code editor while no problem with terminal
I'm new to django, and want to use it in VS Code. However, "ModuleNotFoundError: No module named 'django'" blocked me.

I've pip installed virtual environment, it worked fine in terminal.

on terminal, it shows:

```<code>(myenv) Kates-MacBook:~ kate.wang$ python3
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> from django.shortcuts import render
>>>
</code>```

on VS Code, it outputs:

```<code>[Running] python -u "/Users/kate.wang/myenv/my_django_project/blog/views.py"
Traceback (most recent call last):
File "/Users/kate.wang/myenv/my_django_project/blog/views.py", line 1, in <module>
from django.shortcuts import render
ModuleNotFoundError: No module named 'django'
</code>```

My VS Code Settings are:

```<code>{
"workbench.iconTheme": "vs-minimal",
"editor.fontSize": 15,
"editor.fontLigatures": true,
"terminal.integrated.fontSize": 14,
"workbench.startupEditor": "newUntitledFile",
"workbench.activityBar.visible": true,
"python.dataScience.sendSelectionToInteractiveWindow": true,
"workbench.sideBar.location": "left",
"workbench.colorTheme": "Visual Studio Dark",
"editor.minimap.enabled": false,
"kite.showWelcomeNotificationOnStartup": false,
"python.pythonPath": "python3.7",
"python.venvPath": "/Users/kate.wang/myenv"
</code>```

}

This problem has bothered me for days since I've been trying different solutions from stackoverflow and other websites the first time it poped up and didn't find a way to solve it.

Thank you for your time to help me.

答: You might have installed it using pip3 and so it gives no error when you use the terminal. Check if you have multiple versions.</p>

Body:
I'm new to django, and want to use it in VS Code. However, "ModuleNotFoundError: No module named 'django'" blocked me.

I've pip installed virtual environment, it worked fine in terminal.

on terminal, it shows:

(myenv) Kates-MacBook:~ kate.wang$ python3
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> from django.shortcuts import render
>>>

on VS Code, it outputs:

[Running] python -u "/Users/kate.wang/myenv/my_django_project/blog/views.py"
Traceback (most recent call last):
File "/Users/kate.wang/myenv/my_django_project/blog/views.py", line 1, in <module>
from django.shortcuts import render
ModuleNotFoundError: No module named 'django'

My VS Code Settings are:

{
"workbench.iconTheme": "vs-minimal",
"editor.fontSize": 15,
"editor.fontLigatures": true,
"terminal.integrated.fontSize": 14,
"workbench.startupEditor": "newUntitledFile",
"workbench.activityBar.visible": true,
"python.dataScience.sendSelectionToInteractiveWindow": true,
"workbench.sideBar.location": "left",
"workbench.colorTheme": "Visual Studio Dark",
"editor.minimap.enabled": false,
"kite.showWelcomeNotificationOnStartup": false,
"python.pythonPath": "python3.7",
"python.venvPath": "/Users/kate.wang/myenv"

}

This problem has bothered me for days since I've been trying different solutions from stackoverflow and other websites the first time it poped up and didn't find a way to solve it.

Thank you for your time to help me.


问:
How to get JSON data from an API in flutter
I'm facing the same issue since i start coding yesterday on my project which has a part of getting some of json data from a given api.

My api link is: http://alkadhum-col.edu.iq/wp-json/wp/v2/posts?_embed

I'm working on flutter SDK and i'm confused why it is not working with me!, my job is to get only link, title, and source_url objects but i cannot get it.

I tried the following code in flutter documentation

https://flutter.dev/docs/cookbook/networking/fetch-data
and after some of modification according to my needs didn't got any data.

```<code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  final response =
      await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post {

  final int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'].toString(),
      link: json['link'].toString()
    );
  }
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<Post> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.link);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
</code>```

I only got the meesage below:

Type List dynamic is not a subtype of type Map String, dynamic

Any help will be appreciated.

Thanks in advance.

答:
Try below code: </p>

```<code>factory Post.fromMap(Map<String, dynamic> json) {
  return Post(
    id: json['id'],
    title: json['title'].cast<String>(),
    link: json['link'].cast<String>()
  );
}
</code>```

Body:
I'm facing the same issue since i start coding yesterday on my project which has a part of getting some of json data from a given api.

My api link is: http://alkadhum-col.edu.iq/wp-json/wp/v2/posts?_embed

I'm working on flutter SDK and i'm confused why it is not working with me!, my job is to get only link, title, and source_url objects but i cannot get it.

I tried the following code in flutter documentation

https://flutter.dev/docs/cookbook/networking/fetch-data
and after some of modification according to my needs didn't got any data.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  final response =
      await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post {

  final int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'].toString(),
      link: json['link'].toString()
    );
  }
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<Post> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.link);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

I only got the meesage below:

Type List dynamic is not a subtype of type Map String, dynamic

Any help will be appreciated.

Thanks in advance.

Body:
Try below code:

factory Post.fromMap(Map<String, dynamic> json) {
  return Post(
    id: json['id'],
    title: json['title'].cast<String>(),
    link: json['link'].cast<String>()
  );
}


问:
How to automate the Leep Seek/Reading for video player(HTML5) in Appium?
I am automating the HTML5 Video Player. I do not want only Play/Pause/Load actions on a Player but also I want to automate Leep Seek/Reading for a Player. I want to automate the content which is present in the player using Appium. I have an Android app which contains the player.

How we can automate what is going on inside the video at a specific time? Is there any external tool or Jar present to automate this activity for HTML5 Video Player?

答:
You can use OpenCV library to process video player screenshots (e.g. some parts of it, like video content) made with Appium.

And the cool thing is that Appium already supports this library under the hood

Since you mentioned HTML5 I recommend checking WebDriver-based examples.


问:
HTML5 iOS volumechange event not fired
I'm trying to capture volumechange event on the iPad, but it isn't being fired though other events I bind are; Such as play, pause, webkitbegin and endfullscreen, etc.

The volume value is also fixed at 1.
When I'm using Google Chrome on Linux, I can see the volumechange event, with the correct volume updated.

Apple declares that the volumechange event can be used. How can I get it to work?

答:
From official Apple Developer documentation:

On iOS devices, the audio level is always under the user’s physical control. The volume property is not settable in JavaScript. Reading the volume property always returns 1.

In other words, we can't control the volume on iOS in any way.

Title: HTML5 iOS volumechange event not fired


答:
You should show the code in the component that emit the event.

You must have something like this:

```<code>//code that trigger an click event
this.$emit('click');

//or if you you to pass some data
this.$emit('click','some_data');
</code>```

.native doesn't need to be used here.

Title: Click event in vuejs on custom component?

Body:
I have in my main component one custom component and I need to fire a custom event on click, I tried it in this way:

<child-component @click="fireCustomEvent"></child-component>

This does not work and I tried to solve this problem with adding @click.native

<child-component @click.native="fireCustomEvent"></child-component>

With .native it works but it fires the event every time if I click inside my "child-component".

Can I avoid somehow to fire this event again if I click inside "child-component"?

Body:
You should show the code in the component that emit the event.

You must have something like this:

//code that trigger an click event
this.$emit('click');

//or if you you to pass some data
this.$emit('click','some_data');

.native doesn't need to be used here.