问:
How to get img and p tag inside div using vue?
I want to get image src and text of
 when I click on
 element.

```<code><div class="image-holder" @click="showImage($event)" >
  img class="img-fluid"  src="images/models-detail-small.png" alt="" />
  <p>elevation {{elevationA}}- {{elevationASqt}} sq. ft</p>
</div>

var vm = new Vue({
    el: '#app',
    methods: {
        showImage: function (event) {
            element = event.currentTarget;
            console.log(element);

            // href = element.getAttribute('src');
            // this.imgSrc=href;
        }
    }
});
</code>```

答:
You should add extra wrapper for hidden elements to toggle visibility

new Vue({
  el: "#app",

  data: () => ({
    imageVisible: false,
    imgSrc: '',
    text: ''
  }),

  methods: {
    setData() {
      this.imageVisible = true
      this.imgSrc = 'https://picsum.photos/200/300'
      this.text = 'Lorem ipsum dolor'
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.image-holder {
  width: 200px;
  min-height: 300px;
  background: #ccc;
}</code>```

{{ text }}

```

Body:
I want to get image src and text of
 when I click on
 element.

  img class="img-fluid"  src="images/models-detail-small.png" alt="" />

elevation {{elevationA}}- {{elevationASqt}} sq. ft

var vm = new Vue({
    el: '#app',
    methods: {
        showImage: function (event) {
            element = event.currentTarget;
            console.log(element);

            // href = element.getAttribute('src');
            // this.imgSrc=href;
        }
    }
});

Body:
You should add extra wrapper for hidden elements to toggle visibility

new Vue({
  el: "#app",

  data: () => ({
    imageVisible: false,
    imgSrc: '',
    text: ''
  }),

  methods: {
    setData() {
      this.imageVisible = true
      this.imgSrc = 'https://picsum.photos/200/300'
      this.text = 'Lorem ipsum dolor'
    }
  }
})

.image-holder {
  width: 200px;
  min-height: 300px;
  background: #ccc;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="image-holder" @click="setData()">
    <div v-if="imageVisible">
      <img class="img-fluid" :src="imgSrc" alt="" />
      <p>{{ text }}</p>
    </div>
  </div>
</div>


来源: stackexchange

问:
Pure Javascript How to Zoom Image on mousemove?
I'm trying to create onmousemove event inside the image then show the zoomed image in the right side.

Problem:

When I try to mousemove inside the image, the black box and zoomed image are blinking.

The zoomed image is not match in the blackbox.

How do I do that? May computation is wrong.

This is my code.

```<code><div>
    <div id="cursor" style="background:black; opacity:0.5; width:100px; height:100px; position:absolute; display:none">

    </div>
    <div style="float:left;">
        <img id="img" src="http://www.animenewsnetwork.com/thumbnails/cover400x200/cms/news/102950/26902290903_3c8f2db0ea_b.jpg" onmousemove="getPos(event)" onmouseout="stopTracking()"/>
    </div>
    <div id="zoom" style="width:300px; height:300px; zoom:1; float:left;">
        qwe
    </div>
</div>
<script>
    function getPos(e){
        var x = e.clientX;
        var y = e.clientY;
        var width = document.getElementById("img").clientWidth;
        var height = document.getElementById("img").clientHeight;

        document.getElementById("cursor").style.left = x - 50;
        document.getElementById("cursor").style.top = y - 50;
        document.getElementById("cursor").style.display = "inline-block";

        document.getElementById("zoom").style.background = "url('http://www.animenewsnetwork.com/thumbnails/cover400x200/cms/news/102950/26902290903_3c8f2db0ea_b.jpg') "+x / width * 100+"% "+y / width * 100+"%";
    }

    function stopTracking(){
        document.getElementById("cursor").style.display = "none";
        document.getElementById("zoom").style.background = "transparent";
    }
</script>
</code>```

答:
catch source from my e-commerce project (i'm using GSAP library for animation u can create custom CSS class with transitions instead):</p>

```<code><div class="grid col-10 rel z300">
  <div class="border padt20 padb20 padl20 padr20 zoom--in flex align-center">
    <img class="auto" src="img/prod.jpg" data-zoom="img/prod-large.jpg" alt="">
  </div>
</div>

export class zoom_in_gallery {
  constructor() {
    if (!this.setVars()) return;
    this.setEvents();
  }

  setVars() {
    let _this = this;

    _this.zoom = document.body.getElementsByTagName('section')[0].getElementsByClassName('zoom--in')[0];
    if (!this.zoom) return false;

    _this.img = this.zoom.firstElementChild;
    if (!this.img) return false;

    _this.zoom_pop = false;
    _this.act = false;

    return true;
  }

  setEvents() {
    let _this = this;

    function del(el) => {
      el = typeof el === 'string' ? document.body.getElementsByClassName(el)[0] : el;

      if (!el || !el.parentNode) return;
      return el.parentNode.removeChild(el);
    }

    this.obj.onmove = (e) => {
      if (_this.act) return;
      let y = e.offsetY ? (e.offsetY) : e.pageY - _this.img.offsetTop,
        x = e.offsetX ? (e.offsetX) : e.pageX - _this.img.offsetLeft;

      if (!_this.zoom_pop) {
        _this.zoom_pop = _this.render(e.target.parentNode, `<div class="top0 right0 abs o-hidden border" style="right:calc(-70%);left:initial;height:${_this.zoom.offsetWidth / 1.5}px;width:${_this.zoom.offsetWidth / 1.5}px"><div style="width:100%;height:100%;background: #fff url(${_this.img.dataset.zoom}) 0 0 / cover scroll no-repeat"></div></div>`);
        TweenLite.fromTo(_this.zoom_pop, .3, {autoAlpha: 0}, {autoAlpha: 1});
      }

      _this.zoom_pop.firstElementChild.style.backgroundPosition = `${x / 3.8}% ${y / 3.8}%`;
    };

    this.obj.onleave = () => {
      if (!_this.zoom_pop || _this.act) return;
      _this.act = true;

      TweenLite.to(_this.zoom_pop, .3, {
        autoAlpha: 0, onComplete: () => {
         del(_this.zoom_pop);
         _this.zoom_pop = false;
         _this.act = false;
        }
      });
    };

    this.zoom.addEventListener('mousemove', this.obj.onmove);
    this.zoom.addEventListener('mouseout', this.obj.onleave);
  }

  render(relEl, tpl, cfg = {}) {
    if (!relEl) return;
    const parse = typeof cfg.parse === 'undefined' ? true : cfg.parse, child;

    if (tpl.nodeName === 'TEMPLATE') {
      child = document.importNode(tpl.content, true);
    } else if (typeof tpl === 'string') {
      const range = document.createRange();
      range.selectNode(relEl);
      child = range.createContextualFragment(tpl);
    } else {
      child = tpl;
    }

    if (parse) {
      relEl.appendChild(child);
      return relEl.lastElementChild;
    }
    return {rel: relEl, el: child};
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create onmousemove event inside the image then show the zoomed image in the right side.

Problem:

When I try to mousemove inside the image, the black box and zoomed image are blinking.

The zoomed image is not match in the blackbox.

How do I do that? May computation is wrong.

This is my code.

        qwe

Body:
catch source from my e-commerce project (i'm using GSAP library for animation u can create custom CSS class with transitions instead):

<div class="grid col-10 rel z300">
  <div class="border padt20 padb20 padl20 padr20 zoom--in flex align-center">
    <img class="auto" src="img/prod.jpg" data-zoom="img/prod-large.jpg" alt="">
  </div>
</div>

export class zoom_in_gallery {
  constructor() {
    if (!this.setVars()) return;
    this.setEvents();
  }

  setVars() {
    let _this = this;

    _this.zoom = document.body.getElementsByTagName('section')[0].getElementsByClassName('zoom--in')[0];
    if (!this.zoom) return false;

    _this.img = this.zoom.firstElementChild;
    if (!this.img) return false;

    _this.zoom_pop = false;
    _this.act = false;

    return true;
  }

  setEvents() {
    let _this = this;

    function del(el) => {
      el = typeof el === 'string' ? document.body.getElementsByClassName(el)[0] : el;

      if (!el || !el.parentNode) return;
      return el.parentNode.removeChild(el);
    }

    this.obj.onmove = (e) => {
      if (_this.act) return;
      let y = e.offsetY ? (e.offsetY) : e.pageY - _this.img.offsetTop,
        x = e.offsetX ? (e.offsetX) : e.pageX - _this.img.offsetLeft;

      if (!_this.zoom_pop) {
        _this.zoom_pop = _this.render(e.target.parentNode, `<div class="top0 right0 abs o-hidden border" style="right:calc(-70%);left:initial;height:${_this.zoom.offsetWidth / 1.5}px;width:${_this.zoom.offsetWidth / 1.5}px"><div style="width:100%;height:100%;background: #fff url(${_this.img.dataset.zoom}) 0 0 / cover scroll no-repeat"></div></div>`);
        TweenLite.fromTo(_this.zoom_pop, .3, {autoAlpha: 0}, {autoAlpha: 1});
      }

      _this.zoom_pop.firstElementChild.style.backgroundPosition = `${x / 3.8}% ${y / 3.8}%`;
    };

    this.obj.onleave = () => {
      if (!_this.zoom_pop || _this.act) return;
      _this.act = true;

      TweenLite.to(_this.zoom_pop, .3, {
        autoAlpha: 0, onComplete: () => {
         del(_this.zoom_pop);
         _this.zoom_pop = false;
         _this.act = false;
        }
      });
    };

    this.zoom.addEventListener('mousemove', this.obj.onmove);
    this.zoom.addEventListener('mouseout', this.obj.onleave);
  }

  render(relEl, tpl, cfg = {}) {
    if (!relEl) return;
    const parse = typeof cfg.parse === 'undefined' ? true : cfg.parse, child;

    if (tpl.nodeName === 'TEMPLATE') {
      child = document.importNode(tpl.content, true);
    } else if (typeof tpl === 'string') {
      const range = document.createRange();
      range.selectNode(relEl);
      child = range.createContextualFragment(tpl);
    } else {
      child = tpl;
    }

    if (parse) {
      relEl.appendChild(child);
      return relEl.lastElementChild;
    }
    return {rel: relEl, el: child};
  }
}


问:
SQL Server combine data
I have 2 tables, one containing an ID number and a DateTime (MAIN TABLE). The other table has an ID, LocationName and DateTime (Location table).

The DateTime in the main table is a frequent capture of automated signals. The DateTime in the location table is when an object has been moved to a new location. Both the IDs are the primary key and link.

What I'm trying to do is produce just one table showing when the location changes occur, showing ID, DateTime from the main table and LocationName from the location table.

I have been trying for hours but can't seem to do it...

Below is an example of the tables and the end result..

Any help would be grateful.

Thanks

```<code>MAIN TABLE           Location Table

ID DateTime          ID DateTime         Location
-----------------    ----------------------------
1  20200101 12:00    1  20200101 11:45   Loc 1
1  20200101 13:00    1  20200101 13:45   Loc 2
1  20200101 14:00    2  20200101 15:15   Loc 1
2  20200101 15:00    2  20200101 17:30   Loc 2
2  20200101 17:00
</code>```

To show the table as:

```<code>ID DateTime       Location
---------------------------
1  20200101 12:00 Loc 1
1  20200101 13:00 Loc 2
1  20200101 14:00 Loc 2
2  20200101 15:00 Loc 1
2  20200101 17:00 Loc 2
</code>```

答:
It can be solved by using the nested SELECT to obtain location of nearest time that compared with the MAIN.DATETIME

```<code>SELECT MAIN.ID,MAIN.DATETIME,
    (SELECT TOP 1 B.Location
     FROM Location AS B
     WHERE B.ID = MAIN.ID
     ORDER BY CASE
                WHEN DATEDIFF(MINUTE, MAIN.DATETIME, B.DATETIME)>=0
                THEN DATEDIFF(MINUTE, MAIN.DATETIME, B.DATETIME)
                ELSE DATEDIFF(MINUTE, B.DATETIME, MAIN.DATETIME)
     END asc) AS Location
FROM MAIN
</code>```

Result :

Title: SQL Server combine data

Body:
I have 2 tables, one containing an ID number and a DateTime (MAIN TABLE). The other table has an ID, LocationName and DateTime (Location table).

The DateTime in the main table is a frequent capture of automated signals. The DateTime in the location table is when an object has been moved to a new location. Both the IDs are the primary key and link.

What I'm trying to do is produce just one table showing when the location changes occur, showing ID, DateTime from the main table and LocationName from the location table.

I have been trying for hours but can't seem to do it...

Below is an example of the tables and the end result..

Any help would be grateful.

Thanks

MAIN TABLE           Location Table

ID DateTime          ID DateTime         Location
-----------------    ----------------------------
1  20200101 12:00    1  20200101 11:45   Loc 1
1  20200101 13:00    1  20200101 13:45   Loc 2
1  20200101 14:00    2  20200101 15:15   Loc 1
2  20200101 15:00    2  20200101 17:30   Loc 2
2  20200101 17:00

To show the table as:

ID DateTime       Location
---------------------------
1  20200101 12:00 Loc 1
1  20200101 13:00 Loc 2
1  20200101 14:00 Loc 2
2  20200101 15:00 Loc 1
2  20200101 17:00 Loc 2

Body:
It can be solved by using the nested SELECT to obtain location of nearest time that compared with the MAIN.DATETIME

SELECT MAIN.ID,MAIN.DATETIME,
    (SELECT TOP 1 B.Location
     FROM Location AS B
     WHERE B.ID = MAIN.ID
     ORDER BY CASE
                WHEN DATEDIFF(MINUTE, MAIN.DATETIME, B.DATETIME)>=0
                THEN DATEDIFF(MINUTE, MAIN.DATETIME, B.DATETIME)
                ELSE DATEDIFF(MINUTE, B.DATETIME, MAIN.DATETIME)
     END asc) AS Location
FROM MAIN

Result :


问:
Compare boost::any contents
I am using a container to hold a list of pointers to anything:

```<code>struct Example {
    std::vector<boost::any> elements;
}
</code>```

To insert elements in this container, I had written a couple of helper functions (members of the struct Example):

```<code>void add_any(boost::any& a) {
    elements.push_back(a);
}

template<typename T>
void add_to_list(T& a) {
    boost::any bany = &a;
    add_any(bany);
}
</code>```

Now, I would like to insert elements only when they are not present in this container. To do this, I thought that I would only need to call search over elements with an appropriate comparator function. However, I do not know how to compare the boost::any instances.

My question:
Knowing that my boost::any instances always contain a pointer to something; is it possible to compare two boost::any values?

update

I thank you for your answers. I have also managed to do this in a probably unsafe way: using boost::unsafe_any_cast to obtain a void** and comparing the underlying pointer.

For the moment, this is working fine. I would, however, appreciate your comments: maybe this is a big mistake!

```<code>#include <boost/any.hpp>
#include <iostream>
#include <vector>
#include <string>
using namespace std;

bool any_compare(const boost::any& a1, const boost::any& a2) {
    cout << "compare " << *boost::unsafe_any_cast<void*>(&a1)
         << " with:  " << *boost::unsafe_any_cast<void*>(&a2);
    return (*boost::unsafe_any_cast<void*>(&a1)) ==
        (*boost::unsafe_any_cast<void*>(&a2));
}

struct A {};

class Example {
public:
    Example() : elements(0),
                m_1(3.14),
                m_2(42),
                m_3("hello"),
                m_4() {};
    virtual ~Example() {};

    void test_insert() {
        add_to_list(m_1);
        add_to_list(m_2);
        add_to_list(m_3);
        add_to_list(m_4);
        add_to_list(m_1); // should not insert
        add_to_list(m_2); // should not insert
        add_to_list(m_3); // should not insert
        add_to_list(m_4); // should not insert
    };

    template <typename T>
    void add_to_list(T& a) {
        boost::any bany = &a;
        add_any(bany);
    }

private:
    vector<boost::any> elements;
    double m_1;
    int    m_2;
    string m_3;
    A      m_4;

    void add_any(const boost::any& a) {
        cout << "Trying to insert " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        vector<boost::any>::const_iterator it;
        for (it =  elements.begin();
             it != elements.end();
             ++it) {
            if ( any_compare(a,*it) ) {
                cout << " : not inserting, already in list" << endl;
                return;
            }
            cout << endl;
        }
        cout << "Inserting " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        elements.push_back(a);
    };

};

int main(int argc, char *argv[]) {

    Example ex;
    ex.test_insert();
    unsigned char c;
    ex.add_to_list(c);
    ex.add_to_list(c); // should not insert

    return 0;
}
</code>```

答:
The only easy way to do this I can think of involves hardcoding support for the types that you're storing in the any instances, undermining much of the usefulness of any...

```<code>bool equal(const boost::any& lhs, const boost::any& rhs)
{
    if (lhs.type() != rhs.type())
        return false;

    if (lhs.type() == typeid(std::string))
        return any_cast<std::string>(lhs) == any_cast<std::string>(rhs);

    if (lhs.type() == typeid(int))
        return any_cast<int>(lhs) == any_cast<int>(rhs);

    // ...

    throw std::runtime_error("comparison of any unimplemented for type");
}
</code>```

With C++11's type_index you could use a std::map or std::unordered_map keyed on std::type_index(some_boost_any_object.type()) - similar to what Alexandre suggests in his comment below.

ContentLicense: CC BY-SA 3.0

Title: Compare boost::any contents

Body:
I am using a container to hold a list of pointers to anything:

struct Example {
    std::vector<boost::any> elements;
}

To insert elements in this container, I had written a couple of helper functions (members of the struct Example):

void add_any(boost::any& a) {
    elements.push_back(a);
}

template<typename T>
void add_to_list(T& a) {
    boost::any bany = &a;
    add_any(bany);
}

Now, I would like to insert elements only when they are not present in this container. To do this, I thought that I would only need to call search over elements with an appropriate comparator function. However, I do not know how to compare the boost::any instances.

My question:
Knowing that my boost::any instances always contain a pointer to something; is it possible to compare two boost::any values?

update

I thank you for your answers. I have also managed to do this in a probably unsafe way: using boost::unsafe_any_cast to obtain a void** and comparing the underlying pointer.

For the moment, this is working fine. I would, however, appreciate your comments: maybe this is a big mistake!

#include <boost/any.hpp>
#include <iostream>
#include <vector>
#include <string>
using namespace std;

bool any_compare(const boost::any& a1, const boost::any& a2) {
    cout << "compare " << *boost::unsafe_any_cast<void*>(&a1)
         << " with:  " << *boost::unsafe_any_cast<void*>(&a2);
    return (*boost::unsafe_any_cast<void*>(&a1)) ==
        (*boost::unsafe_any_cast<void*>(&a2));
}

struct A {};

class Example {
public:
    Example() : elements(0),
                m_1(3.14),
                m_2(42),
                m_3("hello"),
                m_4() {};
    virtual ~Example() {};

    void test_insert() {
        add_to_list(m_1);
        add_to_list(m_2);
        add_to_list(m_3);
        add_to_list(m_4);
        add_to_list(m_1); // should not insert
        add_to_list(m_2); // should not insert
        add_to_list(m_3); // should not insert
        add_to_list(m_4); // should not insert
    };

    template <typename T>
    void add_to_list(T& a) {
        boost::any bany = &a;
        add_any(bany);
    }

private:
    vector<boost::any> elements;
    double m_1;
    int    m_2;
    string m_3;
    A      m_4;

    void add_any(const boost::any& a) {
        cout << "Trying to insert " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        vector<boost::any>::const_iterator it;
        for (it =  elements.begin();
             it != elements.end();
             ++it) {
            if ( any_compare(a,*it) ) {
                cout << " : not inserting, already in list" << endl;
                return;
            }
            cout << endl;
        }
        cout << "Inserting " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        elements.push_back(a);
    };

};

int main(int argc, char *argv[]) {

    Example ex;
    ex.test_insert();
    unsigned char c;
    ex.add_to_list(c);
    ex.add_to_list(c); // should not insert

    return 0;
}

Body:
The only easy way to do this I can think of involves hardcoding support for the types that you're storing in the any instances, undermining much of the usefulness of any...

bool equal(const boost::any& lhs, const boost::any& rhs)
{
    if (lhs.type() != rhs.type())
        return false;

    if (lhs.type() == typeid(std::string))
        return any_cast<std::string>(lhs) == any_cast<std::string>(rhs);

    if (lhs.type() == typeid(int))
        return any_cast<int>(lhs) == any_cast<int>(rhs);

    // ...

    throw std::runtime_error("comparison of any unimplemented for type");
}

With C++11's type_index you could use a std::map or std::unordered_map keyed on std::type_index(some_boost_any_object.type()) - similar to what Alexandre suggests in his comment below.


问:
How to convert this HSV into RGB
How to convert this HSV into RGB I would like it using cv2.color cv2.COLOR_BGR2RGB but its not same result.

This is the image i've used
enter image description here

Heres' the result that I want but using the cv2.COLOR_BGR2RGB but the code below is using the cv2.COLOR_BGR2HSV
enter image description here

```<code>import cv2
import numpy as np

## Read
img = cv2.imread("ni.jpg")

## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

## mask of green (36,25,25) ~ (86, 255,255)
# mask = cv2.inRange(hsv, (36, 25, 25), (86, 255,255))
mask = cv2.inRange(hsv, (7, 25, 25), (70, 255,255))

## slice the green
imask = mask>0
green = np.zeros_like(img, np.uint8)
green[imask] = img[imask]

## save
cv2.imwrite("green.png", green)
</code>```

答:
To convert an image from HSV to RGB you can do:

```<code>rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
</code>```

and to do HSV to BGR it is

```<code>bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
</code>```

You have to know that OpenCV is using BGR when reading/saving images.
You can convert between RGB and BGR with cvtColor and cv2.COLOR_RGB2BGR, or cv2.COLOR_BGR2RGB.

EDIT:

However, if what you want is having a mask of green bananas (or yellow bananas), The issue is the way you defined green color : it is including a lot of other colors right now, including yellow.

What you can do with the HSV, is to only look at the first channel, the hue :

Here you can see that green and yellow can be differentiated : green bananas have pixel value roughly between 30 and 50, and yellow between 20 and 30.

You can do a mask with that. I used another library to do the cleanup of pixel we don't want. It is Scikit-image. This can be done in OpenCV as well, but it takes a bit more time...

SO here is my code :

```<code>import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.morphology import remove_small_objects, remove_small_holes
## Read
img = cv2.imread("ni.jpg")

## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hue = hsv[:,:,0]

# plt.imshow(hue) # this show the figure in my post
# plt.show()

# mask = np.bitwise_and(hue > 20, hue < 35) # for yellow
mask = np.bitwise_and(hue > 30, hue < 50)  # for green
mask = remove_small_objects(mask, 1000)
mask = remove_small_holes(mask, 1000)

green = np.zeros_like(img, np.uint8)
green[mask] = img[mask]

## save
cv2.imwrite("green.png", green)
</code>```

Title: How to convert this HSV into RGB

Body:
How to convert this HSV into RGB I would like it using cv2.color cv2.COLOR_BGR2RGB but its not same result.

This is the image i've used
enter image description here

Heres' the result that I want but using the cv2.COLOR_BGR2RGB but the code below is using the cv2.COLOR_BGR2HSV
enter image description here

import cv2
import numpy as np

## Read
img = cv2.imread("ni.jpg")

## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

## mask of green (36,25,25) ~ (86, 255,255)
# mask = cv2.inRange(hsv, (36, 25, 25), (86, 255,255))
mask = cv2.inRange(hsv, (7, 25, 25), (70, 255,255))

## slice the green
imask = mask>0
green = np.zeros_like(img, np.uint8)
green[imask] = img[imask]

## save
cv2.imwrite("green.png", green)

Body:
To convert an image from HSV to RGB you can do:

rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)

and to do HSV to BGR it is

bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

You have to know that OpenCV is using BGR when reading/saving images.
You can convert between RGB and BGR with cvtColor and cv2.COLOR_RGB2BGR, or cv2.COLOR_BGR2RGB.

EDIT:

However, if what you want is having a mask of green bananas (or yellow bananas), The issue is the way you defined green color : it is including a lot of other colors right now, including yellow.

What you can do with the HSV, is to only look at the first channel, the hue :

Here you can see that green and yellow can be differentiated : green bananas have pixel value roughly between 30 and 50, and yellow between 20 and 30.

You can do a mask with that. I used another library to do the cleanup of pixel we don't want. It is Scikit-image. This can be done in OpenCV as well, but it takes a bit more time...

SO here is my code :

import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.morphology import remove_small_objects, remove_small_holes
## Read
img = cv2.imread("ni.jpg")

## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hue = hsv[:,:,0]

# plt.imshow(hue) # this show the figure in my post
# plt.show()

# mask = np.bitwise_and(hue > 20, hue < 35) # for yellow
mask = np.bitwise_and(hue > 30, hue < 50)  # for green
mask = remove_small_objects(mask, 1000)
mask = remove_small_holes(mask, 1000)

green = np.zeros_like(img, np.uint8)
green[mask] = img[mask]

## save
cv2.imwrite("green.png", green)


问:
Deleting a row from MySQL after 24 hours in JEE?
I am trying to delete a row in my table. Here is my sample code

```<code>String DBDate = new String();
Long date = new Date().getTime();
String dateToday = date.toString();
dbobj.clear();
dbobj.put(LAST_TIME_ANSWERED, "");
int hasDB = dbobj.getFromDB(tableName,column key, primary key);

if(hasDB != 0) {
    DBDate = dbobj.get(LAST_TIME_ANSWERED);
    if(DBDate != dateToday) {
        dbobj.deleteClientDB(tableName, column key, primary key);
    }
}
</code>```

How could I change the date of a timer?
Any help would be nice. Thanks in advance!

答:
there are two options for this.
1.) use java scheduler  or
2.) use a scheduled job at DB level to clear data at the end of each day</p>

Body:
I am trying to delete a row in my table. Here is my sample code

String DBDate = new String();
Long date = new Date().getTime();
String dateToday = date.toString();
dbobj.clear();
dbobj.put(LAST_TIME_ANSWERED, "");
int hasDB = dbobj.getFromDB(tableName,column key, primary key);

if(hasDB != 0) {
    DBDate = dbobj.get(LAST_TIME_ANSWERED);
    if(DBDate != dateToday) {
        dbobj.deleteClientDB(tableName, column key, primary key);
    }
}

How could I change the date of a timer?
Any help would be nice. Thanks in advance!


问:
download directory from a branch using Gitlab API v4
I am trying to download a directory inside of a 'release' branch of a repository from Gitlab. I am using API v4.

The branch includes is of the below structure:

```<code>- archive
  - outputs
    - history-2020-01-01T142535
    - history-2020-01-15T142559
    - history-2020-02-01T142540
</code>```

I want to get the "history-2020-02-01T142540" directory.

I can get a ZIP archive of the entire branch...

```<code>https://<GITLAB_URL>/api/v4/projects/<PROJECT_ID>/repository/archive.zip?sha=<BRANCH_ID>
</code>```

How do I get a ZIP archive of only a specific folder within that branch?

答:
You can't get an archive for a specific file or folder.

But you can do something similar which might help you:

Get file from repository

List repository tree

Body:
I am trying to download a directory inside of a 'release' branch of a repository from Gitlab. I am using API v4.

The branch includes is of the below structure:

- archive
  - outputs
    - history-2020-01-01T142535
    - history-2020-01-15T142559
    - history-2020-02-01T142540

I want to get the "history-2020-02-01T142540" directory.

I can get a ZIP archive of the entire branch...

https://<GITLAB_URL>/api/v4/projects/<PROJECT_ID>/repository/archive.zip?sha=<BRANCH_ID>

How do I get a ZIP archive of only a specific folder within that branch?


问:
Spring boot autowiring: strange case of property value being populated
I've been blown away by something and my sleep is nowhere after finding out that my code is working from last 2 years when clearly it shouldn't!
So it's a Spring boot application. The application has some controllers. One of the classes I'm using extends WebServiceGatewaySupport, so requires that I @Autowire this. The class name is AClient. Now, this class needs 4 properties to work. Three of them are coming from properties file, e.g.

```<code>@Value("${a.userName}")String userName;
</code>```

So three properties are obviously picked from application.properties file. Now the fourth property had me blown away. It is NOT being fetched as rest three, but is being copied from constructor parameter. So we have only one constructor in the class:

```<code>public AClient(String d){
    this.d=d;
}
</code>```

Now this property is being used in one of the methods this class has

```<code>public String getSomeData(){
// This method gets Data based on property d
}
</code>```

And interestingly and surprisingly, this property's value is present everytime this bean is accessed! The bean is @Autowired at one place only, inside the Controller class. I haven't marked the property value to be fetched from application.properties file. I haven't provided this class any clue where to get the value of d from. I haven't provided any public methods for other classes to set this value. Yet the code is working and I can even place a debug pointer in method getSomeData() and see that the value of d is present!

Now I understand I might be missing something obvious, but what? Is there a way I can get into Spring container when @Autowired objects are being instantiated and debug from that point to see where this value is coming from? I've checked the code multiple times. Run hundreds of query on Google to find something like Spring boot does some magic stuff to map the missing String properties. But the variable name in properties file is different from what it is in AClient class. So how can it even map? This is truly killing me now!

Addition:
Less relevant, but the code is being accessed in a standard way:

```<code>@Autowired
AClient aClient;

public someOtherMethod(){
    aClient.getSomeData();
}
</code>```

So when I place a debugger on first line of someOtherMethod() and hover over aClient, it shows variable d value populated, same as in application.properties file!

Edit:Here's what I missed:

```<code>@Configuration
public class someConfig{
@Bean
   public AClient aClient(){
    // Someone else fetched property from application.properties file, created an object of AClient class using argument constructor and returned that object here. So now Spring is using @Autowire reference for this object I guess
 }
}
</code>```

答:
So basically, your @Configuration class looks similar to this?

```<code>@Configuration
public class SomeConfig {

    @Value("${a-client.important-value-d}")
    private String importantValueDFromApplicationProperties;

    @Bean
    public AClient aClient() {
        return new AClient(importantValueDFromApplicationProperties);
    }

}
</code>```

If yes, then Spring will the aClient for every @Autowired requesting it. Therefore the value of importantValueDFromApplicationProperties will be present in this certain instance.

Another note:
I would recommend using Spring Boot's @ConfigurationProperties instead of @Value. Take a look.

Body:
I've been blown away by something and my sleep is nowhere after finding out that my code is working from last 2 years when clearly it shouldn't!
So it's a Spring boot application. The application has some controllers. One of the classes I'm using extends WebServiceGatewaySupport, so requires that I @Autowire this. The class name is AClient. Now, this class needs 4 properties to work. Three of them are coming from properties file, e.g.

@Value("${a.userName}")String userName;

So three properties are obviously picked from application.properties file. Now the fourth property had me blown away. It is NOT being fetched as rest three, but is being copied from constructor parameter. So we have only one constructor in the class:

public AClient(String d){
    this.d=d;
}

Now this property is being used in one of the methods this class has

public String getSomeData(){
// This method gets Data based on property d
}

And interestingly and surprisingly, this property's value is present everytime this bean is accessed! The bean is @Autowired at one place only, inside the Controller class. I haven't marked the property value to be fetched from application.properties file. I haven't provided this class any clue where to get the value of d from. I haven't provided any public methods for other classes to set this value. Yet the code is working and I can even place a debug pointer in method getSomeData() and see that the value of d is present!

Now I understand I might be missing something obvious, but what? Is there a way I can get into Spring container when @Autowired objects are being instantiated and debug from that point to see where this value is coming from? I've checked the code multiple times. Run hundreds of query on Google to find something like Spring boot does some magic stuff to map the missing String properties. But the variable name in properties file is different from what it is in AClient class. So how can it even map? This is truly killing me now!

Addition:
Less relevant, but the code is being accessed in a standard way:

@Autowired
AClient aClient;

public someOtherMethod(){
    aClient.getSomeData();
}

So when I place a debugger on first line of someOtherMethod() and hover over aClient, it shows variable d value populated, same as in application.properties file!

Edit:Here's what I missed:

@Configuration
public class someConfig{
@Bean
   public AClient aClient(){
    // Someone else fetched property from application.properties file, created an object of AClient class using argument constructor and returned that object here. So now Spring is using @Autowire reference for this object I guess
 }
}

Body:
So basically, your @Configuration class looks similar to this?

@Configuration
public class SomeConfig {

    @Value("${a-client.important-value-d}")
    private String importantValueDFromApplicationProperties;

    @Bean
    public AClient aClient() {
        return new AClient(importantValueDFromApplicationProperties);
    }

}

If yes, then Spring will the aClient for every @Autowired requesting it. Therefore the value of importantValueDFromApplicationProperties will be present in this certain instance.

Another note:
I would recommend using Spring Boot's @ConfigurationProperties instead of @Value. Take a look.


问:
mp4parser version conflict (compressed video has no sound)
I am using these two libraries in my project:

https://github.com/HemendraGangwar/VideoTrimmingLikeWhatsapp
https://github.com/fishwjy/VideoCompressor

Both libraries are imported locally to my project (i.e. copied them and added them to the project)

Both libraries work fine when used separately, but when I use them together I get some errors of type Program type already present which I solved by deleting the file isoparser-1.0.6.jar from the second library, because I noticed that the two libraries use the same library 'com.googlecode.mp4parser:isoparser' but with different versions: 1.1.21 for the first one and 1.0.6 for the second one.

When using only the old library, I get this code:

error: cannot find symbol class FileDataSourceViaHeapImpl

It is working now, but the problem the output video (after compression) does not have sound on it. How can I solve this?

Here is the code I am using for compressing the video (after trimming):

```<code>VideoController.getInstance().convertVideo(tmpFile.toString(), dstFile.toString(),
           VideoController.COMPRESS_QUALITY_MEDIUM, null);
</code>```

EDIT1

Summering the scenarios here with the same video:

VideoTrimmingLikeWhatsapp with verion 1.1.21 => works

VideoTrimmingLikeWhatsapp with verion 1.0.6 => does not works (compile error of missing classes)

VideoCompressor with 1.1.21 => does not work (no sound)

VideoCompressor with 1.0.6 => work

I tried a lot of things, and I am loosing tracks here. I also tried using SiliCompressor which seems also using version 1.0.6 of mp4isoparser, and the same problem is happening, output video has no sound. I posted an issue here a few days ago, but I don't think they will address this any time soon.

I also submitted here.

I tried downloading the mp4parser version 1.1.21 from here, and tried to import it locally so I can change the package names, but I couldn't because it using Maven not Gradle. The old version is a jar file, and I need to decompile it so I can mess with it. Can I do that?

I also tried using ffmpeg libraries, but all of them work very slowly compared to mp4isoparser

EDIT 2

The author of SiliCompressor has replied to the here I opened, he says that the problem should be solved by now. For the moment I am unable to verify it, as I no longer work on that project. If any one can confirm it, just tell me to add the answer to this topic.

答:
It's too late but i send this solution to be useful for others.

Yes, the problem is about version conflicts between the two libraries.

Solution:

Don't touch video compressor library at all.

Downgrade the "isoparser" dependency of video trimmer to the same version (1.0.6) with video compressor library dependency "isoparser".

Remove the following line from TrimVideoUtils.java file:

```<code>import com.googlecode.mp4parser.FileDataSourceViaHeapImpl;
</code>```

Then change the following line:

```<code>Movie movie = MovieCreator.build(new FileDataSourceViaHeapImpl(src.getAbsolutePath()));
</code>```

To

```<code>Movie movie = MovieCreator.build(src.getAbsolutePath());
</code>```

It's done.

NOTE: Be careful about large files. Because this solution doesn't use memory mapping.

Body:
I am using these two libraries in my project:

https://github.com/HemendraGangwar/VideoTrimmingLikeWhatsapp
https://github.com/fishwjy/VideoCompressor

Both libraries are imported locally to my project (i.e. copied them and added them to the project)

Both libraries work fine when used separately, but when I use them together I get some errors of type Program type already present which I solved by deleting the file isoparser-1.0.6.jar from the second library, because I noticed that the two libraries use the same library 'com.googlecode.mp4parser:isoparser' but with different versions: 1.1.21 for the first one and 1.0.6 for the second one.

When using only the old library, I get this code:

error: cannot find symbol class FileDataSourceViaHeapImpl

It is working now, but the problem the output video (after compression) does not have sound on it. How can I solve this?

Here is the code I am using for compressing the video (after trimming):

VideoController.getInstance().convertVideo(tmpFile.toString(), dstFile.toString(),
           VideoController.COMPRESS_QUALITY_MEDIUM, null);

EDIT1

Summering the scenarios here with the same video:

VideoTrimmingLikeWhatsapp with verion 1.1.21 => works

VideoTrimmingLikeWhatsapp with verion 1.0.6 => does not works (compile error of missing classes)

VideoCompressor with 1.1.21 => does not work (no sound)

VideoCompressor with 1.0.6 => work

I tried a lot of things, and I am loosing tracks here. I also tried using SiliCompressor which seems also using version 1.0.6 of mp4isoparser, and the same problem is happening, output video has no sound. I posted an issue here a few days ago, but I don't think they will address this any time soon.

I also submitted here.

I tried downloading the mp4parser version 1.1.21 from here, and tried to import it locally so I can change the package names, but I couldn't because it using Maven not Gradle. The old version is a jar file, and I need to decompile it so I can mess with it. Can I do that?

I also tried using ffmpeg libraries, but all of them work very slowly compared to mp4isoparser

EDIT 2

The author of SiliCompressor has replied to the here I opened, he says that the problem should be solved by now. For the moment I am unable to verify it, as I no longer work on that project. If any one can confirm it, just tell me to add the answer to this topic.

Body:
It's too late but i send this solution to be useful for others.

Yes, the problem is about version conflicts between the two libraries.

Solution:

Don't touch video compressor library at all.

Downgrade the "isoparser" dependency of video trimmer to the same version (1.0.6) with video compressor library dependency "isoparser".

Remove the following line from TrimVideoUtils.java file:

import com.googlecode.mp4parser.FileDataSourceViaHeapImpl;

Then change the following line:

Movie movie = MovieCreator.build(new FileDataSourceViaHeapImpl(src.getAbsolutePath()));

To

Movie movie = MovieCreator.build(src.getAbsolutePath());

It's done.

NOTE: Be careful about large files. Because this solution doesn't use memory mapping.


问:
Is there a way to resume an application to the "current activity" even if it was killed by the OS?
I am working on a taxi application like Uber. I have a background service that keeps the app working in the background. When the driver starts the trip, the app reloads to the homepage instead of staying at the JourneyActivity(this happens if the trip takes 10 minutes or more). How can I ensure that even if the app is killed, when the driver opens it again it takes them to the JourneyActivity?
Any help would be highly appreciated. Thanks</p>

答:
You can use PendingIntent over a notification which you can keep displaying while the service is running in the background. With this, whenever a user clicks on the notification, he will be taken to the JourneyActivity. For cases when the app icon is clicked, you can implement using SharedPreferences whenever you have a running Journey. Set a flag value to 1. In the onCreate method of the LauncherActivity, check for this value, and if it is 1, you can directly launch the JourneyActivity, otherwise, continue with the LanucherActivity.

Please note, You will have to reset this flag to 0 once the Journey Ends.


问:
Change many values with specific
I have data like this:

```<code>data.frame(text1 = c("Amazon", "Google", "other"))
</code>```

Add I would like to replace whatever is in the list with a specific value

```<code>mylist <- c("Amazon", "Google")
</code>```

replace what is in the mylist with stock value

Expected output:

```<code>data.frame(text1 = c("stock", "stock", "other"))
</code>```

答:
You can do direct assignment :

```<code>df$text1[df$text1 %in% mylist] <- 'stock'
df
#  text1
#1 stock
#2 stock
#3 other
</code>```

Or use replace

```<code>df$text1 <- replace(df$text1, df$text1 %in% mylist, 'stock')
</code>```

data

Read the data as characters :

```<code>df <- data.frame(text1 = c("Amazon", "Google", "other"), stringsAsFactors = FALSE)
</code>```

Title: Change many values with specific

Body:
I have data like this:

data.frame(text1 = c("Amazon", "Google", "other"))

Add I would like to replace whatever is in the list with a specific value

mylist <- c("Amazon", "Google")

replace what is in the mylist with stock value

Expected output:

data.frame(text1 = c("stock", "stock", "other"))

Body:
You can do direct assignment :

df$text1[df$text1 %in% mylist] <- 'stock'
df
#  text1
#1 stock
#2 stock
#3 other

Or use replace

df$text1 <- replace(df$text1, df$text1 %in% mylist, 'stock')

data

Read the data as characters :

df <- data.frame(text1 = c("Amazon", "Google", "other"), stringsAsFactors = FALSE)


问:
sharepoint field createdby matches which property of AD
As a requirement im using sharepoint object model and trying to compare "Created By" field of a List Item with the Current User Logged on.

My Question is  :

If the Same user who has created the item logged on

Does  Web.CurrentUser.LoginName = Created By Matches?? or anyother active directory property that matches with Created By

Please help me on this

Thanks in advance

答: To my knowledge,  System.Web.HttpContext.Current.User.Identity.Name should match the CreatedBy property.


问:
"Schema is not configured for mutations."
In my project I am using npm, apollo server and typeorm to set up my server. When I try to create a mutation i get this error message "Schema is not configured for mutations".  I have tried searching for a solution but in all the other solutions they are using different libraries than me, so they don't really help... I have also looked at examples and in their code it works fine to import the mutation into the resolver file and then import the resolver into the schema. As it also says that the "schema is not configured" I wonder if I need to add a configuration to my tsconfig.json which allows the project to use schemas with mutations.

The mutation looks as such:

```<code>import {InputType, Field} from "type-graphql";

@InputType()
export class CreateBookInput{
    @Field()
    title: string;

    @Field()
    author: string;
}
</code>```

I import this class to my resolver class:

```<code>
import { Resolver, Query, Mutation, Arg } from "type-graphql";
import { Book } from "../models/book";
import {CreateBookInput} from "../inputs/createBookInput";

@Resolver()
export class BookResolver {
    @Query(() => [Book])
    books() {
        return Book.find()
    }

    @Mutation(() => Book)
    async createBook(@Arg("data") data: CreateBookInput) {
        const book = Book.create(data);
        await book.save();
        return book;
    }

}
</code>```

This is later on imported in my index.ts file where I also handle my schema:

```<code>import "reflect-metadata";
import { createConnection } from "typeorm";
import { ApolloServer } from "apollo-server";
import { BookResolver } from "./resolvers/bookResolver"; // add this
import { buildSchema } from "type-graphql";

async function main() {
  const connection = await createConnection()
  const schema = await buildSchema({
    resolvers: [BookResolver]
  })
  const server = new ApolloServer({ schema })
  await server.listen(4000)
  console.log("Server has started!")
}

main();
</code>```

Any help is highly valued

答:
Somehow it works now.

I compiled the project again using tsc and launched it and this time it worked without failure. I thought using npm start also compiled the project at the same time, but I guess I was wrong.

Body:
In my project I am using npm, apollo server and typeorm to set up my server. When I try to create a mutation i get this error message "Schema is not configured for mutations".  I have tried searching for a solution but in all the other solutions they are using different libraries than me, so they don't really help... I have also looked at examples and in their code it works fine to import the mutation into the resolver file and then import the resolver into the schema. As it also says that the "schema is not configured" I wonder if I need to add a configuration to my tsconfig.json which allows the project to use schemas with mutations.

The mutation looks as such:

import {InputType, Field} from "type-graphql";

@InputType()
export class CreateBookInput{
    @Field()
    title: string;

    @Field()
    author: string;
}

I import this class to my resolver class:

import { Resolver, Query, Mutation, Arg } from "type-graphql";
import { Book } from "../models/book";
import {CreateBookInput} from "../inputs/createBookInput";

@Resolver()
export class BookResolver {
    @Query(() => [Book])
    books() {
        return Book.find()
    }

    @Mutation(() => Book)
    async createBook(@Arg("data") data: CreateBookInput) {
        const book = Book.create(data);
        await book.save();
        return book;
    }

}

This is later on imported in my index.ts file where I also handle my schema:

import "reflect-metadata";
import { createConnection } from "typeorm";
import { ApolloServer } from "apollo-server";
import { BookResolver } from "./resolvers/bookResolver"; // add this
import { buildSchema } from "type-graphql";

async function main() {
  const connection = await createConnection()
  const schema = await buildSchema({
    resolvers: [BookResolver]
  })
  const server = new ApolloServer({ schema })
  await server.listen(4000)
  console.log("Server has started!")
}

main();

Any help is highly valued


答:
One common practice is to delete database records which are older than some threshold value. For this purpose, the database table should have a column with a timestamp representing insert or update time. When executing the scheduled task there a command is performed (pseudocode, assuming an 'update' timestamp):

DELETE FROM TABLE_NAME WHERE LAST_UPDATED < (CURRENT_TIME - THRESHOLD)

Or there is a select query performed to retrieve all these records and handle their deletion one by one including logging and maybe some conditional logic.

To achieve this functionality java SE provides ScheduledExecutorService which can be used to execute delayed tasks:

```<code>    // initialize scheduler
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    // schedule repeating task
    ScheduledFuture future = scheduler.scheduleAtFixedRate(
            () -> {
                System.out.println("Excuting task...");
            },
            60,
            60,
            TimeUnit.SECONDS
    );
</code>```

The future object can be used to cancel task:

```<code>future.cancel(true);
scheduler.shutdown();
</code>```

But when using enterprise solutions, there are normally libraries and frameworks, providing functionality for executing scheduled tasks: quartz scheduler, spring framework task scheduling or EJB timer services.

Title: Deleting a row from MySQL after 24 hours in JEE?

Body:
One common practice is to delete database records which are older than some threshold value. For this purpose, the database table should have a column with a timestamp representing insert or update time. When executing the scheduled task there a command is performed (pseudocode, assuming an 'update' timestamp):

DELETE FROM TABLE_NAME WHERE LAST_UPDATED < (CURRENT_TIME - THRESHOLD)

Or there is a select query performed to retrieve all these records and handle their deletion one by one including logging and maybe some conditional logic.

To achieve this functionality java SE provides ScheduledExecutorService which can be used to execute delayed tasks:

    // initialize scheduler
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    // schedule repeating task
    ScheduledFuture future = scheduler.scheduleAtFixedRate(
            () -> {
                System.out.println("Excuting task...");
            },
            60,
            60,
            TimeUnit.SECONDS
    );

The future object can be used to cancel task:

future.cancel(true);
scheduler.shutdown();

But when using enterprise solutions, there are normally libraries and frameworks, providing functionality for executing scheduled tasks: quartz scheduler, spring framework task scheduling or EJB timer services.


问:
Rubik's cube scanning algorithm
I'm working on an augmented reality rubik's cube solving project.
We want the user to be able to use an smartphone application for collecting hints on to solving a rubiks cube.

For this we need to rebuild the cube in the smartphone memory.
We were unable to find scanning algorithms which can rebuild a rubik's cube with only scanning ONE side of the cube.

Does somebody know a rubik's cube scanning algorithm which can do this, or could at least mention if this algorithm could be mathematically possible?

答:
I don't know what is cube scanning algorithm.
But you are talking about algorithm which finds, is cube solved or not?

To check this you need to scan four sides of the cube out of 6( Only for 3 by 3 cube)
Even, you have to select 4 side like in manner that remaining 2 side must be beside of each other.( Remaining sides shouldn't  be opposite to each other)

As I'm also cuber. And doing cubing since 5 years.
I can guarantee you the above scanning is optimal.

Title: Rubik's cube scanning algorithm


问:
How to select and copy files with specific file names from one directory to another?
I have a directory with two different types of filenames daily/monthly:

```<code> report_20-10-2019.csv
 report_21-10-2019.csv
 report_22-10-2019.csv

 report_09-2019.csv
 report_10-2019.csv
 report_11-2019.csv
</code>```

I'm trying to copy only daily files to another directory. So far I'm able to copy all the files with the below code:

```<code>import shutil
import os
import glob

source_daily = '/path/to/files/to/copy/*.csv'
dest1 = 'path/to/directory/where/i/paste/my/files/'

files = os.listdir(source)

for file in glob.glob(source):
shutil.copy(file, dest1);
</code>```

Would someone be able to help with this? Thanks in advance!

答:
You can certainly do that,

```<code>import shutil
import os
import re

source = '/path/to/files/to/copy/'
dest1 = 'path/to/directory/where/i/paste/my/files/'

for filename in os.listdir(source):
    filepath = os.path.join(source, filename)
    if os.path.isfile(filepath):
        if re.search(r"[0-9]+-[0-9]+-[0-9]+\.csv", filepath):
            shutil.copy(filepath, dest1)
</code>```

Hope it addresses your problem!

Body:
I have a directory with two different types of filenames daily/monthly:

 report_20-10-2019.csv
 report_21-10-2019.csv
 report_22-10-2019.csv

 report_09-2019.csv
 report_10-2019.csv
 report_11-2019.csv

I'm trying to copy only daily files to another directory. So far I'm able to copy all the files with the below code:

import shutil
import os
import glob

source_daily = '/path/to/files/to/copy/*.csv'
dest1 = 'path/to/directory/where/i/paste/my/files/'

files = os.listdir(source)

for file in glob.glob(source):
shutil.copy(file, dest1);

Would someone be able to help with this? Thanks in advance!

Body:
You can certainly do that,

import shutil
import os
import re

source = '/path/to/files/to/copy/'
dest1 = 'path/to/directory/where/i/paste/my/files/'

for filename in os.listdir(source):
    filepath = os.path.join(source, filename)
    if os.path.isfile(filepath):
        if re.search(r"[0-9]+-[0-9]+-[0-9]+\.csv", filepath):
            shutil.copy(filepath, dest1)

Hope it addresses your problem!


问:
Updating CSS variables with attr()
Why is it that this works, and yields the :before and it says "changed"

:root {
    --namevar: "fallback";
}

.in[name] {
    --namevar: "changed";
}

.in dd:first-of-type:before {
    font-weight: bold;
    display: block;
    content: var(--namevar);
}
```

<p>But if you change it to this, the <code>:before</code> is lost?</p>

<pre class="lang-css prettyprint-override"><code>.in[name] {
    --namevar: attr(name);
}
</code>```

Nor do either of these work:

.in dd:first-of-type:before {
    content: attr(name, inherit);
}
```

<pre class="lang-css prettyprint-override"><code>.in[name] dd {
    name: inherit;
}
</code>```

The HTML would look something like:

one

two

three

```

What am I missing here?

答:
The use of --namevar: attr(name); works fine but you need to understand how it's working.

Example:

:root {
    --namevar: "fallback";
}

.in dd:before {
    font-weight: bold;
    content: var(--namevar);
}

.in[name] {
    --namevar: attr(name);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="in" name="this">
    <dd>one</dd>
    <dd name="ok ">two</dd>
    <dd>three</dd>
</div></code>```

Notice how in the second case we show "Ok" and nothing for the others because they don't have name attribute. When using .in[name] {--namevar: attr(name);} it doesn't mean get the value of the name attribute that belong to .in and store it inside the variable. It means that the value of the variable is attr(name) nothing more. We only resolve the value when the variable is used and in your case it's used inside dd so we consider the attribute name (if it exists) of dd.

In other words, you cannot use CSS variables to store a value of an element attribute and use it later inside any child element. What you can do is keeping your initial example and instead of attribute you consider CSS variable like below:

:root {
    --namevar: "fallback";
}

.in dd:before {
    font-weight: bold;
    content: var(--namevar);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="in" style="--namevar:'this '">
    <dd>one</dd>
    <dd name="ok">two</dd>
    <dd>three</dd>
</div></code>```

Title: Updating CSS variables with attr()

Body:
Why is it that this works, and yields the :before and it says "changed"

:root {
    --namevar: "fallback";
}

.in[name] {
    --namevar: "changed";
}

.in dd:first-of-type:before {
    font-weight: bold;
    display: block;
    content: var(--namevar);
}

But if you change it to this, the :before is lost?

.in[name] {
    --namevar: attr(name);
}

Nor do either of these work:

.in dd:first-of-type:before {
    content: attr(name, inherit);
}

.in[name] dd {
    name: inherit;
}

The HTML would look something like:

one

two

three

What am I missing here?

Body:
The use of --namevar: attr(name); works fine but you need to understand how it's working.

Example:

:root {
    --namevar: "fallback";
}

.in dd:before {
    font-weight: bold;
    content: var(--namevar);
}

.in[name] {
    --namevar: attr(name);
}

<div class="in" name="this">
    <dd>one</dd>
    <dd name="ok ">two</dd>
    <dd>three</dd>
</div>

Notice how in the second case we show "Ok" and nothing for the others because they don't have name attribute. When using .in[name] {--namevar: attr(name);} it doesn't mean get the value of the name attribute that belong to .in and store it inside the variable. It means that the value of the variable is attr(name) nothing more. We only resolve the value when the variable is used and in your case it's used inside dd so we consider the attribute name (if it exists) of dd.

In other words, you cannot use CSS variables to store a value of an element attribute and use it later inside any child element. What you can do is keeping your initial example and instead of attribute you consider CSS variable like below:

:root {
    --namevar: "fallback";
}

.in dd:before {
    font-weight: bold;
    content: var(--namevar);
}

<div class="in" style="--namevar:'this '">
    <dd>one</dd>
    <dd name="ok">two</dd>
    <dd>three</dd>
</div>


问:
React.createRef() inside useMemo
Is it safe to use such a pattern:

```<code>const appLoaders = useMemo(() => React.createRef(), [])
</code>```

The thing is I use this ref in useEffect and it is needed in the dependency array (exhaustive-deps). The above pattern does the trick and everything seems to work - without the memo, when I put the ref in the dependency array the app was in constant rerender.

I am just wondering if there are some 'traps' that will surprise me in certain circumstances.

答:
Don't see any issue with your version, but

```<code>const appLoaders = useRef();
</code>```

looks much shorter and does exactly the same(referential equality across re-renders, we set initial value, changing value does not cause re-render).

PS Actually useRef is not a replacement for React.createRef(they have different purpose but similar names, sometimes people misunderstand/misuse), so don't be confused by similarity.

But in this particular case they are definitely interchangeable

Title: React.createRef() inside useMemo

Body:
Is it safe to use such a pattern:

const appLoaders = useMemo(() => React.createRef(), [])

The thing is I use this ref in useEffect and it is needed in the dependency array (exhaustive-deps). The above pattern does the trick and everything seems to work - without the memo, when I put the ref in the dependency array the app was in constant rerender.

I am just wondering if there are some 'traps' that will surprise me in certain circumstances.

Body:
Don't see any issue with your version, but

const appLoaders = useRef();

looks much shorter and does exactly the same(referential equality across re-renders, we set initial value, changing value does not cause re-render).

PS Actually useRef is not a replacement for React.createRef(they have different purpose but similar names, sometimes people misunderstand/misuse), so don't be confused by similarity.

But in this particular case they are definitely interchangeable


问:
Jmeter how to send a constant number of requests every second
Does JMeter allow me to send a constant number of requests every second, instead of sequentially only when the request has finished? i.e. can I send request 2 after request 1 even if the request 1 is not done responding yet?

I am using Apache JMeter 5.2.1, I'd appreciate if anyone can give me guidance regarding this.
The Constant Throughput Timer, seems to focus more on the throughput, however I'd like to simply send X req/s.

答:
Constant Throughput Timer is only capable of pausing JMeter threads in order to limit the number of requests per second to the given value.

So you must supply enough threads in the Thread Group to create more requests per second than you're trying to achieve and then limit the number of requests per second to the desired rate using Constant Throughput Timer.

So major limitations are:

Constant Throughput Timer can only slow down JMeter, it will not kick off extra threads

Constant Throughput Timer is precise enough on the "minute" level, if your test last less or you want to see immediate throughput changes you will need to play with ramp-up

So I would recommend going for one of the following approaches instead:

Precise Throughput Timer (available since JMeter 4.0)

Concurrency Thread Group and Throughput Shaping Timer combination, these guys provide the most flexible way to reach/maintain the desired throughput


问:
C++ 11 in vxworks
I am new to VxWorks and I am developing a software using C++ in VxWorks platform. I want to know whether VxWorks compiler supports C++ 11 standard. The reason I am asking this question is because there is no shrink_to_fit() std::vector function available(this function is introduced in c++ 11 standard). So I want to know is there any way to compile the code with C++ 11 standard in VxWorks.</p>

答:
The latest vxworks version comes with c++17 support (C++17, Boost, Python, and Rust collection)
https://www.windriver.com/news/press/pr.html?ID=22444</p>

Title: C++ 11 in vxworks


问:
I'm using the Requests module to login into Instagram and retrieve user information after login in
EDIT: Code works now, problem was to do with Non-ASCII character '\xe2',
solved by declaring:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
</code>```

I referred to PEP-263 for help.

I'm login into instagram using requests using this code:

```<code>import bs4
from bs4 import BeautifulSoup
import json
import re
import requests

BASE_URL = 'https://www.instagram.com/accounts/login/'
LOGIN_URL = BASE_URL + 'ajax/'

headers_list = "Mozilla/5.0 (Windows NT 5.1; rv:41.0) Gecko/20100101"
" Firefox/41.0"

USERNAME = 'myUser'
PASSWD = 'myPassword'
USER_AGENT = headers_list

session = requests.Session()
session.headers = {'user-agent': USER_AGENT}
session.headers.update({'Referer': BASE_URL})
req = session.get(BASE_URL)
soup = BeautifulSoup(req.content, 'html.parser')
body = soup.find('body')

pattern = re.compile('window._sharedData')
script = body.find("script", text=pattern)

script = script.get_text().replace('window._sharedData = ', '')[:-1]
data = json.loads(script)

csrf = data['config'].get('csrf_token')
login_data = {'username': USERNAME, 'password': PASSWD}
session.headers.update({'X-CSRFToken': csrf})
login = session.post(LOGIN_URL, data=login_data, allow_redirects=True)
print(login.content)

# b'{"authenticated": true, "user": true, "userId": "*******", "oneTapPrompt": false, "status": "ok"}'
</code>```

However, once I've logged in I want to extract user info e.g. n number of followers & posts. I've got this code that gives the information of a specific user.

```<code>html = requests.get('https://www.instagram.com/USER')
soup = BeautifulSoup(html.text, 'lxml')
item = soup.select_one("meta[property='og:description']")
name = item.find_previous_sibling().get("content").split("•")[0]
followers = item.get("content").split(",")[0]
following = item.get("content").split(",")[1].strip()
print(f'{name}\n{followers}\n{following}')
</code>```

But what I want is to display the logged user info rather than a specific account. How would I go about it?

答:
You can simply visit your own page while logged in.

This modification should do the trick:

```<code>html = requests.get('https://www.instagram.com/'+USERNAME)
</code>```

Body:
EDIT: Code works now, problem was to do with Non-ASCII character '\xe2',
solved by declaring:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

I referred to PEP-263 for help.

I'm login into instagram using requests using this code:

import bs4
from bs4 import BeautifulSoup
import json
import re
import requests

BASE_URL = 'https://www.instagram.com/accounts/login/'
LOGIN_URL = BASE_URL + 'ajax/'

headers_list = "Mozilla/5.0 (Windows NT 5.1; rv:41.0) Gecko/20100101"
" Firefox/41.0"

USERNAME = 'myUser'
PASSWD = 'myPassword'
USER_AGENT = headers_list

session = requests.Session()
session.headers = {'user-agent': USER_AGENT}
session.headers.update({'Referer': BASE_URL})
req = session.get(BASE_URL)
soup = BeautifulSoup(req.content, 'html.parser')
body = soup.find('body')

pattern = re.compile('window._sharedData')
script = body.find("script", text=pattern)

script = script.get_text().replace('window._sharedData = ', '')[:-1]
data = json.loads(script)

csrf = data['config'].get('csrf_token')
login_data = {'username': USERNAME, 'password': PASSWD}
session.headers.update({'X-CSRFToken': csrf})
login = session.post(LOGIN_URL, data=login_data, allow_redirects=True)
print(login.content)

# b'{"authenticated": true, "user": true, "userId": "*******", "oneTapPrompt": false, "status": "ok"}'

However, once I've logged in I want to extract user info e.g. n number of followers & posts. I've got this code that gives the information of a specific user.

html = requests.get('https://www.instagram.com/USER')
soup = BeautifulSoup(html.text, 'lxml')
item = soup.select_one("meta[property='og:description']")
name = item.find_previous_sibling().get("content").split("•")[0]
followers = item.get("content").split(",")[0]
following = item.get("content").split(",")[1].strip()
print(f'{name}\n{followers}\n{following}')

But what I want is to display the logged user info rather than a specific account. How would I go about it?

Body:
You can simply visit your own page while logged in.

This modification should do the trick:

html = requests.get('https://www.instagram.com/'+USERNAME)


问:
How to resize the svg in Angular?
Here's the svg:

```<code><svg width="40%" viewbox="0 0 30 42">
  <path fill="transparent" stroke="#000" stroke-width="1.5"
        d="M15 3
           Q16.5 6.8 25 18
           A12.8 12.8 0 1 1 5 18
           Q13.5 6.8 15 3z" />
</svg>
</code>```

How to make this svg bigger? Here's the code: https://stackblitz.com/edit/angular-nnqwef?file=src/app/app.component.html

答:
You need to set the viewBox (be careful, it's not viewbox) in order to scale changing with and height as you do.

Like in here:

```<code><svg width="220" height="220" viewBox="0 0 50 100">
  <path id="scale" fill="transparent" stroke="#000" stroke-width="1.5"
        d="M15 3
           Q16.5 6.8 25 18
           A-22.8 -22.8 0 1 1 5 18
           Q13.5 6.8 15 3z" />
</svg>

<svg width="440" height="440" viewBox="0 0 50 100">
  <path id="scale2"
        d="M15 3
          Q20.5 11.8 35 25
          A-28.8 -28.8 0 1 1 0 20
          Q13.5 6.8 15 3z" />
</svg>
</code>```

https://stackblitz.com/edit/angular-4nylpq?file=src/app/app.component.html

and

https://stackblitz.com/edit/angular-jxc7nx?file=src/app/app.component.html

SVG with a viewBox will scale to fit the height and width you give it.

More info

Title: How to resize the svg in Angular?

Body:
Here's the svg:

<svg width="40%" viewbox="0 0 30 42">
  <path fill="transparent" stroke="#000" stroke-width="1.5"
        d="M15 3
           Q16.5 6.8 25 18
           A12.8 12.8 0 1 1 5 18
           Q13.5 6.8 15 3z" />
</svg>

How to make this svg bigger? Here's the code: https://stackblitz.com/edit/angular-nnqwef?file=src/app/app.component.html

Body:
You need to set the viewBox (be careful, it's not viewbox) in order to scale changing with and height as you do.

Like in here:

<svg width="220" height="220" viewBox="0 0 50 100">
  <path id="scale" fill="transparent" stroke="#000" stroke-width="1.5"
        d="M15 3
           Q16.5 6.8 25 18
           A-22.8 -22.8 0 1 1 5 18
           Q13.5 6.8 15 3z" />
</svg>

<svg width="440" height="440" viewBox="0 0 50 100">
  <path id="scale2"
        d="M15 3
          Q20.5 11.8 35 25
          A-28.8 -28.8 0 1 1 0 20
          Q13.5 6.8 15 3z" />
</svg>

https://stackblitz.com/edit/angular-4nylpq?file=src/app/app.component.html

and

https://stackblitz.com/edit/angular-jxc7nx?file=src/app/app.component.html

SVG with a viewBox will scale to fit the height and width you give it.

More info


问:
How to layout C++ code: namespaces and similar file names in visual studio 2010
This is more of a general question as I have found relatively little information on the net on how to best organize source code.

The way I currently have laid out my code is to have one project in VS compiling a lib, and then two console application projects on top of that, one for unit tests and one to execute the code in the lib.

In the main project, I have a folder called src containing my src code. This source code is then structured into various folders, each holding .h and .cpp files. File names match class names. Folders match namespaces, so every folder is in its own namespace.

I thought this was quite a sensible approach, until I discovered that visual studio 2010 hickups under this approach if two .cpp files have the same name (albeit in different folders and namespaces), because all .obj files are placed into the same temp directory (Debug or Release).

This has led me to wonder, as surely the point of maintaining lots of namespaces and sub-namespaces would be to enable you to have identically named classes and hence files. Some google-ing turned up the solution to individually select conflicting files and place the .obj file into a different place, but some hint at worse performance, and it does seem a bit of an odd approach.

So I am just wondering, is this not a sensible layout? Or do people usually compile each folder into a static library and then link those? Or do you just maintain different filenames? Do you then keep on matching filenames to class names? Because if you do, you wouldn't really need sub-namespaces either, as the whole project could just be in one namespace...

I wonder, I ponder... not sure if this question is concrete enough. I guess my immediate question (assuming the layout is somewhat sensible) is how to get around the conflicting obj files? I am just thinking of renaming the files while maintaining the class names. But I don't like that solution so much.

Thanks (sorry for long question)

P.S. the source folder should be compatible with gcc under linux

答:
IDE's usually let you arrange your files logically. (Visual Studio and XCode at least both let you create heirachal groups to arrange your source files, that does not correspond to the locations on disk of the files).

Because most IDEs compile all the source files to a common intermediate folder for the linking step any identically named source files can generate a conflict, where the second file to compile overwrites the .o or .obj of the previous compile.

As such, I've tended to go with a pragmatic approach: All the files for a single target (static library, dylib, exe) are contained in a single folder. Platform specific, or feature specific files, are places in specific sub folders so it becomes easy to rebuild a project for a different platform/configuration by simply adding (or removing) a folder of files at a time. Which really (in hindsight) seems to be the most useful way of using the filesystem effectively.

Rather than creating a deep sub structure, each time a single library becomes too cumbersome, I split off a new static library.

This maps well to the basic project structure IDEs such as Visual Studio and XCode tend to imply as best practice with their wizards: A Project folder, containing multiple target folders, each target folder containing its source files.


问:
Highlight between two points on MapKit swift 5
I am struggling to try and Highlight the road between 2 points using MapKit. All I don't want directions i just want to try and Highlight the road between these two points. </p>

<p>My code is: </p>

```<code>import UIKit
import MapKit
class ViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!

struct Points {
  var name: String
  var lattitude: CLLocationDegrees
  var longtitude: CLLocationDegrees
}

override func viewDidLoad() {
    super.viewDidLoad()

    let points = [
    Points(name: "Point 1", lattitude: 52.100525, longtitude: -9.623071),
    Points(name: "Point 2", lattitude: 52.07241, longtitude: -9.575299)
    ]

    fetchPointsOnMap(points)

}

func fetchPointsOnMap(_ points: [Points]) {
  for points in points {
    let annotations = MKPointAnnotation()
    annotations.title = points.name
    annotations.coordinate = CLLocationCoordinate2D(latitude:
      points.lattitude, longitude: points.longtitude)
    mapView.addAnnotation(annotations)
  }
}

}`
</code>```

答:
You can draw a line:

```<code>   directionsRequest.transportType = MKDirectionsTransportType.automobile

        //Draw polyline by using MKRoute so it follows the street roads...
        for (k, item) in arrayarrayPlacemarks.enumerated() {
            if k < (arrayarrayPlacemarks.count - 1) {
                directionsRequest.source = item
                directionsRequest.destination = arrayarrayPlacemarks[k+1]

                let directions = MKDirections(request: directionsRequest)
          directions.calculate { (response:MKDirections.Response!, error: Error!) -> Void in
                    if error == nil {
                        self.locRoute = response.routes[0] as? MKRoute
                        let geodesic:MKPolyline = self.locRoute!.polyline
                        self.mapView.addOverlay(geodesic)
                    }
                }
            }
        }
</code>```

Delegate:

```<code>  func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay.isKind(of: MKPolyline.self){
                var polylineRenderer = MKPolylineRenderer(overlay: overlay)
                polylineRenderer.fillColor = UIColor.blue
                polylineRenderer.strokeColor = UIColor.blue
                polylineRenderer.lineWidth = 2

            return polylineRenderer
     }
        return MKOverlayRenderer(overlay: overlay)
    }
</code>```

Body:
I am struggling to try and Highlight the road between 2 points using MapKit. All I don't want directions i just want to try and Highlight the road between these two points.

My code is:

import UIKit
import MapKit
class ViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!

struct Points {
  var name: String
  var lattitude: CLLocationDegrees
  var longtitude: CLLocationDegrees
}

override func viewDidLoad() {
    super.viewDidLoad()

    let points = [
    Points(name: "Point 1", lattitude: 52.100525, longtitude: -9.623071),
    Points(name: "Point 2", lattitude: 52.07241, longtitude: -9.575299)
    ]

    fetchPointsOnMap(points)

}

func fetchPointsOnMap(_ points: [Points]) {
  for points in points {
    let annotations = MKPointAnnotation()
    annotations.title = points.name
    annotations.coordinate = CLLocationCoordinate2D(latitude:
      points.lattitude, longitude: points.longtitude)
    mapView.addAnnotation(annotations)
  }
}

}`

Body:
You can draw a line:

   directionsRequest.transportType = MKDirectionsTransportType.automobile

        //Draw polyline by using MKRoute so it follows the street roads...
        for (k, item) in arrayarrayPlacemarks.enumerated() {
            if k < (arrayarrayPlacemarks.count - 1) {
                directionsRequest.source = item
                directionsRequest.destination = arrayarrayPlacemarks[k+1]

                let directions = MKDirections(request: directionsRequest)
          directions.calculate { (response:MKDirections.Response!, error: Error!) -> Void in
                    if error == nil {
                        self.locRoute = response.routes[0] as? MKRoute
                        let geodesic:MKPolyline = self.locRoute!.polyline
                        self.mapView.addOverlay(geodesic)
                    }
                }
            }
        }

Delegate:

  func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay.isKind(of: MKPolyline.self){
                var polylineRenderer = MKPolylineRenderer(overlay: overlay)
                polylineRenderer.fillColor = UIColor.blue
                polylineRenderer.strokeColor = UIColor.blue
                polylineRenderer.lineWidth = 2

            return polylineRenderer
     }
        return MKOverlayRenderer(overlay: overlay)
    }


问:
fatal error while compiling pybind11 test cases on raspbian
Following this question, I'm now trying to compile the pybind11 test cases as instructed here on a Raspberry Pi. What I have done so far:

installed Raspbian Raspbian Buster Lite from the official page

updated/upgraded all packages

updated/upgraded python packages following the instructions here

compiled and installed pybind11 following the instructions here

my environment is:

Raspbian buster version 10

python 3.7.3

pip 20.0.2

gcc 8.3.0

Then running the command make check -j 4 the compiler stops at:

[ 68%] Building CXX object CmakeFiles/pybind11_tests.dir/test_numpy_dtypes.cpp.o

and the errors are:

c++: fatal error: Killed signal terminated program cplusplus

compilation terminated.

make[3]: *** [CMakeFiles/pybind11_tests.dir/build.make:297: CMakeFiles/pybind11_tests.dir/test_local_bindings.cpp.o] Error 1

make[3]: *** waiting for unfinished jobs...

make[2]: *** [CMakeFiles/Makefile2:110: CMakeFiles/pybind11_tests.dir/all] Error 2

make[1]: *** [CMakeFiles/Makefile2:191: CMakeFile/check.dir/rule] Error 2

make: *** [Makefile:157: check] Error 2

I would appreciate it if you could help me understand what is the problem and how I can solve it.

答:
Yes you have to create first swap file. After that you can do it. Acctually swap file will increase yor ram memory. It will use rom space for ram performance.

Please go through with below link it would help you.

https://youtu.be/Cr5mDFxvsb0


问:
Detecting debugger on Mac OS X
I am trying to detect whether my process is being run in a debugger or not and, while in Windows there are many solutions and in Linux I use:

```<code>ptrace(PTRACE_ME,0,0,0)
</code>```

and check its return value, I did not manage to perform the same basic check on Mac OS X.
I tried to use the

```<code>ptrace(PT_TRACE_ME,0,0,0)
</code>```

call but it always returns 0 even when run under gdb.

If I change the request to PT_DENY_ATTACH it correctly stops the debugging but that is not what I want to achieve. Any ideas?

答:
Here's a Swift version of the function from Apple Technical Q&A QA1361:

```<code>import Foundation

extension ProcessInfo {
    /// - returns: true if the process is being debugged, else false.
    public func isBeingDebugged() -> Bool {
        // https://developer.apple.com/library/archive/qa/qa1361/_index.html
        // Technical Q&A QA1361: Detecting the Debugger

        var mib: [Int32] = [
            CTL_KERN,
            KERN_PROC,
            KERN_PROC_PID,
            processIdentifier
        ]

        var info = kinfo_proc()
        var size: size_t = MemoryLayout.size(ofValue: info)

        let rc = sysctl(&mib, UInt32(mib.count), &info, &size, nil, 0)
        assert(rc == 0)

        return (info.kp_proc.p_flag & P_TRACED) != 0
    }
}
</code>```

Usage:

```<code>if ProcessInfo.processInfo.isBeingDebugged() {
     print("running under the debugger")
}
</code>```

Title: Detecting debugger on Mac OS X

Body:
I am trying to detect whether my process is being run in a debugger or not and, while in Windows there are many solutions and in Linux I use:

ptrace(PTRACE_ME,0,0,0)

and check its return value, I did not manage to perform the same basic check on Mac OS X.
I tried to use the

ptrace(PT_TRACE_ME,0,0,0)

call but it always returns 0 even when run under gdb.

If I change the request to PT_DENY_ATTACH it correctly stops the debugging but that is not what I want to achieve. Any ideas?

Body:
Here's a Swift version of the function from Apple Technical Q&A QA1361:

import Foundation

extension ProcessInfo {
    /// - returns: true if the process is being debugged, else false.
    public func isBeingDebugged() -> Bool {
        // https://developer.apple.com/library/archive/qa/qa1361/_index.html
        // Technical Q&A QA1361: Detecting the Debugger

        var mib: [Int32] = [
            CTL_KERN,
            KERN_PROC,
            KERN_PROC_PID,
            processIdentifier
        ]

        var info = kinfo_proc()
        var size: size_t = MemoryLayout.size(ofValue: info)

        let rc = sysctl(&mib, UInt32(mib.count), &info, &size, nil, 0)
        assert(rc == 0)

        return (info.kp_proc.p_flag & P_TRACED) != 0
    }
}

Usage:

if ProcessInfo.processInfo.isBeingDebugged() {
     print("running under the debugger")
}


问:
PySpark computing correlation
I want to use pyspark.mllib.stat.Statistics.corr function to compute correlation between two columns of pyspark.sql.dataframe.DataFrame object. corr function expects to take an rdd of Vectors objects. How do I translate a column of df['some_name'] to rdd of Vectors.dense object?

Title: PySpark computing correlation


问:
Entity Framework: Improving Performance when inserting a record in a table with many records
I want to insert a single record into a table with 60 columns (some of them are not required) and 2 million records. It takes about 20 seconds.

var package = new Package()
      {
          DestinationCityId = city.Id,
          OriginCityId = RequestDetails.User.Retailer.CityId,
          State = state,
          CreatedOn = RequestDetails.DateTime,
          CreatedByUserId = RequestDetails.User.Id,
          OrderedOn = RequestDetails.DateTime,
          CustomerName = "a",
          CustomerAddress = "a",
          CustomerEmail = "a",
          CustomerPostalCode = "a",
          CustomerLandPhone = "a",
          CustomerCellPhone = "aa",
          CustomerMessage = "a",
          CustomerSubstitute = "a",
          RetailerPackageDiscount = 0,
          Barcode = "2",
          InternalBarcode = "11111",
          PackagingWeight = 10,
          DeliveryType = PackageDeliveryType.ByPostExpress,
          ProvidedByWarehouse = false,
          NeedReview = false,
          NeedReviewType = NeedReviewType.Unknown,
          RetailerId = retailer.Id,
          Retailer = retailer
      };

DbContext.ZPackages.Add(package);
DbContext.SaveChanges();
```

Any Idea to improve performance?

答:
You could also have a look at the EfCore Bulk Extensions project if you're using EF Core
https://github.com/borisdj/EFCore.BulkExtensions</p>

Body:
I want to insert a single record into a table with 60 columns (some of them are not required) and 2 million records. It takes about 20 seconds.

var package = new Package()
      {
          DestinationCityId = city.Id,
          OriginCityId = RequestDetails.User.Retailer.CityId,
          State = state,
          CreatedOn = RequestDetails.DateTime,
          CreatedByUserId = RequestDetails.User.Id,
          OrderedOn = RequestDetails.DateTime,
          CustomerName = "a",
          CustomerAddress = "a",
          CustomerEmail = "a",
          CustomerPostalCode = "a",
          CustomerLandPhone = "a",
          CustomerCellPhone = "aa",
          CustomerMessage = "a",
          CustomerSubstitute = "a",
          RetailerPackageDiscount = 0,
          Barcode = "2",
          InternalBarcode = "11111",
          PackagingWeight = 10,
          DeliveryType = PackageDeliveryType.ByPostExpress,
          ProvidedByWarehouse = false,
          NeedReview = false,
          NeedReviewType = NeedReviewType.Unknown,
          RetailerId = retailer.Id,
          Retailer = retailer
      };

DbContext.ZPackages.Add(package);
DbContext.SaveChanges();

Any Idea to improve performance?


问:
Convert CSV file To Mysql (.sql) database file?
I am using :
WampServer 2.2,
Apache Version :2.2.21,
PHP Version : 5.3.8,
MySQL Version :5.5.16,
PhpMyadmin Version: 3.4.5...

I have face Problem Of Importing CSV file-(size 13MB*), Error File is Too large...
phpMyadmin allow only 2MB file size ...

So Separate files with 1.83MB file size...then also it does not work ???

And also tell me , How to automatic create table through CSV file ...?

答:
I'd suggest you look at Data Transformer (disclaimer - I'm its developer). It can convert CSV/JSON/XML to SQL. The generated SQL contains "insert" statements for each line and a "create table" statement.

The app works offline and your data never leaves your computer.

You can get it from the Mac App Store or the Microsoft Store.


问:
Too few template-parameter-lists problem
Can anybody please tell me how to make the following pseudo-code compatible with GCC4? I wonder how it works under MSVC...

```<code>typedef int TypeA;
typedef float TypeB;

class MyClass
{
// No base template function, only partially specialized functions...
    inline TypeA myFunction<TypeA>(int a, int b) {} //error: Too few template-parameter-lists
    template<> inline TypeB myFunction<TypeB>(int a, int b) {}
};
</code>```

答:
The proper way of coding that construct would be:

```<code>typedef int TypeA;
typedef float TypeB;
class MyClass
{
    template <typename T>
    T myFunction( int a, int b );
};
template <>
inline TypeA MyClass::myFunction<TypeA>(int a, int b) {}
template <>
inline TypeB MyClass::myFunction<TypeB>(int a, int b) {}
</code>```

Note that the template member function has to be declared inside the class declaration, but specializations must be defined outside of it, at namespace level.

Body:
Can anybody please tell me how to make the following pseudo-code compatible with GCC4? I wonder how it works under MSVC...

typedef int TypeA;
typedef float TypeB;

class MyClass
{
// No base template function, only partially specialized functions...
    inline TypeA myFunction<TypeA>(int a, int b) {} //error: Too few template-parameter-lists
    template<> inline TypeB myFunction<TypeB>(int a, int b) {}
};

Body:
The proper way of coding that construct would be:

typedef int TypeA;
typedef float TypeB;
class MyClass
{
    template <typename T>
    T myFunction( int a, int b );
};
template <>
inline TypeA MyClass::myFunction<TypeA>(int a, int b) {}
template <>
inline TypeB MyClass::myFunction<TypeB>(int a, int b) {}

Note that the template member function has to be declared inside the class declaration, but specializations must be defined outside of it, at namespace level.


问:
How can I resize an image dynamically with CSS as the browser width/height changes?
I wonder how I could make an image resize along with the browser window, here is what I have done so far (or download the whole site in a ZIP).

This works okay in Firefox, but it has problems in Chrome: the image does not always resize, it somehow depends on the size of the window when the page was loaded.

This also works okay in Safari, but sometimes the image is loaded with its minimum width/height. Maybe this is caused by the image size, I am not sure. (If it loads okay, try to refresh several times to see the bug.)

Any ideas on how could I make this more bulletproof? (If JavaScript will be needed I can live with that, too, but CSS is preferable.)

答:
Try

```<code>.img{
   width:100vw; /* Matches to the Viewport Width */
   height:auto;
   max-width:100% !important;
}
</code>```

Only works with display block and inline block, this has no effect on flex items as I've just spent ages trying to find out.

Body:
Try

.img{
   width:100vw; /* Matches to the Viewport Width */
   height:auto;
   max-width:100% !important;
}

Only works with display block and inline block, this has no effect on flex items as I've just spent ages trying to find out.


问:
pyspark show dataframe as table with horizontal scroll in ipython notebook
a pyspark.sql.DataFrame displays messy with DataFrame.show() - lines wrap instead of a scroll.

but displays with pandas.DataFrame.head

I tried these options

```<code>import IPython
IPython.auto_scroll_threshold = 9999

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython.display import display
</code>```

but no luck. Although the scroll works when used within Atom editor with jupyter plugin:

答:
Just edit the css file and you are good to go.

Open the jupyter notebook ../site-packages/notebook/static/style/style.min.css file.

Search for white-space: pre-wrap;, and remove it.

Save the file and restart jupyter-notebook.

Problem fixed. :)

Body:
a pyspark.sql.DataFrame displays messy with DataFrame.show() - lines wrap instead of a scroll.

but displays with pandas.DataFrame.head

I tried these options

import IPython
IPython.auto_scroll_threshold = 9999

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython.display import display

but no luck. Although the scroll works when used within Atom editor with jupyter plugin:


问:
Jinja converting quotation marks to &#39
I'm using a flask project and at one point I render a template with the variable:

```<code>open_modal = "jQuery(document).ready(function($) {$UIkit.modal("#modal1").show();});
</code>```

Which is then rendered in the template with the following code:

```<code><script type="text/javascript">
    {{ open_modal }}
</script>
</code>```

However, when I run the page and check the html it shows instead

```<code>jQuery(document).ready(function($) {$UIkit.modal("#modal1").show();});
</code>```

And so I take it that the quotation mark (') is being converted into '&#34' which is messing with the Javascript syntax. How can this conversion be prevented?

Thanks!

答:
By default jinja2 engine does the conversion. Update your code as below to use safe filter -

```<code>{{ open_modal | safe }}
</code>```

Body:
I'm using a flask project and at one point I render a template with the variable:

open_modal = "jQuery(document).ready(function($) {$UIkit.modal("#modal1").show();});

Which is then rendered in the template with the following code:

However, when I run the page and check the html it shows instead

jQuery(document).ready(function($) {$UIkit.modal("#modal1").show();});

And so I take it that the quotation mark (') is being converted into '&#34' which is messing with the Javascript syntax. How can this conversion be prevented?

Thanks!

Body:
By default jinja2 engine does the conversion. Update your code as below to use safe filter -

{{ open_modal | safe }}


问:
Safari reporting "Unexpected token 'const' " when I open my React App
I have problem with my React App opening in Safari and especially my private routing.Error:

SyntaxError: Unexpected token 'const'

I have ordinary rooting function:

```<code>function App() {
  return (
    <Router history={history}>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/login" component={Login} />
        <PrivateRoute path="/dash" component={Dashboard} />
        <PrivateRoute path="/filters" component={Filters} />
        <PrivateRoute path="/profile" component={Profile} />
        <PrivateRoute path="/map" component={Map} />
        <PrivateRoute path="/bookmarks" component={Bookmarks} />
        <PrivateRoute path="/client/:planID/:isLarge" component={Client} />
        <PrivateRoute
          path="/analyses/:planID/:isLarge"
          component={Analyses}
        />
      </Switch>
    </Router>
  );
}
</code>```

The problem is with this PrivateRoute because when I remove the import and tags it is not displaying the error. Here is my private route file:

```<code>import React from "react";
import { Route, Redirect } from "react-router-dom";

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        sessionStorage.getItem("Token") ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );
};
export default PrivateRoute;
</code>```

I suspect something in returning is not right for Safari but I do not know what. Also this is working in this way on Chrome, Mozilla, IE and Edge. Only Safari have problems.

UPDATE:

Here is the screenshot of issue in Safari:

答:
Fixed it! The problem was arrow function declaration. Safari 5.1 is really bad and for getting well with all browsers it is better to avoid ES6 syntax arrow functions. From this:

```<code>const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        sessionStorage.getItem("Token") ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );
</code>```

I transformed code to this:

```<code>function PrivateRoute({ component: Component, ...rest }) {
  return (
    <Route
      {...rest}
      render={function(props) {
        return sessionStorage.getItem("Token") ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        );
      }}
    />
  );
</code>```

Body:
I have problem with my React App opening in Safari and especially my private routing.Error:

SyntaxError: Unexpected token 'const'

I have ordinary rooting function:

function App() {
  return (
    <Router history={history}>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/login" component={Login} />
        <PrivateRoute path="/dash" component={Dashboard} />
        <PrivateRoute path="/filters" component={Filters} />
        <PrivateRoute path="/profile" component={Profile} />
        <PrivateRoute path="/map" component={Map} />
        <PrivateRoute path="/bookmarks" component={Bookmarks} />
        <PrivateRoute path="/client/:planID/:isLarge" component={Client} />
        <PrivateRoute
          path="/analyses/:planID/:isLarge"
          component={Analyses}
        />
      </Switch>
    </Router>
  );
}

The problem is with this PrivateRoute because when I remove the import and tags it is not displaying the error. Here is my private route file:

import React from "react";
import { Route, Redirect } from "react-router-dom";

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        sessionStorage.getItem("Token") ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );
};
export default PrivateRoute;

I suspect something in returning is not right for Safari but I do not know what. Also this is working in this way on Chrome, Mozilla, IE and Edge. Only Safari have problems.

UPDATE:

Here is the screenshot of issue in Safari:

Body:
Fixed it! The problem was arrow function declaration. Safari 5.1 is really bad and for getting well with all browsers it is better to avoid ES6 syntax arrow functions. From this:

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        sessionStorage.getItem("Token") ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );

I transformed code to this:

function PrivateRoute({ component: Component, ...rest }) {
  return (
    <Route
      {...rest}
      render={function(props) {
        return sessionStorage.getItem("Token") ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        );
      }}
    />
  );


问:
What are some good rigid body dynamics references?
I'm not a math guy in the least but I'm interested in learning about rigid body physics (for the purpose of implementing a basic 3d physics engine).  In school I only took Maths through Algebra II, but I've done 3d dev for years so I have a fairly decent understanding of vectors, quaternions, matrices, etc.  My real problem is reading complex formulas and such, so I'm looking for some decent rigid body dynamics references that will make some sense.

Anyone have any good references?

答:
Chris Hecker has a nice set of articles on his website which were originally published in Game Developer Magazine. They start with 2D physics and progress to 3D.

Physically Based Modeling by David Baraff is also good, but is a bit heavier on the math.

OwnerDisplayName: Cody Brocious

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Cody Brocious

OwnerDisplayName: Niall Ryan


问:
Print Date and Time In Visual Studio C++ build?
How would I print the date and time for the purposes of the build. Ie: When the console for my application starts up I want to do this:

```<code>Binary Build date: 03/03/2009 @ 10:00AM
</code>```

I think this would be a super useful function for all applications to have behind the scenes for programmers, especially in a team environment.

Is there a simple way to do this using Visual Studio 2008 in C++. Thanks.

答:
One way of doing this would be using the built-in __DATE__ and __TIME__ macros. From MSDN (for VS 2005):

__DATE__:
   The compilation date of the current source file. The date is a string literal of the form Mmm dd yyyy. The month name Mmm is the same as for dates generated by the library function asctime declared in TIME.H.

__TIME__:
   The most recent compilation time of the current source file. The time is a string literal of the form hh:mm:ss.

OwnerDisplayName: Brock Woolf

Body:
How would I print the date and time for the purposes of the build. Ie: When the console for my application starts up I want to do this:

Binary Build date: 03/03/2009 @ 10:00AM

I think this would be a super useful function for all applications to have behind the scenes for programmers, especially in a team environment.

Is there a simple way to do this using Visual Studio 2008 in C++. Thanks.

LastEditorDisplayName: Iraimbilanja

OwnerDisplayName: saw-lau