问:
UICollectionView Height resizes on first load
I have a UITableViewCell (MyTableViewCell) that contains a stackview. The first item in the stackview is a subview (MyHeaderView) which contains a few labels and a UICollectionView.
I have a problem when the tableview initially loads where the height of the UICollectionView is larger than the content and it then retracts/jumps to the correct size (the initial height is about twice that of the content). It also only happens when the items in the UICollectionView runs over more than 1 row.

```<code>class MyHeaderView: UIView {

    private var identifierLabel = UILabel()
    private var statementLabel = UILabel()
    private var referenceIdLabel = UILabel()

    private var tagsCollectionView: DynamicHeightCollectionView!

    private var tagsArray = [String]()
    private var tags = [String]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        initTagsCollectionViewLayout()

        backgroundColor = .red
        self.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        contentView.addSubview(identifierLabel)
        contentView.addSubview(tagsCollectionView)
        contentView.addSubview(statementLabel)
        contentView.addSubview(referenceIdLabel)

        identifierLabel.layer.borderWidth = 4
        identifierLabel.layer.borderColor = UIColor.white.cgColor
        identifierLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalToSuperview()
            make.width.lessThanOrEqualTo(30)
            make.height.equalTo(30)
        }

        tagsCollectionView.snp.makeConstraints { make in
            make.top.equalTo(identifierLabel.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }

        referenceIdLabel.numberOfLines = 0
        referenceIdLabel.snp.makeConstraints { make in
            make.top.equalTo(tagsCollectionView.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }

        statementLabel.numberOfLines = 0
        statementLabel.snp.makeConstraints { make in
            make.top.equalTo(referenceIdLabel.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }

    lazy var contentView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 400))
        view.layer.borderWidth = 4
        view.layer.borderColor = UIColor.white.cgColor

        view.backgroundColor = UIColor.red
        return view
    }()

    func initTagsCollectionViewLayout() {
        let flowLayout = LeftAlignedCollectionViewFlowLayout()

        tagsCollectionView = DynamicHeightCollectionView(frame: .zero, collectionViewLayout: flowLayout)

        tagsCollectionView.delegate = self
        tagsCollectionView.dataSource = self
        tagsCollectionView.isScrollEnabled = false
        tagsCollectionView.backgroundColor = .white

        flowLayout.estimatedItemSize = CGSize(width: 50, height: 20)
        flowLayout.minimumInteritemSpacing = 4
        flowLayout.minimumLineSpacing = 8
        flowLayout.scrollDirection = .vertical

        self.tagsCollectionView.collectionViewLayout = flowLayout
        self.tagsCollectionView.layoutIfNeeded()
        self.tagsCollectionView.register(UINib.init(nibName: Constants.tagsCollectionCellNibName, bundle: nil), forCellWithReuseIdentifier: Constants.tagsCollectionCellReuseID)
    }

    // MARK: Set up view
    func setUpView(observation: Observation) {
        identifierLabel.text = observation.identifier
        statementLabel.text = observation.statement
        referenceIdLabel.text = observation.referenceID

        tagsArray = [String]()

        if let tags = observation.tags, tags.count > 0 {
            for tag in tags {
                tagsArray.append(tag)
            }
        }

        if tagsArray.count > 0 {
            tagsCollectionView.reloadData()
            //tagsCollectionView.setNeedsLayout()
            tagsCollectionView.layoutIfNeeded()
        }
    }

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        if (self.superview != nil) {
            self.superview?.layoutIfNeeded()
        }

        return tagsCollectionView.contentSize
    }
}

extension MyHeaderView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tagsArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell = UICollectionViewCell()

        switch collectionView {
        case tagsCollectionView:
            let tagsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.tagsCollectionCellReuseID, for: indexPath) as! TagsCollectionViewCell

            tagsCollectionViewCell.initRequirementTag(tagText: self.tagsArray[indexPath.item])

            cell = tagsCollectionViewCell

        default:
            break
        }

        return cell
    }
}

// MARK: - Constants
private enum Constants {
    static let tagsCollectionCellReuseID = "TagsCollectionViewCell"
    static let tagsCollectionCellNibName = "TagsCollectionViewCell"
}

class MyTableViewCell: UITableViewCell {

    private var stackView = UIStackView()
    private var myHeaderView = MyHeaderView()
    private var observation: Observation?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        self.addSubview(stackView)

        stackView.axis = .vertical
        stackView.spacing = 4
        stackView.distribution = .fillProportionally
        stackView.alignment = .fill
        stackView.arrangedSubviews.forEach({ $0.removeFromSuperview() }) // clear stack view on each load

        stackView.addArrangedSubview(myHeaderView)

        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            //make.width.equalToSuperview()
        }

        myHeaderView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

    }

    func setupView(observation: Observation) {
        self.observation = observation

        myHeaderView.setUpView(observation: observation)
    }

}

class DynamicHeightCollectionView: UICollectionView {

    override func layoutSubviews() {
        super.layoutSubviews()
        if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
            self.invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        return contentSize
    }
}

class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)

        var leftMargin = sectionInset.left
        var maxY: CGFloat = -1.0
        attributes?.forEach { layoutAttribute in
            if layoutAttribute.frame.origin.y >= maxY {
                leftMargin = sectionInset.left
            }

            layoutAttribute.frame.origin.x = leftMargin

            leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
            maxY = max(layoutAttribute.frame.maxY , maxY)
        }

        return attributes
    }
}

// in tableview controller
var obs1 = Observation(identifier: "1.1", statement: "custom statement test", referenceID: "reference id test", tags: ["tag 1", "tag 2", "tag 3", "tag 4", "tag 5", "tag 6", "tag 7", "tag 8", "tag 9", "tag 10", "tag 11", "tag 12", "tag 13", "tag 14", "tag 15", "tag 16", "tag 17", "tag 18", "tag 19", "tag 20"])

    var obs2 = Observation(identifier: "1.2", statement: "custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines", referenceID: "reference id test that runs onto multiple lines, reference id test that runs onto multiple lines reference id test that runs onto multiple lines reference id test that runs onto multiple lines reference id test that runs onto multiple lines", tags: ["tag 1", "tag 2", "tag 3", "tag 4", "tag 5", "tag 6", "tag 7", "tag 8"])

    var obs3 = Observation(identifier: "1.3", statement: "custom statement test", referenceID: "reference id test", tags: [])

    var obs4 = Observation(identifier: "1.4", statement: "custom statement test", referenceID: "reference id test", tags: [])

var obs: [Observation]
obs.append(obs1)
obs.append(obs2)
obs.append(obs3)
obs.append(obs4)

struct Observation {
    var identifier: String
    var statement: String
    var referenceID: String
    var tags: [String]
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ObservationTableViewCellV2") as! ObservationTableViewCellV2

        let observation = obs[indexPath.row] as! Observation
        cell.setupView(observation: observation)

        return cell
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return obs.count
    }
</code>```

I have tried changing the estimated item size and the UICollectionViewDelegateFlowLayout sizeForItemAt but it makes no difference.

The UICollectionView is highlighted in blue. On first load it appears as:

Then a split second later it resizes to the correct size:

答:
Try to explicitly run layoutIfNeeded on the main thread inside of initTagsCollectionViewLayout. That could be the issue here.</p>

```<code>DispatchQueue.main.async {
   self.tagsCollectionView.layoutIfNeeded()
}
</code>```

Body:
I have a UITableViewCell (MyTableViewCell) that contains a stackview. The first item in the stackview is a subview (MyHeaderView) which contains a few labels and a UICollectionView.
I have a problem when the tableview initially loads where the height of the UICollectionView is larger than the content and it then retracts/jumps to the correct size (the initial height is about twice that of the content). It also only happens when the items in the UICollectionView runs over more than 1 row.

class MyHeaderView: UIView {

    private var identifierLabel = UILabel()
    private var statementLabel = UILabel()
    private var referenceIdLabel = UILabel()

    private var tagsCollectionView: DynamicHeightCollectionView!

    private var tagsArray = [String]()
    private var tags = [String]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        initTagsCollectionViewLayout()

        backgroundColor = .red
        self.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        contentView.addSubview(identifierLabel)
        contentView.addSubview(tagsCollectionView)
        contentView.addSubview(statementLabel)
        contentView.addSubview(referenceIdLabel)

        identifierLabel.layer.borderWidth = 4
        identifierLabel.layer.borderColor = UIColor.white.cgColor
        identifierLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalToSuperview()
            make.width.lessThanOrEqualTo(30)
            make.height.equalTo(30)
        }

        tagsCollectionView.snp.makeConstraints { make in
            make.top.equalTo(identifierLabel.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }

        referenceIdLabel.numberOfLines = 0
        referenceIdLabel.snp.makeConstraints { make in
            make.top.equalTo(tagsCollectionView.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }

        statementLabel.numberOfLines = 0
        statementLabel.snp.makeConstraints { make in
            make.top.equalTo(referenceIdLabel.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }

    lazy var contentView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 400))
        view.layer.borderWidth = 4
        view.layer.borderColor = UIColor.white.cgColor

        view.backgroundColor = UIColor.red
        return view
    }()

    func initTagsCollectionViewLayout() {
        let flowLayout = LeftAlignedCollectionViewFlowLayout()

        tagsCollectionView = DynamicHeightCollectionView(frame: .zero, collectionViewLayout: flowLayout)

        tagsCollectionView.delegate = self
        tagsCollectionView.dataSource = self
        tagsCollectionView.isScrollEnabled = false
        tagsCollectionView.backgroundColor = .white

        flowLayout.estimatedItemSize = CGSize(width: 50, height: 20)
        flowLayout.minimumInteritemSpacing = 4
        flowLayout.minimumLineSpacing = 8
        flowLayout.scrollDirection = .vertical

        self.tagsCollectionView.collectionViewLayout = flowLayout
        self.tagsCollectionView.layoutIfNeeded()
        self.tagsCollectionView.register(UINib.init(nibName: Constants.tagsCollectionCellNibName, bundle: nil), forCellWithReuseIdentifier: Constants.tagsCollectionCellReuseID)
    }

    // MARK: Set up view
    func setUpView(observation: Observation) {
        identifierLabel.text = observation.identifier
        statementLabel.text = observation.statement
        referenceIdLabel.text = observation.referenceID

        tagsArray = [String]()

        if let tags = observation.tags, tags.count > 0 {
            for tag in tags {
                tagsArray.append(tag)
            }
        }

        if tagsArray.count > 0 {
            tagsCollectionView.reloadData()
            //tagsCollectionView.setNeedsLayout()
            tagsCollectionView.layoutIfNeeded()
        }
    }

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        if (self.superview != nil) {
            self.superview?.layoutIfNeeded()
        }

        return tagsCollectionView.contentSize
    }
}

extension MyHeaderView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tagsArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell = UICollectionViewCell()

        switch collectionView {
        case tagsCollectionView:
            let tagsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.tagsCollectionCellReuseID, for: indexPath) as! TagsCollectionViewCell

            tagsCollectionViewCell.initRequirementTag(tagText: self.tagsArray[indexPath.item])

            cell = tagsCollectionViewCell

        default:
            break
        }

        return cell
    }
}

// MARK: - Constants
private enum Constants {
    static let tagsCollectionCellReuseID = "TagsCollectionViewCell"
    static let tagsCollectionCellNibName = "TagsCollectionViewCell"
}

class MyTableViewCell: UITableViewCell {

    private var stackView = UIStackView()
    private var myHeaderView = MyHeaderView()
    private var observation: Observation?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        self.addSubview(stackView)

        stackView.axis = .vertical
        stackView.spacing = 4
        stackView.distribution = .fillProportionally
        stackView.alignment = .fill
        stackView.arrangedSubviews.forEach({ $0.removeFromSuperview() }) // clear stack view on each load

        stackView.addArrangedSubview(myHeaderView)

        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            //make.width.equalToSuperview()
        }

        myHeaderView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

    }

    func setupView(observation: Observation) {
        self.observation = observation

        myHeaderView.setUpView(observation: observation)
    }

}

class DynamicHeightCollectionView: UICollectionView {

    override func layoutSubviews() {
        super.layoutSubviews()
        if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
            self.invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        return contentSize
    }
}

class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)

        var leftMargin = sectionInset.left
        var maxY: CGFloat = -1.0
        attributes?.forEach { layoutAttribute in
            if layoutAttribute.frame.origin.y >= maxY {
                leftMargin = sectionInset.left
            }

            layoutAttribute.frame.origin.x = leftMargin

            leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
            maxY = max(layoutAttribute.frame.maxY , maxY)
        }

        return attributes
    }
}

// in tableview controller
var obs1 = Observation(identifier: "1.1", statement: "custom statement test", referenceID: "reference id test", tags: ["tag 1", "tag 2", "tag 3", "tag 4", "tag 5", "tag 6", "tag 7", "tag 8", "tag 9", "tag 10", "tag 11", "tag 12", "tag 13", "tag 14", "tag 15", "tag 16", "tag 17", "tag 18", "tag 19", "tag 20"])

    var obs2 = Observation(identifier: "1.2", statement: "custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines, custom statement test thats runs onto multiple lines", referenceID: "reference id test that runs onto multiple lines, reference id test that runs onto multiple lines reference id test that runs onto multiple lines reference id test that runs onto multiple lines reference id test that runs onto multiple lines", tags: ["tag 1", "tag 2", "tag 3", "tag 4", "tag 5", "tag 6", "tag 7", "tag 8"])

    var obs3 = Observation(identifier: "1.3", statement: "custom statement test", referenceID: "reference id test", tags: [])

    var obs4 = Observation(identifier: "1.4", statement: "custom statement test", referenceID: "reference id test", tags: [])

var obs: [Observation]
obs.append(obs1)
obs.append(obs2)
obs.append(obs3)
obs.append(obs4)

struct Observation {
    var identifier: String
    var statement: String
    var referenceID: String
    var tags: [String]
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ObservationTableViewCellV2") as! ObservationTableViewCellV2

        let observation = obs[indexPath.row] as! Observation
        cell.setupView(observation: observation)

        return cell
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return obs.count
    }

I have tried changing the estimated item size and the UICollectionViewDelegateFlowLayout sizeForItemAt but it makes no difference.

The UICollectionView is highlighted in blue. On first load it appears as:

Then a split second later it resizes to the correct size:

Body:
Try to explicitly run layoutIfNeeded on the main thread inside of initTagsCollectionViewLayout. That could be the issue here.

DispatchQueue.main.async {
   self.tagsCollectionView.layoutIfNeeded()
}


来源: stackexchange

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

答:
The best way to do this that keeps the table clean is to implement the following:

The table needs at least the account ID with a UNIQUE index and foreign key to the accounts table, the hash with a UNIQUE index and a timestamp.

In the page that creates the link, do not allow "reset my password" based on information that can be obtained by a random person. If you do this, one can fill your table with reset password requests and generate spam and security concerns with your users.

In the page where the link is verified first delete all expired records by comparing NOW() with the stored timestamp, then simply SELECT using WHERE='$hash' (of course, you sanitize $hash). Given the UNIQUE index on the hash, this can only return one row or no rows.

The UNIQUE index on the account ID ensures that people cannot request multiple resets within the expiration time.

ContentLicense: CC BY-SA 3.0


问:
What kind of algorithm paradigm/algorithm design paradigm is A* (A star) pathfinding algorithm?
I'm not sure about what kind of design paradigm is A* (A star) pathfinding algorithm. According of the topics of the book "Introduction to the Design & Analysis of Algorithms" by Anany Levitin, I think the design paradigm is a greedy technique, because this algorithm is a combination of Dijktra's algorithm and greedy best first which are greedy techniques. But I'm not sure if that is a good reasoning.

Edit: According Emma comment, she gave me a link of Wikipedia where it says " Dijkstra and A* are special cases of dynamic programming. A* itself is a special case of a generalization of branch and bound." link.
But in this other Wikipedia link says "Dijkstra's algorithm and the related A* search algorithm are verifiably optimal greedy algorithms for graph search and shortest path finding."

答: I think the main paradigm of A* is exhaustive search (or branch and bound (b&b), many people consider exhaustive search and b&b as two different paradigms, but i think b&b is just a technique for implementing and improving exhaustive search), like other exhaustive search, A* will explore the entire solution space (exclude solutions determined is worst than optimal solution). Greedy is just an additional technique, used to navigate the search in the most promising direction.</p>

ContentLicense: CC BY-SA 4.0


问:
Python, how to calculate the difference between lists
I have list

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

and need to calculate the difference between two neighbor points in this list.

For example, (B-A), (C-B), (D-C) and get this output:

output = [(20, -2), (43, 7), (-70, 0)

Are there any fast ways how to do it?

答:
if you dont want to assume anything about the length</p>

```<code>i=0
index=0
while i<len(a)-1:
    for ValueA in a[i]:
        if str(ValueA).isdigit():
            print(str(a[i+1][index])+" "+str(ValueA))
        index+=1
    i+=1
    index=0
</code>```

Body:
if you dont want to assume anything about the length

i=0
index=0
while i<len(a)-1:
    for ValueA in a[i]:
        if str(ValueA).isdigit():
            print(str(a[i+1][index])+" "+str(ValueA))
        index+=1
    i+=1
    index=0


问:
Sharepoint list item using Api Rest
I need to get a list's items, so I created this function

```<code>export function retrieveSPItems(spToken, alias) {
  var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
  var myHeaders = new Headers({
    Accept: "application/json;odata=nometadata",
    Authorization: spToken,
  });
  return fetch(url, {
    method: "get",
    headers: myHeaders,
  }).then((response) => response.json());
}
</code>```

As a output I get 3000.

when I change the url to

```<code>var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;
</code>```

I get an empty list!

PS :

It's work in Postman with no problem

The token is generated by adaljs :

Get Token

authContext.acquireToken(SP_BASE_URL, function (error, token){....})

Adal config

```<code>export const adalConfig = {
  tenant: CURRENT_TENANT,
  clientId: CURRENT_APP_ID,
  endpoints: {
    api: CURRENT_APP_ID,
    graph: GRAPH_BASE_URL,
    sharepoint: SP_BASE_URL,
  },
  cacheLocation: "localStorage",
  validateAuthority: true,
};
</code>```

So I need to know :

what the reason fot this issue?

How can I fix it?

答:
It's too general information, you need debug and figure out the detailed error information.

My test demo:

```<code><script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="Scripts/adal.js"></script>
    <script type="text/javascript">

        var authContext = null;
        var user = null;

        (function () {
            window.config = {
                instance: 'https://login.microsoftonline.com/',
                tenant: 'xxx.onmicrosoft.com',
                clientId: '9afc37cb-x-x-x-xxx',
                postLogoutRedirectUri: window.location.origin,
                endpoints: {
                    graphApiUri: "https://graph.microsoft.com",
                    sharePointUri: "https://xxx.sharepoint.com/",
                },
                    cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
            };

            authContext = new AuthenticationContext(config);
            var isCallback = authContext.isCallback(window.location.hash);
            authContext.handleWindowCallback();
            //$errorMessage.html(authContext.getLoginError());
            if (isCallback && !authContext.getLoginError()) {
                window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
            }

            user = authContext.getCachedUser();
            if (!user) {
                authContext.login();
            }
            //authContext.acquireToken(window.config.clientId, function (error, token) {
            //    console.log('---');
            //})
            authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
                alert(token);
                if (error || !token) {
                    console.log("ADAL error occurred: " + error);
                    return;
                }
                else {
                    var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";

                    $.ajax({
                        type: "GET",
                        url: listUri,
                        headers: {
                            "Authorization": "Bearer " + token,
                            "accept": "application/json;odata=verbose"
                        }
                    }).done(function (response) {
                        console.log("Successfully fetched list from SharePoint.");
                        var items = response.d.results;
                        for (var i = 0; i < items.length; i++) {
                            console.log(items[i].Title);
                            $("#SharePoint").append("<li>" + items[i].Title + "</li>");
                        }
                    }).fail(function () {
                        console.log("Fetching list from SharePoint failed.");
                    })
                }
            })

        }());
    </script>
</code>```

Title: Sharepoint list item using Api Rest

Body:
I need to get a list's items, so I created this function

export function retrieveSPItems(spToken, alias) {
  var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
  var myHeaders = new Headers({
    Accept: "application/json;odata=nometadata",
    Authorization: spToken,
  });
  return fetch(url, {
    method: "get",
    headers: myHeaders,
  }).then((response) => response.json());
}

As a output I get 3000.

when I change the url to

var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;

I get an empty list!

PS :

It's work in Postman with no problem

The token is generated by adaljs :

Get Token

authContext.acquireToken(SP_BASE_URL, function (error, token){....})

Adal config

export const adalConfig = {
  tenant: CURRENT_TENANT,
  clientId: CURRENT_APP_ID,
  endpoints: {
    api: CURRENT_APP_ID,
    graph: GRAPH_BASE_URL,
    sharepoint: SP_BASE_URL,
  },
  cacheLocation: "localStorage",
  validateAuthority: true,
};

So I need to know :

what the reason fot this issue?

How can I fix it?

Body:
It's too general information, you need debug and figure out the detailed error information.

My test demo:

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="Scripts/adal.js"></script>
    <script type="text/javascript">

        var authContext = null;
        var user = null;

        (function () {
            window.config = {
                instance: 'https://login.microsoftonline.com/',
                tenant: 'xxx.onmicrosoft.com',
                clientId: '9afc37cb-x-x-x-xxx',
                postLogoutRedirectUri: window.location.origin,
                endpoints: {
                    graphApiUri: "https://graph.microsoft.com",
                    sharePointUri: "https://xxx.sharepoint.com/",
                },
                    cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
            };

            authContext = new AuthenticationContext(config);
            var isCallback = authContext.isCallback(window.location.hash);
            authContext.handleWindowCallback();
            //$errorMessage.html(authContext.getLoginError());
            if (isCallback && !authContext.getLoginError()) {
                window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
            }

            user = authContext.getCachedUser();
            if (!user) {
                authContext.login();
            }
            //authContext.acquireToken(window.config.clientId, function (error, token) {
            //    console.log('---');
            //})
            authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
                alert(token);
                if (error || !token) {
                    console.log("ADAL error occurred: " + error);
                    return;
                }
                else {
                    var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";

                    $.ajax({
                        type: "GET",
                        url: listUri,
                        headers: {
                            "Authorization": "Bearer " + token,
                            "accept": "application/json;odata=verbose"
                        }
                    }).done(function (response) {
                        console.log("Successfully fetched list from SharePoint.");
                        var items = response.d.results;
                        for (var i = 0; i < items.length; i++) {
                            console.log(items[i].Title);
                            $("#SharePoint").append("<li>" + items[i].Title + "</li>");
                        }
                    }).fail(function () {
                        console.log("Fetching list from SharePoint failed.");
                    })
                }
            })

        }());
    </script>


问:
python search the user name
```<code>Mon Apr 27 18:12:54 '<rdpDirect> ITC\109975@win_itsskdcbkp2_10.18.2.104
Mon Apr 27 18:14:31 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:14:32 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147
</code>```

From the above text, need to search user name which is mentioned between the "\" and "@" sign. This can be numeric, characters, or alphanumeric.

eg: in the above example, 109975, VINOTHKUMAR, UITSMUSR etc.

答:
A simple regex should do the job. You can try \\(.*?)\@.
This "captures" text between \ and @

Title: python search the user name

Body:
Mon Apr 27 18:12:54 '<rdpDirect> ITC\109975@win_itsskdcbkp2_10.18.2.104
Mon Apr 27 18:14:31 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:14:32 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147

From the above text, need to search user name which is mentioned between the "\" and "@" sign. This can be numeric, characters, or alphanumeric.

eg: in the above example, 109975, VINOTHKUMAR, UITSMUSR etc.


问:
Find top parent in hierarchy
I have a SQL table with different project codes. A project can consist of multiple levels (sub-projects). I want to find the top level (top parent) for each of the project codes using SQL coding.

My table looks like this:

```<code>CREATE TABLE #Temp
(
    Child nvarchar(100),
    Parent nvarchar(100)

)

insert into #Temp (Child,Parent)
values
('17210',Null),
('17210-100','17210'),
('17210-100-100','17210-100'),
('1310',Null),
('1310-100','1310'),
('1310-100-100','1310-100')
;

select * from #Temp

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End
</code>```

This is the result I want:

```<code>Child           Parent      TopParent
17210           NULL        17210
17210-100       17210       17210
17210-100-100   17210-100   17210
1310            NULL        1310
1310-100        1310        1310
1310-100-100    1310-100    1310
</code>```

How do I find the top parent for each project number (child)? I have an idea that using recursive CTE's might be the solution, but I am not sure if this is the right approach.

Any help is much appreciated.

答:
Try this one :

```<code>CREATE TABLE Category
(
    Child nvarchar(100),
    Parent nvarchar(100)

)

insert into Category (Child,Parent)
values
('17210',Null),
('17210-100','17210'),
('17210-100-100','17210-100'),
('1310',Null),
('1310-100','1310'),
('1310-100-100','1310-100')
;

With cte (Child , Parent, LevelID, topparent)
as
(
    --Anchor
    Select Child , Parent ,0 as LevelID , Child AS TopParent
    From Category
    Where Parent is Null

    Union All

    Select c.Child , c.Parent , cte.LevelID - 1 , cte.TopParent
    From Category c inner join  cte On cte.Child=c.Parent
)

Select c.Child , c.Parent ,cte.TopParent
        From cte
</code>```

You can use CTE for recursive query and find top level id for parents like above query.
this model very fast and useful.

i hope you wish the best

Title: Find top parent in hierarchy

Body:
I have a SQL table with different project codes. A project can consist of multiple levels (sub-projects). I want to find the top level (top parent) for each of the project codes using SQL coding.

My table looks like this:

CREATE TABLE #Temp
(
    Child nvarchar(100),
    Parent nvarchar(100)

)

insert into #Temp (Child,Parent)
values
('17210',Null),
('17210-100','17210'),
('17210-100-100','17210-100'),
('1310',Null),
('1310-100','1310'),
('1310-100-100','1310-100')
;

select * from #Temp

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End

This is the result I want:

Child           Parent      TopParent
17210           NULL        17210
17210-100       17210       17210
17210-100-100   17210-100   17210
1310            NULL        1310
1310-100        1310        1310
1310-100-100    1310-100    1310

How do I find the top parent for each project number (child)? I have an idea that using recursive CTE's might be the solution, but I am not sure if this is the right approach.

Any help is much appreciated.

Body:
Try this one :

CREATE TABLE Category
(
    Child nvarchar(100),
    Parent nvarchar(100)

)

insert into Category (Child,Parent)
values
('17210',Null),
('17210-100','17210'),
('17210-100-100','17210-100'),
('1310',Null),
('1310-100','1310'),
('1310-100-100','1310-100')
;

With cte (Child , Parent, LevelID, topparent)
as
(
    --Anchor
    Select Child , Parent ,0 as LevelID , Child AS TopParent
    From Category
    Where Parent is Null

    Union All

    Select c.Child , c.Parent , cte.LevelID - 1 , cte.TopParent
    From Category c inner join  cte On cte.Child=c.Parent
)

Select c.Child , c.Parent ,cte.TopParent
        From cte

You can use CTE for recursive query and find top level id for parents like above query.
this model very fast and useful.

i hope you wish the best


问:
background-image property is not showing the image in css
I was trying to put background image but it is not showing.</p>

```<code>.jumbotron{
   background-image: url("/src/assets/shop1.png");
   background-size: cover;
}

<div class="jumbotron">
   Welcome to Home Page
</div>
</code>```

答:
The background image will look at the height and width of the div. Please follow the code to see the image.

```<code>.jumbotron {
   background-image: url('https://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg');
  background-size: 100% 100%;
  height: 100px;
  width: 100%;
  background-repeat: no-repeat;
}
</code>```

Working demo

Body:
I was trying to put background image but it is not showing.

.jumbotron{
   background-image: url("/src/assets/shop1.png");
   background-size: cover;
}

   Welcome to Home Page

Body:
The background image will look at the height and width of the div. Please follow the code to see the image.

.jumbotron {
   background-image: url('https://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg');
  background-size: 100% 100%;
  height: 100px;
  width: 100%;
  background-repeat: no-repeat;
}

Working demo


问:
What does this one liner means in lambda function in Python?
I'm stuck in this lambda one-liner. This one-liner is for sorting the string in a list but don't know how this actually functions? Kindly help me to understand this.
This is the motive of the below function:

sort_item_list_by_author(): Accepts the new list of books and returns it sorted in the alphabetical order of their author names. Note: While sorting the author names in alphabetical order, ignore the special characters including space, if there are any.

```<code>    def sort_item_list_by_author(self,new_item_list):
       new_item_list.sort(key=lambda x:''.join(e for e in x.get_author_name() if e.isalnum())) #problem causing line

    item11=Item("Broken Wing","Sarojini Naidu",2012)
    item12=Item("Guide","R.K.Narayanan",2001)
    item13=Item("Indian Summers","John Mathews",2001)
    item14=Item("Innocent in Death","J.D.Robb",2010)
    item15=Item("Life of Pi","Yann Martel",2010 )
    item16=Item("Sustainability","Johny",2016)
    item17=Item("Look Ahead","E.M.Freddy",2012 )

    new_item_list=[item11,item12,item13,item14,item15,item16,item17]
    new_item_list_sorted=library.sort_item_list_by_author(new_item_list)
</code>```

答:
In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.Let's see an example.

>>> addition=lambda x1,x2:x1+x2
>>> subtraction=lambda x1,x2:x1-x2
>>> addition(10,20)
30
>>> subtraction(10,20)
-10
>>> #there is another way also
>>>(lambda num1, num2: num1+num2)(10,20)
30
```

<p>Now Suppose we have a list of items(integers and strings with numeric contents)</p>

```numbers = [1,"2", "5", 3, 4, "8", "-1", "-11"]
```

<p>Now I am using sorted function to sort it, You can use sort also but as we know sort function alters the original data but the sorted returns a new sorted list</p>

```>>> numbers = [1,"2", "5", 3, 4, "8", "-1", "-11"]
>>> sorted(numbers)
[1, 3, 4, '-1', '-11', '2', '5', '8']
>>>
```

<p>But this is not expected answer</p>

```['-11', '-1', 1, '2', 3, 4, '5', '8']
```

<p>so here we've to used to key keyword as a argument</p>

```>>> sorted(numbers, key=int)
['-11', '-1', 1, '2', 3, 4, '5', '8']
>>> sorted(['There', 'are','some', 'sort', 'words'], key=lambda word: word.lower())
['are', 'some', 'sort', 'There', 'words']
```

<p>Which is same as</p>

```sorted(['There', 'are','some', 'sort', 'words'],key=str.lower)
```

According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element
key=str.lower The default value is None (compare the elements directly)

Body:
I'm stuck in this lambda one-liner. This one-liner is for sorting the string in a list but don't know how this actually functions? Kindly help me to understand this.
This is the motive of the below function:

sort_item_list_by_author(): Accepts the new list of books and returns it sorted in the alphabetical order of their author names. Note: While sorting the author names in alphabetical order, ignore the special characters including space, if there are any.

    def sort_item_list_by_author(self,new_item_list):
       new_item_list.sort(key=lambda x:''.join(e for e in x.get_author_name() if e.isalnum())) #problem causing line

    item11=Item("Broken Wing","Sarojini Naidu",2012)
    item12=Item("Guide","R.K.Narayanan",2001)
    item13=Item("Indian Summers","John Mathews",2001)
    item14=Item("Innocent in Death","J.D.Robb",2010)
    item15=Item("Life of Pi","Yann Martel",2010 )
    item16=Item("Sustainability","Johny",2016)
    item17=Item("Look Ahead","E.M.Freddy",2012 )

    new_item_list=[item11,item12,item13,item14,item15,item16,item17]
    new_item_list_sorted=library.sort_item_list_by_author(new_item_list)

Body:
In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.Let's see an example.

>>> addition=lambda x1,x2:x1+x2
>>> subtraction=lambda x1,x2:x1-x2
>>> addition(10,20)
30
>>> subtraction(10,20)
-10
>>> #there is another way also
>>>(lambda num1, num2: num1+num2)(10,20)
30

Now Suppose we have a list of items(integers and strings with numeric contents)

numbers = [1,"2", "5", 3, 4, "8", "-1", "-11"]

Now I am using sorted function to sort it, You can use sort also but as we know sort function alters the original data but the sorted returns a new sorted list

>>> numbers = [1,"2", "5", 3, 4, "8", "-1", "-11"]
>>> sorted(numbers)
[1, 3, 4, '-1', '-11', '2', '5', '8']
>>>

But this is not expected answer

['-11', '-1', 1, '2', 3, 4, '5', '8']

so here we've to used to key keyword as a argument

>>> sorted(numbers, key=int)
['-11', '-1', 1, '2', 3, 4, '5', '8']
>>> sorted(['There', 'are','some', 'sort', 'words'], key=lambda word: word.lower())
['are', 'some', 'sort', 'There', 'words']

Which is same as

sorted(['There', 'are','some', 'sort', 'words'],key=str.lower)

According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element
key=str.lower The default value is None (compare the elements directly)


问:
QListView max number of items in view
I need to calculate max number of items in current view of QListView.
I wrote code like this:

```<code>void MyListView::resizeEvent(QResizeEvent *event)
{
    QListView::resizeEvent(event);

    QFontMetrics fm (this->font());
    int fontHeight = fm.lineSpacing();

    QRect cr = contentsRect();
    int windowHeight = cr.bottom() - cr.top();

    int maxItemsCount = windowHeight / fontHeight;
    qDebug()<<"max items in view: "<< maxItemsCount;

}
</code>```

but calculated max number of items is is incorrect.
E.g. in case of my window height and font height I get 32 max items in view when in fact current view has 28 items. Perhaps someone can suggest something, how to calculate it properly?

答:
My idea is to use QListView::indexAt() (inherited from QAbstractView) to obtain the row index for

the top-left corner

the bottom-left corner

of the list view viewport and determining the number of visible items by difference of them.

To check this out, I made an MCVE testQListViewNumVisibleItems.cc:

```<code>// Qt header:
#include <QtWidgets>

class ListWidget: public QListWidget {

  public:
    ListWidget(QWidget *pQParent = nullptr): QListWidget(pQParent) { }
    virtual ~ListWidget() = default;
    ListWidget(const ListWidget&) = delete;
    ListWidget& operator=(const ListWidget&) = delete;

    int getNumVisibleItems() const
    {
      const QSize size = viewport()->size();
      const QModelIndex qMIdx0 = indexAt(QPoint(0, 0));
      const QModelIndex qMIdx1 = indexAt(QPoint(0, size.height() - 1));
      //qDebug() << "qMIdx0:" << qMIdx0 << "qMIdx1:" << qMIdx1;
      return qMIdx0.isValid()
        ? (qMIdx1.isValid() ? qMIdx1.row() : count()) - qMIdx0.row()
        : 0;
    }
};

const int MaxItems = 20;

// main application
int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  ListWidget qLst;
  qLst.resize(200, 200);
  qLst.show();
  // timer to populate list view
  using namespace std::chrono_literals;
  QTimer qTimer;
  qTimer.setInterval(1000ms);
  // install signal handlers
  int n = 0;
  QObject::connect(&qTimer, &QTimer::timeout,
    [&]() {
      qLst.addItem(QString("item %0").arg(++n));
      qDebug() << "Visible items:" << qLst.getNumVisibleItems();
      if (n >= MaxItems) qTimer.stop();
    });
  // runtime loop
  qTimer.start();
  return app.exec();
}
</code>```

and a CMakeLists.txt:

project(QListViewNumVisibleItems)

cmake_minimum_required(VERSION 3.10.0)

set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

find_package(Qt5Widgets CONFIG REQUIRED)

include_directories("${CMAKE_SOURCE_DIR}")

add_executable(testQListViewNumVisibleItems testQListViewNumVisibleItems.cc)

target_link_libraries(testQListViewNumVisibleItems Qt5::Widgets)
```

<p>built and tested in VS2017 on Windows 10:</p>

<p><img src="https://i.stack.imgur.com/Rf4j4.gif" alt="snapshot of testQListViewNumVisibleItems.exe (animated)"></p>

<hr>

<p>After having implemented what came in my mind, I googled a bit to possibly see other approaches. (I admit I should've done before.)</p>

<p>Thereby I found the following possible duplicate:</p>

<p>SO: <strong>Simple way to get all visible items in the QListView</strong></p>

<p>The accepted answer doesn't contain much more than the hint for <code>indexAt</code> and a link to a Qt-FAQ article:</p>

<blockquote>
  <p><strong>How can i get hold of all of the visible items in my QListView?</strong></p>

  <p>In order to get hold of the visible items in a QListView http://doc.qt.io/qt-5/qlistview.html, then you can iterate over them using indexAt() http://doc.qt.io/qt-5/qlistview.html#indexAt. You can get hold of the first visible item using indexAt(QPoint(0, 0)), then in order to get the index at the next position then use visualRect() http://doc.qt.io/qt-5/qlistview.html#visualRect to find out what your next call to itemAt() should be. This position would be:</p>

```visualRect.y() + visualRect.height() + 1 effectively.
```

  <p>See the following example for an illustration:</p>

```#include <QtGui>
QList <QModelIndex>myList;

class ListView : public QListView
{
  Q_OBJECT
public:
  ListView()
  {
    QStringListModel *myModel = new QStringListModel(this);
    QStringList list;
    list << "a" << "b" <<"c" <<"d" <<"e" <<"f" <<"g" <<"h" <<"i" <<"j" <<"k";
    myModel->setStringList(list);
    setModel(myModel);
    QTimer::singleShot(3000, this, SLOT(test1()));
  }
  public slots:
    void test1()
    {

      QModelIndex firstIndex = indexAt(QPoint(0, 0));
      if (firstIndex.isValid()) {
        myList << firstIndex;
      } while (viewport()->rect().contains(QPoint(0, visualRect(firstIndex).y() + visualRect(firstIndex).height() + 1 ))) {
        firstIndex = indexAt(QPoint(0, visualRect(firstIndex).y() + visualRect(firstIndex).height() + 1 ));
        myList << firstIndex;
      }
      qDebug() << myList.count() << "are visible";
    }
};

#include "main.moc"

int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  ListView window;
  window.resize(100, 50);
  window.show();
  return app.exec();

}
```

Title: QListView max number of items in view

Body:
I need to calculate max number of items in current view of QListView.
I wrote code like this:

void MyListView::resizeEvent(QResizeEvent *event)
{
    QListView::resizeEvent(event);

    QFontMetrics fm (this->font());
    int fontHeight = fm.lineSpacing();

    QRect cr = contentsRect();
    int windowHeight = cr.bottom() - cr.top();

    int maxItemsCount = windowHeight / fontHeight;
    qDebug()<<"max items in view: "<< maxItemsCount;

}

but calculated max number of items is is incorrect.
E.g. in case of my window height and font height I get 32 max items in view when in fact current view has 28 items. Perhaps someone can suggest something, how to calculate it properly?

Body:
My idea is to use QListView::indexAt() (inherited from QAbstractView) to obtain the row index for

the top-left corner

the bottom-left corner

of the list view viewport and determining the number of visible items by difference of them.

To check this out, I made an MCVE testQListViewNumVisibleItems.cc:

// Qt header:
#include <QtWidgets>

class ListWidget: public QListWidget {

  public:
    ListWidget(QWidget *pQParent = nullptr): QListWidget(pQParent) { }
    virtual ~ListWidget() = default;
    ListWidget(const ListWidget&) = delete;
    ListWidget& operator=(const ListWidget&) = delete;

    int getNumVisibleItems() const
    {
      const QSize size = viewport()->size();
      const QModelIndex qMIdx0 = indexAt(QPoint(0, 0));
      const QModelIndex qMIdx1 = indexAt(QPoint(0, size.height() - 1));
      //qDebug() << "qMIdx0:" << qMIdx0 << "qMIdx1:" << qMIdx1;
      return qMIdx0.isValid()
        ? (qMIdx1.isValid() ? qMIdx1.row() : count()) - qMIdx0.row()
        : 0;
    }
};

const int MaxItems = 20;

// main application
int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  ListWidget qLst;
  qLst.resize(200, 200);
  qLst.show();
  // timer to populate list view
  using namespace std::chrono_literals;
  QTimer qTimer;
  qTimer.setInterval(1000ms);
  // install signal handlers
  int n = 0;
  QObject::connect(&qTimer, &QTimer::timeout,
    [&]() {
      qLst.addItem(QString("item %0").arg(++n));
      qDebug() << "Visible items:" << qLst.getNumVisibleItems();
      if (n >= MaxItems) qTimer.stop();
    });
  // runtime loop
  qTimer.start();
  return app.exec();
}

and a CMakeLists.txt:

project(QListViewNumVisibleItems)

cmake_minimum_required(VERSION 3.10.0)

set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

find_package(Qt5Widgets CONFIG REQUIRED)

include_directories("${CMAKE_SOURCE_DIR}")

add_executable(testQListViewNumVisibleItems testQListViewNumVisibleItems.cc)

target_link_libraries(testQListViewNumVisibleItems Qt5::Widgets)

built and tested in VS2017 on Windows 10:

After having implemented what came in my mind, I googled a bit to possibly see other approaches. (I admit I should've done before.)

Thereby I found the following possible duplicate:

SO: Simple way to get all visible items in the QListView

The accepted answer doesn't contain much more than the hint for indexAt and a link to a Qt-FAQ article:

How can i get hold of all of the visible items in my QListView?

In order to get hold of the visible items in a QListView http://doc.qt.io/qt-5/qlistview.html, then you can iterate over them using indexAt() http://doc.qt.io/qt-5/qlistview.html#indexAt. You can get hold of the first visible item using indexAt(QPoint(0, 0)), then in order to get the index at the next position then use visualRect() http://doc.qt.io/qt-5/qlistview.html#visualRect to find out what your next call to itemAt() should be. This position would be:

visualRect.y() + visualRect.height() + 1 effectively.

See the following example for an illustration:

#include <QtGui>
QList <QModelIndex>myList;

class ListView : public QListView
{
  Q_OBJECT
public:
  ListView()
  {
    QStringListModel *myModel = new QStringListModel(this);
    QStringList list;
    list << "a" << "b" <<"c" <<"d" <<"e" <<"f" <<"g" <<"h" <<"i" <<"j" <<"k";
    myModel->setStringList(list);
    setModel(myModel);
    QTimer::singleShot(3000, this, SLOT(test1()));
  }
  public slots:
    void test1()
    {

      QModelIndex firstIndex = indexAt(QPoint(0, 0));
      if (firstIndex.isValid()) {
        myList << firstIndex;
      } while (viewport()->rect().contains(QPoint(0, visualRect(firstIndex).y() + visualRect(firstIndex).height() + 1 ))) {
        firstIndex = indexAt(QPoint(0, visualRect(firstIndex).y() + visualRect(firstIndex).height() + 1 ));
        myList << firstIndex;
      }
      qDebug() << myList.count() << "are visible";
    }
};

#include "main.moc"

int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  ListView window;
  window.resize(100, 50);
  window.show();
  return app.exec();

}


问:
React Redux - How to do a proper loading screen using React and Redux on url change
I am working on a web app that uses React + Redux. However, I am struggling with the loading screens. Basically, my initial state for the redux store is this.

```<code>const initialState = {
    project: {},
    projects: [],
    customers: [],
    vendors: [],
    customer: {},
    vendor: {},
    loading: false
};
</code>```

An example of one of my reducers is this

```<code>const fetchSalesProject = (state, action) => {
    return updateObject(state, {
        project: action.payload,
        loading: false
    });
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case actionTypes.FETCH_SALES_PROJECT: return fetchSalesProject(state, action);
    default:
        return state;
</code>```

where updateObject is this

```<code>export const updateObject = (oldObject, updatedProperties) => {
    return {
        ...oldObject,
        ...updatedProperties
    }
}
</code>```

here are my actions (axiosInstance is just a custom addon to axios to include the necessary headers for authentication, but works exactly the same like a normal axios api call)

```<code>export const fetchSalesProject = (id) => (dispatch) => {
    axiosInstance
        .get(`/sales-project/detail/${id}/`)
        .then((res) => {
            dispatch({
                type: FETCH_SALES_PROJECT,
                payload: res.data,
            });
        })
        .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)));
};

export const showLoader = (area) => (dispatch) => {
    dispatch({
        type: SHOW_LOADER,
        area: area ? area : true
    });
};
</code>```

where the param area is just in the case where loading is meant to be rendered only on a specific area on the page (not relevant for this question hence when showLoader is called, no params would be passed in and hence the area would be set to true for this question)

this is my component

```<code>componentDidMount() {
    this.props.showLoader()
    this.props.fetchSalesProject(this.props.match.params.id)
};
</code>```

this is my mapStateToProps

```<code>const mapStateToProps = state => ({
     project: state.api.project,
     loading: state.api.loading
})
</code>```

this is my conditional rendering

```<code>render() {
    return (
        !this.props.loading ?
            {... whatever content within my page }
        : { ...loading screen }
</code>```

Basically, the issue I am facing is that, when i first load this component, there would be an error, as my this.props.project would be an empty {} (due to initialState). The reason why is that before the showLoader action is dispatched fully by componentDidMount, the component renders, and hence since this.props.loading is still set to the initialState of false, the conditional rendering passes through and the this.props.project would be rendered (however since it is empty, the various keys that I try to access within the rendering would be undefined hence throwing an error).

I tried various methods to try to overcome this, but none seem like an optimum solution. For example, I have tried to set the initialState of loading to an arbitary number, like eg. 0, and only render the page when this.props.loading === false, which is only after the data is fetched. However, the issue arises when I go onto a new page, like for example, another component called CustomerDetail. When that component is mounted, this.props.loading would be false and not 0, as it was previously manipulated by the previous component that I was on (SalesProjectDetail). Hence, that same error would come up as the conditional rendering passes through before any data was actually fetched.

Another method I tried was to use component states to handle the conditional rendering. For example, I only set a component state of done : true only after all the dispatches are completed. However, I felt like it was not good practice to mix component states and a state management system like Redux, and hence was hoping to see if there are any solutions to my problem that uses Redux only.

I am looking for a solution to my problem, which is to only render the contents only after the data has been fetched, and before it is fetched, a loading screen should be rendered. All help is appreciated, and I am new to React and especially Redux, so do guide me on the correct path if I am misguided on how this problem should be approached. Thanks all in advance!

答:
there can be more ways to do it. But to go ahead with your scheme of local state...

I think there is no problem if you use local state to keep track of load complete or underway.
You can have a local state variable as you already said.
Before dispatch set that variable to loading=true then use async/await to fetch data and afterwards set loading back to false.

I think it will work for you.

Body:
I am working on a web app that uses React + Redux. However, I am struggling with the loading screens. Basically, my initial state for the redux store is this.

const initialState = {
    project: {},
    projects: [],
    customers: [],
    vendors: [],
    customer: {},
    vendor: {},
    loading: false
};

An example of one of my reducers is this

const fetchSalesProject = (state, action) => {
    return updateObject(state, {
        project: action.payload,
        loading: false
    });
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case actionTypes.FETCH_SALES_PROJECT: return fetchSalesProject(state, action);
    default:
        return state;

where updateObject is this

export const updateObject = (oldObject, updatedProperties) => {
    return {
        ...oldObject,
        ...updatedProperties
    }
}

here are my actions (axiosInstance is just a custom addon to axios to include the necessary headers for authentication, but works exactly the same like a normal axios api call)

export const fetchSalesProject = (id) => (dispatch) => {
    axiosInstance
        .get(`/sales-project/detail/${id}/`)
        .then((res) => {
            dispatch({
                type: FETCH_SALES_PROJECT,
                payload: res.data,
            });
        })
        .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)));
};

export const showLoader = (area) => (dispatch) => {
    dispatch({
        type: SHOW_LOADER,
        area: area ? area : true
    });
};

where the param area is just in the case where loading is meant to be rendered only on a specific area on the page (not relevant for this question hence when showLoader is called, no params would be passed in and hence the area would be set to true for this question)

this is my component

componentDidMount() {
    this.props.showLoader()
    this.props.fetchSalesProject(this.props.match.params.id)
};

this is my mapStateToProps

const mapStateToProps = state => ({
     project: state.api.project,
     loading: state.api.loading
})

this is my conditional rendering

render() {
    return (
        !this.props.loading ?
            {... whatever content within my page }
        : { ...loading screen }

Basically, the issue I am facing is that, when i first load this component, there would be an error, as my this.props.project would be an empty {} (due to initialState). The reason why is that before the showLoader action is dispatched fully by componentDidMount, the component renders, and hence since this.props.loading is still set to the initialState of false, the conditional rendering passes through and the this.props.project would be rendered (however since it is empty, the various keys that I try to access within the rendering would be undefined hence throwing an error).

I tried various methods to try to overcome this, but none seem like an optimum solution. For example, I have tried to set the initialState of loading to an arbitary number, like eg. 0, and only render the page when this.props.loading === false, which is only after the data is fetched. However, the issue arises when I go onto a new page, like for example, another component called CustomerDetail. When that component is mounted, this.props.loading would be false and not 0, as it was previously manipulated by the previous component that I was on (SalesProjectDetail). Hence, that same error would come up as the conditional rendering passes through before any data was actually fetched.

Another method I tried was to use component states to handle the conditional rendering. For example, I only set a component state of done : true only after all the dispatches are completed. However, I felt like it was not good practice to mix component states and a state management system like Redux, and hence was hoping to see if there are any solutions to my problem that uses Redux only.

I am looking for a solution to my problem, which is to only render the contents only after the data has been fetched, and before it is fetched, a loading screen should be rendered. All help is appreciated, and I am new to React and especially Redux, so do guide me on the correct path if I am misguided on how this problem should be approached. Thanks all in advance!


问:
jQuery: selecting each td in a tr
I need a way to interact with each td element in a tr.

To elaborate, I would like to access the first table row, then the first column, then the second column, etc. Then move onto the second row and repeat the process.

Something like this (pseudo-code):

```<code>for each row in table
{
  for each column in row
  {
    do cool things
  }
}
</code>```

jQuery:

```<code>$('#tblNewAttendees tr').each(function() {
  alert('tr');
  //Cool jquery magic that lets me iterate over all the td only in this row
  $(magicSelector).each(function(){
    alert('hi');
  });

});
</code>```

HTML:

```<code><table>
     <thead>
          <th>someHeader</th>
     </thead>
     <tbody>
          <tr>
               <td>want to grab this first</td>
               <td> this second </td>
          </tr>
          <tr>
               <td>this third</td>
               <td>this fourth</td>
          </tr>
     </tbody>
</table>
</code>```

答:
```<code>$('#tblNewAttendees tbody tr).each((index, tr)=> {
        //console.log(tr);
        $(tr).children('td').each ((index, td) => {
            console.log(td);

        });

    });
</code>```

You can use this tr and td parameter also.

Title: jQuery: selecting each td in a tr

Body:
I need a way to interact with each td element in a tr.

To elaborate, I would like to access the first table row, then the first column, then the second column, etc. Then move onto the second row and repeat the process.

Something like this (pseudo-code):

for each row in table
{
  for each column in row
  {
    do cool things
  }
}

jQuery:

$('#tblNewAttendees tr').each(function() {
  alert('tr');
  //Cool jquery magic that lets me iterate over all the td only in this row
  $(magicSelector).each(function(){
    alert('hi');
  });

});

HTML:

          someHeader

               want to grab this first
                this second

               this third
               this fourth

Body:
$('#tblNewAttendees tbody tr).each((index, tr)=> {
        //console.log(tr);
        $(tr).children('td').each ((index, td) => {
            console.log(td);

        });

    });

You can use this tr and td parameter also.


问:
Access host resources from a kubernetes cluster service when minikube started with DOCKER vm driver
I have been able to successfully provision services inside a kubernetes minikube cluster to connect to services such as cassandra, kafka, etc installed on the host machine so far when I started the minikube cluster with the virutalbox vm.

```<code>minikube start --driver=virtualbox
</code>```

For this I had to defined k8s manifest say fror cassandra endpoint with an IP address of the host machine identified from within the minikube cluster via following command as suggested here:

```<code>minikube ssh "route -n | grep ^0.0.0.0 | awk '{ print \$2 }'"
</code>```

But when I start the minikube cluster with docker as VM driver, I am not able to figure out the ip address of the host machine as identified from inside the cluster because the command to fetch the same doesn't work.

```<code>minikube start --driver=docker

minikube ssh "route -n | grep ^0.0.0.0 | awk '{ print \$2 }'"
bash: route: command not found
</code>```

Please suggest how could this ip address be retrived?

答:
I think you overcomplicate things when it is not needed.
Since you want to run a testing environment (minikube suggests that) you should always want to start minikube with:

```<code>minikube start --driver=docker
</code>```

Now the IP address of the Kubernetes cluster can be found simply by typing:

```<code>minikube ip
</code>```

Or:

```<code>kubectl cluster-info | grep master
</code>```

This command will show you the ip address that Kubernetes is running from, and the port (usually 6443).

Body:
I have been able to successfully provision services inside a kubernetes minikube cluster to connect to services such as cassandra, kafka, etc installed on the host machine so far when I started the minikube cluster with the virutalbox vm.

minikube start --driver=virtualbox

For this I had to defined k8s manifest say fror cassandra endpoint with an IP address of the host machine identified from within the minikube cluster via following command as suggested here:

minikube ssh "route -n | grep ^0.0.0.0 | awk '{ print \$2 }'"

But when I start the minikube cluster with docker as VM driver, I am not able to figure out the ip address of the host machine as identified from inside the cluster because the command to fetch the same doesn't work.

minikube start --driver=docker

minikube ssh "route -n | grep ^0.0.0.0 | awk '{ print \$2 }'"
bash: route: command not found

Please suggest how could this ip address be retrived?

Body:
I think you overcomplicate things when it is not needed.
Since you want to run a testing environment (minikube suggests that) you should always want to start minikube with:

minikube start --driver=docker

Now the IP address of the Kubernetes cluster can be found simply by typing:

minikube ip

Or:

kubectl cluster-info | grep master

This command will show you the ip address that Kubernetes is running from, and the port (usually 6443).


问:
Godot - Confused Tilemap Quadrant Size
Recently my simple tilemap game has a performance drop when export to android, due to tilemap settings. My game details are as followed:

tile size : 64 x 64

display resolution : 1080 x 1920

tilemap size : 30 x 14 tiles

quadrant size : 16 (default)

When i set the quadrant size to 1, the game did run smoother in my android device.

However, I am having a difficulty in understanding the concept of quadrant size. From this godot tutorial page, it mentioned that:
"Quadrant size is a tuning value, which means that the engine will draw and cull the tilemap in blocks of 16x16 tiles" (given quadrant size is 16)
It make sense to me to say that the engine will draw 16 x 16 tiles and make the game visible to players.

But my question arise when my game is still fully draw (aka visible) after i set the quadrant size to 1? According to my understanding, quadrant_size of 1 will only makes the engine draw 1 x 1 tiles. Since one tile in my game has only 64 x 64 px, shouldn't only 64 x 64 px of my game world being draw and visible to players?

I also did reading about quadrant_size here, but still don't understand how to get a best quadrant size for my situation. Perhaps, i may have an incorrect concept of quadrant size in tilemap settings.

To summarize my question, what is quadrant size in tilemap and how to calculate the optimum quadrant size for any game settings?

Thank you for spending your precious time reading my question.

答:
quadrant_size is an internal optimization technique. Different values may be faster than others depending on the device and project -- there's no value that will be always faster or slower than another. If you're not running into performance issues, leave it at the default. If you do, try to tweak it starting from 1 (which has been known to improve performance on some devices).

It won't change what you see on your screen in any way.

Also, Godot 3.2.2 will support 2D batching which should greatly speed up TileMap rendering, especially on mobile devices.

Title: Godot - Confused Tilemap Quadrant Size


问:
Having difficulty with re-installing R in Ubuntu 18.04
Very recently I shifted to Ubuntu from Windows and downloaded R-base (3.4.4) and R studio. However, some packages (car, ROCR etc) were not available and hence I tried to update R. Because of error messages, I finally tried to uninstall and remove R and then install it again.

I tried

```<code>sudo apt-get upgrade
sudo apt install r-base
</code>```

However, it is showing me error message like,

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 r-base : Depends: r-recommended (= 3.6.2.20200221-1~ubuntu18.04.1~ppa1) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

So basically right now, I have no R-base installed.

I tried to remove R-base.

```<code>sudo apt-get remove r-base
</code>```

And all I am getting is-

```<code>    Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'r-base' is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
</code>```

I am a beginner in both R and Linux. I need your valuable suggestions.
Thanks in advance.

答:
If you are using Ubuntu 18.04, please follow these steps if you are using your local machine of your own. (If your are working in any office environment please setup proxy and follow these steps)

1) Let’s first add the relevant GPG key

```<code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
</code>```

2) Add the R Repository

```<code>sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran40/'
</code>```

3) Update Package Lists

```<code>sudo apt update
</code>```

4)  Install R

```<code>sudo apt install r-base
</code>```

5) Test Install

```<code>sudo -i R
</code>```

6) Installing R Packages from CRAN

```<code>install.packages('dplyr')
</code>```

Body:
Very recently I shifted to Ubuntu from Windows and downloaded R-base (3.4.4) and R studio. However, some packages (car, ROCR etc) were not available and hence I tried to update R. Because of error messages, I finally tried to uninstall and remove R and then install it again.

I tried

sudo apt-get upgrade
sudo apt install r-base

However, it is showing me error message like,

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 r-base : Depends: r-recommended (= 3.6.2.20200221-1~ubuntu18.04.1~ppa1) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

So basically right now, I have no R-base installed.

I tried to remove R-base.

sudo apt-get remove r-base

And all I am getting is-

    Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'r-base' is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

I am a beginner in both R and Linux. I need your valuable suggestions.
Thanks in advance.

Body:
If you are using Ubuntu 18.04, please follow these steps if you are using your local machine of your own. (If your are working in any office environment please setup proxy and follow these steps)

1) Let’s first add the relevant GPG key

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9

2) Add the R Repository

sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran40/'

3) Update Package Lists

sudo apt update

4)  Install R

sudo apt install r-base

5) Test Install

sudo -i R

6) Installing R Packages from CRAN

install.packages('dplyr')


问:
Airflow start from first task
So im creating a DAG for daily backup,restore and delete, with branching

do daily backup restore and delete (always runs)

if its saturday do weekly backup,restore and delete

if its first day of month do montly backup,restore and delete

here is the cycle

```<code>    daily_backup_op.set_downstream(daily_restore_op)
    daily_restore_op.set_downstream(daily_delete_op)

    daily_delete_op.set_downstream(branching_op)
    branching_op.set_downstream([weekly_backup_op,monthly_backup_op,monthly_weekly_backup_op,end_task_op])

    weekly_backup_op.set_downstream(weekly_restore_op)
    weekly_restore_op.set_downstream(weekly_delete_op)

    monthly_backup_op.set_downstream(monthly_restore_op)
    monthly_restore_op.set_downstream(monthly_delete_op)

    monthly_weekly_backup_op.set_downstream(monthly_weekly_restore_op)
    monthly_weekly_restore_op.set_downstream(monthly_weekly_delete_op)

    weekly_delete_op.set_downstream(end_task_op)
    monthly_delete_op.set_downstream(end_task_op)
    monthly_weekly_delete_op.set_downstream(end_task_op)
</code>```

when i test it for some reason it and it hits "else: return 'end'" , it wont reach the end_task_op, instead it keep restarting on starting from daily_backup_op

here is the branching code

```<code>def backup_restore_condition():
    if((DATE_TODAY == get_first_day_of_month()) and (get_weekday_number() == SATURDAY_WEEKDAY_NUMBER)):
        return 'monthly_weekly_backup'
    elif(DATE_TODAY == get_first_day_of_month()):
        return 'monthly_backup'
    elif(get_weekday_number() == SATURDAY_WEEKDAY_NUMBER):
        return 'weekly_backup'
    else:
        return 'end'
</code>```

for the end_task_op

```<code>end_task_op = PythonOperator(
        task_id='end',
        python_callable=end_task
    )
</code>```

```<code>def end_task():
    print("task end succesfully")
</code>```

full cycle image
DAG image

am i missing something?

答:
In end_task_op, you have to define a trigger_rule as NONE_FAILED which signifies 'run the task when all the parent task are succeeded or skipped'.
As Javier suggested, its better to use bitshift composition as it increases readability and reduces lines of code. Please see the DAG below which works in all the conditions:</p>

```<code>from airflow import DAG
from airflow.operators.python_operator import PythonOperator, BranchPythonOperator
from airflow.utils.trigger_rule import TriggerRule
import datetime as dt

args = {
    'owner': 'airflow',
    'start_date': '2020-06-02'
}

dag = DAG(
    'backup_restore_delete_db',
    schedule_interval="@daily",
    default_args=args
)
def daily_backup():
    print('daily backup')
def daily_restore():
    print('restore daily backup')
def daily_delete():
    print('delete 7 days old backup')
def weekly_backup():
    print('weekly backup')
def weekly_restore():
    print('restore weekly backup')
def weekly_delete():
    print('delete 7 week old backup')
def monthly_backup():
    print('monthly backup')
def monthly_restore():
    print('restore monthly backup')
def monthly_delete():
    print('delete 7 month old backup')
def monthly_weekly_backup():
    print('monthlyweekly backup')
def monthly_weekly_restore():
    print('restore monthlyweekly backup')
def monthly_weekly_delete():
    print('delete 7 monthlyweekly old backup')
def end_task():
    print("task end succesfully")

def branch_func():
    if (dt.date.today().strftime("%d") == "01") and (dt.date.today().isoweekday() == 6):
        return 'monthly_weekly_backup'
    elif (dt.date.today().strftime("%d") == "01"):
        return 'monthly_backup'
    elif (dt.date.today().isoweekday() == 6):
        return 'weekly_backup'
    else:
        return 'end_task'

daily_backup_op = PythonOperator(
        task_id='daily_backup',
        python_callable=daily_backup,
        dag=dag
    )
weekly_backup_op = PythonOperator(
        task_id='weekly_backup',
        python_callable=weekly_backup,
        dag=dag
    )

monthly_backup_op = PythonOperator(
        task_id='monthly_backup',
        python_callable=monthly_backup,
        dag=dag
    )
daily_restore_op = PythonOperator(
        task_id='daily_restore',
        python_callable=daily_restore,
        dag=dag
    )

weekly_restore_op = PythonOperator(
        task_id='weekly_restore',
        python_callable=weekly_restore,
        dag=dag
    )

monthly_restore_op = PythonOperator(
        task_id='monthly_restore',
        python_callable=monthly_restore,
        dag=dag
    )

daily_delete_op = PythonOperator(
        task_id='daily_delete',
        python_callable=daily_delete,
        dag=dag
    )

weekly_delete_op = PythonOperator(
        task_id='weekly_delete',
        python_callable=weekly_delete,
        dag=dag
    )

monthly_delete_op = PythonOperator(
        task_id='monthly_delete',
        python_callable=monthly_delete,
        dag=dag
    )

monthly_weekly_backup_op = PythonOperator(
        task_id='monthly_weekly_backup',
        python_callable=monthly_weekly_backup,
        dag=dag
    )

monthly_weekly_restore_op = PythonOperator(
        task_id='monthly_weekly_restore',
        python_callable=monthly_weekly_restore,
        dag=dag
    )

monthly_weekly_delete_op = PythonOperator(
        task_id='monthly_weekly_delete',
        python_callable=monthly_weekly_delete,
        dag=dag
    )

end_task_op = PythonOperator(
        task_id='end_task',
        python_callable=end_task,
        trigger_rule=TriggerRule.NONE_FAILED,
        dag=dag
    )

branching_op = BranchPythonOperator(
        task_id='branch_func',
        python_callable=branch_func,
        dag=dag
    )

daily_backup_op >> daily_restore_op >> daily_delete_op >> branching_op
branching_op >> monthly_weekly_backup_op >> monthly_weekly_restore_op >> monthly_weekly_delete_op >> end_task_op
branching_op >> monthly_backup_op >> monthly_restore_op >> monthly_delete_op >> end_task_op
branching_op >> weekly_backup_op >> weekly_restore_op >> weekly_delete_op >> end_task_op
branching_op >> end_task_op
</code>```

Title: Airflow start from first task

Body:
So im creating a DAG for daily backup,restore and delete, with branching

do daily backup restore and delete (always runs)

if its saturday do weekly backup,restore and delete

if its first day of month do montly backup,restore and delete

here is the cycle

    daily_backup_op.set_downstream(daily_restore_op)
    daily_restore_op.set_downstream(daily_delete_op)

    daily_delete_op.set_downstream(branching_op)
    branching_op.set_downstream([weekly_backup_op,monthly_backup_op,monthly_weekly_backup_op,end_task_op])

    weekly_backup_op.set_downstream(weekly_restore_op)
    weekly_restore_op.set_downstream(weekly_delete_op)

    monthly_backup_op.set_downstream(monthly_restore_op)
    monthly_restore_op.set_downstream(monthly_delete_op)

    monthly_weekly_backup_op.set_downstream(monthly_weekly_restore_op)
    monthly_weekly_restore_op.set_downstream(monthly_weekly_delete_op)

    weekly_delete_op.set_downstream(end_task_op)
    monthly_delete_op.set_downstream(end_task_op)
    monthly_weekly_delete_op.set_downstream(end_task_op)

when i test it for some reason it and it hits "else: return 'end'" , it wont reach the end_task_op, instead it keep restarting on starting from daily_backup_op

here is the branching code

def backup_restore_condition():
    if((DATE_TODAY == get_first_day_of_month()) and (get_weekday_number() == SATURDAY_WEEKDAY_NUMBER)):
        return 'monthly_weekly_backup'
    elif(DATE_TODAY == get_first_day_of_month()):
        return 'monthly_backup'
    elif(get_weekday_number() == SATURDAY_WEEKDAY_NUMBER):
        return 'weekly_backup'
    else:
        return 'end'

for the end_task_op

end_task_op = PythonOperator(
        task_id='end',
        python_callable=end_task
    )

def end_task():
    print("task end succesfully")

full cycle image
DAG image

am i missing something?

Body:
In end_task_op, you have to define a trigger_rule as NONE_FAILED which signifies 'run the task when all the parent task are succeeded or skipped'.
As Javier suggested, its better to use bitshift composition as it increases readability and reduces lines of code. Please see the DAG below which works in all the conditions:

from airflow import DAG
from airflow.operators.python_operator import PythonOperator, BranchPythonOperator
from airflow.utils.trigger_rule import TriggerRule
import datetime as dt

args = {
    'owner': 'airflow',
    'start_date': '2020-06-02'
}

dag = DAG(
    'backup_restore_delete_db',
    schedule_interval="@daily",
    default_args=args
)
def daily_backup():
    print('daily backup')
def daily_restore():
    print('restore daily backup')
def daily_delete():
    print('delete 7 days old backup')
def weekly_backup():
    print('weekly backup')
def weekly_restore():
    print('restore weekly backup')
def weekly_delete():
    print('delete 7 week old backup')
def monthly_backup():
    print('monthly backup')
def monthly_restore():
    print('restore monthly backup')
def monthly_delete():
    print('delete 7 month old backup')
def monthly_weekly_backup():
    print('monthlyweekly backup')
def monthly_weekly_restore():
    print('restore monthlyweekly backup')
def monthly_weekly_delete():
    print('delete 7 monthlyweekly old backup')
def end_task():
    print("task end succesfully")

def branch_func():
    if (dt.date.today().strftime("%d") == "01") and (dt.date.today().isoweekday() == 6):
        return 'monthly_weekly_backup'
    elif (dt.date.today().strftime("%d") == "01"):
        return 'monthly_backup'
    elif (dt.date.today().isoweekday() == 6):
        return 'weekly_backup'
    else:
        return 'end_task'

daily_backup_op = PythonOperator(
        task_id='daily_backup',
        python_callable=daily_backup,
        dag=dag
    )
weekly_backup_op = PythonOperator(
        task_id='weekly_backup',
        python_callable=weekly_backup,
        dag=dag
    )

monthly_backup_op = PythonOperator(
        task_id='monthly_backup',
        python_callable=monthly_backup,
        dag=dag
    )
daily_restore_op = PythonOperator(
        task_id='daily_restore',
        python_callable=daily_restore,
        dag=dag
    )

weekly_restore_op = PythonOperator(
        task_id='weekly_restore',
        python_callable=weekly_restore,
        dag=dag
    )

monthly_restore_op = PythonOperator(
        task_id='monthly_restore',
        python_callable=monthly_restore,
        dag=dag
    )

daily_delete_op = PythonOperator(
        task_id='daily_delete',
        python_callable=daily_delete,
        dag=dag
    )

weekly_delete_op = PythonOperator(
        task_id='weekly_delete',
        python_callable=weekly_delete,
        dag=dag
    )

monthly_delete_op = PythonOperator(
        task_id='monthly_delete',
        python_callable=monthly_delete,
        dag=dag
    )

monthly_weekly_backup_op = PythonOperator(
        task_id='monthly_weekly_backup',
        python_callable=monthly_weekly_backup,
        dag=dag
    )

monthly_weekly_restore_op = PythonOperator(
        task_id='monthly_weekly_restore',
        python_callable=monthly_weekly_restore,
        dag=dag
    )

monthly_weekly_delete_op = PythonOperator(
        task_id='monthly_weekly_delete',
        python_callable=monthly_weekly_delete,
        dag=dag
    )

end_task_op = PythonOperator(
        task_id='end_task',
        python_callable=end_task,
        trigger_rule=TriggerRule.NONE_FAILED,
        dag=dag
    )

branching_op = BranchPythonOperator(
        task_id='branch_func',
        python_callable=branch_func,
        dag=dag
    )

daily_backup_op >> daily_restore_op >> daily_delete_op >> branching_op
branching_op >> monthly_weekly_backup_op >> monthly_weekly_restore_op >> monthly_weekly_delete_op >> end_task_op
branching_op >> monthly_backup_op >> monthly_restore_op >> monthly_delete_op >> end_task_op
branching_op >> weekly_backup_op >> weekly_restore_op >> weekly_delete_op >> end_task_op
branching_op >> end_task_op


问:
java: set page range for print dialog
I'm just starting to learn how to print a window in Java/Swing.
(edit: just found the Java Printing Guide)

When I do this:

```<code>protected void doPrint() {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(this);
    boolean ok = job.printDialog();
    if (ok) {
        try {
            job.print();
        }
        catch (PrinterException ex) {
            ex.printStackTrace();
        }
        finally {

        }
    }
}
</code>```

I get this printer dialog (on Windows XP):

How do I change the page range so it's not 1-9999?

edit: using Pageable/Book to set the page range (as @t_barbz helpfully points out) requires a PageFormat, in which case I have a catch-22, since I'd like the Print dialog to select that, and I don't seem to get a return value from the print dialog.

答:
For the page range i believe you need to use the PrinterJob's setPageable(Pageable document) method. Looks like it should do the trick.</p>

```<code>protected void doPrint() {
PrinterJob job = PrinterJob.getPrinterJob();
Book book = new Book();
book.append(this, job.defaultPage());
printJob.setPageable(book);

boolean ok = job.printDialog();
if (ok) {
    try {
        job.print();
    }
    catch (PrinterException ex) {
        ex.printStackTrace();
    }
    finally {

    }
}
}
</code>```

Title: java: set page range for print dialog

Body:
I'm just starting to learn how to print a window in Java/Swing.
(edit: just found the Java Printing Guide)

When I do this:

protected void doPrint() {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(this);
    boolean ok = job.printDialog();
    if (ok) {
        try {
            job.print();
        }
        catch (PrinterException ex) {
            ex.printStackTrace();
        }
        finally {

        }
    }
}

I get this printer dialog (on Windows XP):

How do I change the page range so it's not 1-9999?

edit: using Pageable/Book to set the page range (as @t_barbz helpfully points out) requires a PageFormat, in which case I have a catch-22, since I'd like the Print dialog to select that, and I don't seem to get a return value from the print dialog.

Body:
For the page range i believe you need to use the PrinterJob's setPageable(Pageable document) method. Looks like it should do the trick.

protected void doPrint() {
PrinterJob job = PrinterJob.getPrinterJob();
Book book = new Book();
book.append(this, job.defaultPage());
printJob.setPageable(book);

boolean ok = job.printDialog();
if (ok) {
    try {
        job.print();
    }
    catch (PrinterException ex) {
        ex.printStackTrace();
    }
    finally {

    }
}
}


问:
WPF and Windows 10 crash
We have a WPF app that need to stay opened for a longer period of time (overnight) with different users that log on and off to the respective PC.

[Update] The WPF app uses Single Instance technique from here: http://blogs.microsoft.co.il/blogs/arik/SingleInstance.cs.txt
The single instance feature is not a cause for the bug

There is a strange crash happening only in the following situation:

OS is Windows 10

The following sequence of user sign in / sign off must happen:

Account A is starting the app and logs off or locks the PC.
Account B signs in during the night, works on the PC for a while and then logs off.
Account A signs in again in the morning. The app runs but is the UI is frozen/minimized. When clicked/ tried to be resized, the following error occurs:

```<code>   System.OutOfMemoryException: Insufficient memory to continue the execution of the program.
   at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
   at System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean enableRenderTarget, Nullable`1 channelSet)
   at System.Windows.Interop.HwndTarget.UpdateWindowPos(IntPtr lParam)
   at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
</code>```

I already reviewed these posts

win32 window in WPF

https://social.msdn.microsoft.com/Forums/vstudio/en-US/a29b9b58-376c-49b7-a6b7-fba6a510524a/wpf-and-windows-10-crash?forum=wpf

http://www.actiprosoftware.com/community/thread/3849/minimize-navbar-floating-window-size-out-of-m

I tried the suggestions from the above posts with no luck.

Also, I cannot reproduce the problem consistently. It seem that some time needs to pass between the logins so that the problem to appear.

Thanks for any suggestion that you may have.

答:
Seems this is known WPF bug: https://github.com/dotnet/wpf/issues/439
No solution yet on June 3, 2020.</p>

Title: WPF and Windows 10 crash

Body:
We have a WPF app that need to stay opened for a longer period of time (overnight) with different users that log on and off to the respective PC.

[Update] The WPF app uses Single Instance technique from here: http://blogs.microsoft.co.il/blogs/arik/SingleInstance.cs.txt
The single instance feature is not a cause for the bug

There is a strange crash happening only in the following situation:

OS is Windows 10

The following sequence of user sign in / sign off must happen:

Account A is starting the app and logs off or locks the PC.
Account B signs in during the night, works on the PC for a while and then logs off.
Account A signs in again in the morning. The app runs but is the UI is frozen/minimized. When clicked/ tried to be resized, the following error occurs:

   System.OutOfMemoryException: Insufficient memory to continue the execution of the program.
   at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
   at System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean enableRenderTarget, Nullable`1 channelSet)
   at System.Windows.Interop.HwndTarget.UpdateWindowPos(IntPtr lParam)
   at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

I already reviewed these posts

win32 window in WPF

https://social.msdn.microsoft.com/Forums/vstudio/en-US/a29b9b58-376c-49b7-a6b7-fba6a510524a/wpf-and-windows-10-crash?forum=wpf

http://www.actiprosoftware.com/community/thread/3849/minimize-navbar-floating-window-size-out-of-m

I tried the suggestions from the above posts with no luck.

Also, I cannot reproduce the problem consistently. It seem that some time needs to pass between the logins so that the problem to appear.

Thanks for any suggestion that you may have.


Title: Query to join DateTimestamp column with another Table with StartDate and EndDate

Body:
I have below table with 3 column. Lets say table1 with the following data

+---------+-----------------------+----------+
| ID      | E_Date                | TimeDiff |
+---------+-----------------------+----------+
| 7390709 | 2020-03-26 22:25:30   | 456      |
+---------+-----------------------+----------+
| 7390707 | 2020-03-26 16:25:30   | 3        |
+---------+-----------------------+----------+
| 7390706 | 2020-03-26 19:25:30   | 3        |
+---------+-----------------------+----------+
| 7390701 | 2020-03-26 16:23:53   | 512419   |
+---------+-----------------------+----------+
| 7390696 | 2020-03-26 14:33:08   | 111034   |
+---------+-----------------------+----------+
| 7390681 | 2020-03-20   15:25:30 | 2        |
+---------+-----------------------+----------+
| 7390680 | 2020-03-20 16:25:30   | 63867    |
+---------+-----------------------+----------+
| 7390679 | 2020-03-20   13:25:30 | 63867    |
+---------+-----------------------+----------+
| 7390675 | 2020-03-20 12:30:46   | 63867    |
+---------+-----------------------+----------+

Another table with 4 columns, lets say table2 with following data

+-----------------------+---------------------+--------+------+
| Start_Date            | End_Date            | Typ_ID | Diff |
+-----------------------+---------------------+--------+------+
| 2020-03-26 18:00:01   | 2020-03-26 21:00:00 | 3      | 180  |
+-----------------------+---------------------+--------+------+
| 2020-03-26   13:40:01 | 2020-03-26 17:30:00 | 1      | 230  |
+-----------------------+---------------------+--------+------+
| 2020-03-26 10:30:01   | 2020-03-26 13:30:00 | 1      | 180  |
+-----------------------+---------------------+--------+------+
| 2020-03-26   06:10:01 | 2020-03-26 10:00:00 | 1      | 230  |
+-----------------------+---------------------+--------+------+
| 2020-03-20 18:00:01   | 2020-03-20 21:00:00 | 1      | 180  |
+-----------------------+---------------------+--------+------+
| 2020-03-20   13:40:01 | 2020-03-20 17:30:00 | 3      | 230  |
+-----------------------+---------------------+--------+------+
| 2020-03-20 10:30:01   | 2020-03-20 13:30:00 | 1      | 180  |
+-----------------------+---------------------+--------+------+
| 2020-03-20   06:10:01 | 2020-03-20 10:00:00 | 1      | 230  |
+-----------------------+---------------------+--------+------+

What I would like to achieve is check in Table2 for start_date and End_Date where typ_Id = 1 from Table1 where E_Date comes under in Table2 Start_Date and End_Date.

for ID 7390706, 7390681,7390680 the E_Date comes under the range in table2 Start_Date and End_Date where Typ_ID=3 and for ID 7390709 there is no Start_Date and End_Date exist so those rows has be excluded from the final result.

So the final table has to be like this.

+---------+-----------------------+----------+
| ID      | E_Date                | TimeDiff |
+---------+-----------------------+----------+
| 7390707 | 2020-03-26 16:25:30   | 3        |
+---------+-----------------------+----------+
| 7390701 | 2020-03-26 16:23:53   | 512419   |
+---------+-----------------------+----------+
| 7390696 | 2020-03-26 14:33:08   | 111034   |
+---------+-----------------------+----------+
| 7390679 | 2020-03-20   13:25:30 | 63867    |
+---------+-----------------------+----------+
| 7390675 | 2020-03-20 12:30:46   | 63867    |
+---------+-----------------------+----------+

I am still learning joins so any help will be appreciated.

http://sqlfiddle.com/#!18/6eb43

Body:
Try the following and here is the demo.

select
    id,
    e_date,
    timediff
from tableA
join tableB
on e_date between Start_Date and End_Date
where typ_id = 1

output:

| id      | e_date                   | timediff |
| ------- | ------------------------ | -------- |
| 7390707 | 2020-03-26 16:25:30      | 3        |
| 7390701 | 2020-03-26 16:23:53      | 512419   |
| 7390696 | 2020-03-26 14:33:08      | 111034   |
| 7390679 | 2020-03-20 13:25:30      | 63867    |
| 7390675 | 2020-03-20 12:30:46      | 63867    |